Skip to main content

euv_performance/suite/
fn.rs

1use super::*;
2
3/// Benchmarks fine-grained `Signal` updates propagating through a diamond `Memo` graph.
4///
5/// # Arguments
6///
7/// - `usize` - Number of signal updates to measure.
8///
9/// # Returns
10///
11/// - `BenchMetric` - Measured latency and throughput telemetry.
12#[must_use]
13pub fn bench_reactive_signals_and_memos(iterations: usize) -> BenchMetric {
14    reset_reactive_runtime();
15    let count: usize = iterations.max(1);
16    let source: Signal<i64> = Signal::new(0);
17    let left: Memo<i64> = Memo::new(move || source.get() + 1);
18    let right: Memo<i64> = Memo::new(move || source.get() * 2);
19    let sum: Memo<i64> = Memo::new(move || left.get() + right.get());
20    let start: Instant = Instant::now();
21    let mut checksum: i64 = 0;
22    for i in 1..=(count as i64) {
23        let _: bool = source.set(i);
24        checksum = checksum.wrapping_add(sum.get());
25    }
26    build_metric(
27        BENCH_REACTIVE_NAME,
28        count,
29        start.elapsed(),
30        format!("checksum={checksum}"),
31    )
32}
33
34/// Benchmarks O(1) `Selector<usize>` active-index switching across 1,000 tracked rows.
35///
36/// # Arguments
37///
38/// - `usize` - Number of active-row switches to measure.
39///
40/// # Returns
41///
42/// - `BenchMetric` - Measured latency and throughput telemetry.
43#[must_use]
44pub fn bench_selector_o1(iterations: usize) -> BenchMetric {
45    reset_reactive_runtime();
46    let count: usize = iterations.max(1);
47    let selected: Signal<usize> = Signal::new(0);
48    let selector: Selector<usize> = Selector::new(move || selected.get());
49    let start: Instant = Instant::now();
50    let mut hits: usize = 0;
51    for i in 0..count {
52        let key: usize = i % 1_000;
53        let _: bool = selected.set(key);
54        if selector.is_selected(key) {
55            hits += 1;
56        }
57    }
58    build_metric(
59        BENCH_SELECTOR_NAME,
60        count,
61        start.elapsed(),
62        format!("hits={hits}"),
63    )
64}
65
66/// Benchmarks retained layout engine clean-subtree caching across a 120-node UI tree.
67///
68/// # Arguments
69///
70/// - `usize` - Number of layout passes to measure.
71///
72/// # Returns
73///
74/// - `BenchMetric` - Measured latency and cache-hit telemetry.
75#[must_use]
76pub fn bench_layout_cache(iterations: usize) -> BenchMetric {
77    reset_reactive_runtime();
78    let count: usize = iterations.max(1);
79    let scene: SceneHandle = SceneHandle::new_tree();
80    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
81    let container: NodeId = with_context(ctx, || {
82        view! {
83            column {
84                style: {
85                    width: Length::Px(800.0)
86                    height: Length::Px(600.0)
87                    gap: SPACE_XS
88                }
89                for idx in 0..120usize {
90                    row {
91                        style: {
92                            width: Length::Percent(100.0)
93                            height: Length::Px(24.0)
94                        }
95                        text {
96                            { format!("{BENCH_ROW_LABEL} {idx}") }
97                        }
98                    }
99                }
100            }
101        }
102    });
103    scene.with_write(
104        |tree: &mut SceneTree| {
105            let root: NodeId = tree.get_root();
106            tree.replace_children(root, vec![container]);
107        },
108        (),
109    );
110    let mut engine: LayoutEngine = LayoutEngine::default();
111    let viewport: Size = Size::new(800.0, 600.0);
112    let _: LayoutStats = scene.with_write(
113        |tree: &mut SceneTree| engine.compute(tree, viewport),
114        LayoutStats::default(),
115    );
116    let start: Instant = Instant::now();
117    let mut cache_hits: usize = 0;
118    for _ in 0..count {
119        let stats: LayoutStats = scene.with_write(
120            |tree: &mut SceneTree| engine.compute(tree, viewport),
121            LayoutStats::default(),
122        );
123        cache_hits += stats.get_subtrees_skipped();
124    }
125    build_metric(
126        BENCH_LAYOUT_CACHE_NAME,
127        count,
128        start.elapsed(),
129        format!("cache_hits={cache_hits}"),
130    )
131}
132
133/// Benchmarks full 800x600 software SDF tile rasterization frames.
134///
135/// # Arguments
136///
137/// - `usize` - Number of rendered frames to measure.
138///
139/// # Returns
140///
141/// - `BenchMetric` - Measured frame latency, FPS throughput, and pixel hash.
142#[must_use]
143pub fn bench_software_rasterizer(iterations: usize) -> BenchMetric {
144    bench_render_pipeline(BENCH_SW_RASTER_NAME, RenderConfig::software(), iterations)
145}
146
147/// Benchmarks hardware GPU instanced draw-batch compilation frames.
148///
149/// # Arguments
150///
151/// - `usize` - Number of GPU frame submissions to measure.
152///
153/// # Returns
154///
155/// - `BenchMetric` - Measured frame latency, FPS throughput, and batch count.
156#[must_use]
157pub fn bench_hardware_gpu_batching(iterations: usize) -> BenchMetric {
158    bench_render_pipeline(BENCH_HW_BATCH_NAME, RenderConfig::hardware(), iterations)
159}
160
161/// Benchmarks Unicode + CJK glyph rasterization and GPU RGBA8 atlas shelf-packing.
162///
163/// # Arguments
164///
165/// - `usize` - Number of glyph-pack iterations to measure.
166///
167/// # Returns
168///
169/// - `BenchMetric` - Measured latency and packed glyph count.
170#[must_use]
171pub fn bench_unicode_glyph_atlas(iterations: usize) -> BenchMetric {
172    let count: usize = iterations.max(1);
173    let sample_chars: [char; 8] = ['A', 'g', '9', '跨', '端', '原', '生', '框'];
174    let provider: NativeSystemFont = NativeSystemFont::deterministic();
175    let start: Instant = Instant::now();
176    let mut packed_regions: usize = 0;
177    for _ in 0..count {
178        let mut atlas: GlyphAtlas = GlyphAtlas::default();
179        for ch in sample_chars.iter() {
180            let key: GlyphKey = GlyphKey::new(*ch, 160, false);
181            let _: &RasterizedGlyph = atlas.get_or_rasterize_with(key, &provider);
182        }
183        let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
184        packed_regions = packed.get_regions().len();
185    }
186    build_metric(
187        BENCH_GLYPH_ATLAS_NAME,
188        count,
189        start.elapsed(),
190        format!("packed_glyphs={packed_regions}"),
191    )
192}
193
194/// Benchmarks full forced-redraw 800x600 software SDF tile rasterization frames.
195///
196/// # Arguments
197///
198/// - `usize` - Number of full raster frames to measure.
199///
200/// # Returns
201///
202/// - `BenchMetric` - Measured full-frame raster latency and FPS throughput.
203#[must_use]
204pub fn bench_software_full_redraw(iterations: usize) -> BenchMetric {
205    reset_reactive_runtime();
206    let count: usize = iterations.max(1);
207    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
208    let mut win: WindowConfig = WindowConfig::default();
209    win.set_size(800, 600).set_render(RenderConfig::software());
210    let mut cfg: AppConfig = AppConfig::default();
211    cfg.set_window(win);
212    let Ok(mut app) = App::headless(cfg) else {
213        return build_metric(BENCH_SW_FULL_NAME, count, Duration::ZERO, String::new());
214    };
215    let _: NodeId = app.mount(|| {
216        view! {
217            column {
218                style: {
219                    width: Length::Percent(100.0)
220                    padding: Edges::all(SPACE_LG)
221                    gap: SPACE_MD
222                }
223                EuvHeader {
224                    title: BENCH_TITLE.to_string()
225                    subtitle: BENCH_SUBTITLE.to_string()
226                    tokens: tokens
227                }
228                EuvCard {
229                    title: BENCH_TITLE.to_string()
230                    tokens: tokens
231                    subtitle: BENCH_SUBTITLE
232                    EuvBadge {
233                        label: BENCH_BADGE.to_string()
234                        tone: EuvTone::Primary
235                        tokens: tokens
236                    }
237                    EuvProgress {
238                        value: 0.72
239                        tokens: tokens
240                    }
241                }
242            }
243        }
244    });
245    let wid: WindowId = app.get_window_state().get_id();
246    let start: Instant = Instant::now();
247    let mut last_hash: u64 = 0;
248    let mut last_batches: usize = 0;
249    for _ in 0..count {
250        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
251        if let Ok(stats) = app.step_frame() {
252            last_hash = stats.get_frame_hash();
253            last_batches = stats.get_draw_batches();
254        }
255    }
256    build_metric(
257        BENCH_SW_FULL_NAME,
258        count,
259        start.elapsed(),
260        format!("batches={last_batches} hash={last_hash:#018x}"),
261    )
262}
263
264/// Benchmarks 256 dynamic 2D rigid bodies stepping through spatial-hash broad-phase and narrow-phase collision resolution.
265///
266/// # Arguments
267///
268/// - `usize` - Number of fixed 60Hz physics ticks to measure.
269///
270/// # Returns
271///
272/// - `BenchMetric` - Measured physics tick latency and collision throughput.
273#[must_use]
274pub fn bench_game_ecs_physics(iterations: usize) -> BenchMetric {
275    let count: usize = iterations.max(1);
276    let mut world: GameWorld = GameWorld::with_capacity(256);
277    for idx in 0..256usize {
278        let col: f32 = (idx % 16) as f32;
279        let row: f32 = (idx / 16) as f32;
280        let eid: EntityId = world.spawn(
281            EntityTag::Enemy,
282            Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
283        );
284        if let Some(ent) = world.get_entity_mut(eid) {
285            ent.set_velocity(Velocity2D::new(
286                if idx % 2 == 0 { 110.0 } else { -95.0 },
287                if idx % 3 == 0 { 85.0 } else { -75.0 },
288                0.0,
289            ));
290            ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
291            ent.set_collider(Some(Collider2D::circle(
292                10.0,
293                COLLISION_LAYER_ENEMY,
294                COLLISION_LAYER_ALL,
295                false,
296            )));
297        }
298    }
299    let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
300    phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
301    let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
302    let start: Instant = Instant::now();
303    let mut total_collisions: usize = 0;
304    for _ in 0..count {
305        let evs: Vec<CollisionEvent> = physics.step(&mut world, 1.0 / 60.0);
306        total_collisions += evs.len();
307    }
308    build_metric(
309        BENCH_GAME_PHYSICS_NAME,
310        count,
311        start.elapsed(),
312        format!("entities=256 collisions={total_collisions}"),
313    )
314}
315
316/// Benchmarks updating 1,024 active zero-allocation pooled particles per frame.
317///
318/// # Arguments
319///
320/// - `usize` - Number of particle update steps to measure.
321///
322/// # Returns
323///
324/// - `BenchMetric` - Measured particle update latency and throughput.
325#[must_use]
326pub fn bench_game_particles(iterations: usize) -> BenchMetric {
327    let count: usize = iterations.max(1);
328    let mut system: ParticleSystem = ParticleSystem::with_capacity(1024);
329    let mut cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
330    cfg.set_min_life(10.0).set_max_life(20.0);
331    system.emit_burst(Point::new(400.0, 300.0), 1024, cfg);
332    let start: Instant = Instant::now();
333    let mut live: usize = 0;
334    for _ in 0..count {
335        live = system.update(1.0 / 60.0);
336    }
337    build_metric(
338        BENCH_GAME_PARTICLES_NAME,
339        count,
340        start.elapsed(),
341        format!("active_particles={live}"),
342    )
343}
344
345/// Benchmarks the AAA 3D open-world PBR + BVH ray-traced shadows and reflections pipeline.
346///
347/// # Arguments
348///
349/// - `usize` - Number of 3D ray-traced frames to measure.
350///
351/// # Returns
352///
353/// - `BenchMetric` - Measured 3D frame latency, triangle throughput, and BVH ray count.
354#[must_use]
355pub fn bench_game3d_pbr_bvh_raytrace(iterations: usize) -> BenchMetric {
356    let count: usize = iterations.max(1);
357    let mut world: World3D = World3D::create_open_world_city();
358    let mut renderer: Renderer3D = Renderer3D::default();
359    let cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
360    let start: Instant = Instant::now();
361    let mut last_rays: usize = 0;
362    let mut last_tris: usize = 0;
363    for _ in 0..count {
364        let _: ImageBuffer = renderer.render_world(&mut world, 480, 270, &cfg);
365        let st: RenderStats3D = renderer.get_last_stats();
366        last_rays = st.get_rays_traced();
367        last_tris = st.get_triangles_drawn();
368    }
369    build_metric(
370        BENCH_GAME_3D_RT_NAME,
371        count,
372        start.elapsed(),
373        format!("tris={last_tris} rays={last_rays}"),
374    )
375}
376
377/// Benchmarks maxed-out `Cinematic` + `FullPathTracedGi` + `125%` scale 3D ray tracing at HD resolution.
378///
379/// # Arguments
380///
381/// - `usize` - Number of max-settings 3D frames to measure.
382///
383/// # Returns
384///
385/// - `BenchMetric` - Measured frame latency, FPS throughput, resolution, and ray count.
386#[must_use]
387pub fn bench_game3d_cinematic_max_rt(iterations: usize) -> BenchMetric {
388    let count: usize = iterations.max(1);
389    let mut world: World3D = World3D::create_open_world_city();
390    let mut renderer: Renderer3D = Renderer3D::default();
391    let mut cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::Cinematic);
392    cfg.set_ray_tracing(RayTracingMode::FullPathTracedGi)
393        .set_resolution_scale(1.25);
394    let start: Instant = Instant::now();
395    let mut last_rays: usize = 0;
396    let mut last_w: u32 = 0;
397    let mut last_h: u32 = 0;
398    for _ in 0..count {
399        let _: ImageBuffer = renderer.render_world(&mut world, 960, 480, &cfg);
400        let st: RenderStats3D = renderer.get_last_stats();
401        last_rays = st.get_rays_traced();
402        last_w = st.get_render_width();
403        last_h = st.get_render_height();
404    }
405    build_metric(
406        BENCH_GAME_3D_MAX_RT_NAME,
407        count,
408        start.elapsed(),
409        format!("res={last_w}x{last_h} rays={last_rays}"),
410    )
411}
412
413/// Stress-benchmarks continuous scrolling of a 100,000-row `EuvVirtualList` through full layout and software rasterization.
414///
415/// # Arguments
416///
417/// - `usize` - Number of scrolled frames to measure.
418///
419/// # Returns
420///
421/// - `BenchMetric` - Measured frame latency, throughput, and final virtual scroll offset.
422#[must_use]
423pub fn bench_stress_long_list_100k(iterations: usize) -> BenchMetric {
424    reset_reactive_runtime();
425    let count: usize = iterations.max(1);
426    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
427    let p: ThemePalette = tokens.get_palette();
428    let g: ThemeGeometry = tokens.get_geometry();
429    let mut win: WindowConfig = WindowConfig::default();
430    win.set_size(400, 720).set_render(RenderConfig::software());
431    let mut cfg: AppConfig = AppConfig::default();
432    cfg.set_window(win);
433    let Ok(mut app) = App::headless(cfg) else {
434        return build_metric(
435            BENCH_STRESS_LONG_LIST_NAME,
436            count,
437            Duration::ZERO,
438            String::new(),
439        );
440    };
441    let scroll_y: Signal<f32> = Signal::new(0.0);
442    let _: NodeId = app.mount(|| {
443        let vlist: EuvVirtualList =
444            EuvVirtualList::new(100_000, 36.0, scroll_y, tokens).viewport_height(680.0);
445        vlist.mount_with(move |idx: usize| {
446            view! {
447                row {
448                    style: {
449                        width: Length::Percent(100.0)
450                        height: Length::Px(36.0)
451                        padding: Edges::symmetric(SPACE_XS, SPACE_MD)
452                        align: AlignItems::Center
453                        border: (g.get_border_width(), p.get_border())
454                    }
455                    text {
456                        style: {
457                            font_size: 13.0
458                            color: p.get_foreground()
459                        }
460                        { format!("{BENCH_ROW_LABEL} #{idx}") }
461                    }
462                }
463            }
464        })
465    });
466    let _: Result<FrameStats, PlatformError> = app.step_frame();
467    let start: Instant = Instant::now();
468    let mut last_shaded: usize = 0;
469    for step in 1..=count {
470        let next_y: f32 = ((step as f32) * 144.0) % 3_500_000.0;
471        let _: bool = scroll_y.set_if_changed(next_y);
472        if let Ok(stats) = app.step_frame() {
473            last_shaded = stats.get_pixels_shaded();
474        }
475    }
476    build_metric(
477        BENCH_STRESS_LONG_LIST_NAME,
478        count,
479        start.elapsed(),
480        format!(
481            "rows=100000 scroll_y={:.0}px shaded={last_shaded}",
482            scroll_y.get_untracked()
483        ),
484    )
485}
486
487/// Stress-benchmarks a deeply nested 2,000-node Flex/Grid layout tree under repeated full and dirty-subtree layout passes.
488///
489/// # Arguments
490///
491/// - `usize` - Number of layout passes to measure.
492///
493/// # Returns
494///
495/// - `BenchMetric` - Measured per-pass layout latency and node count.
496#[must_use]
497pub fn bench_stress_complex_layout_2000(iterations: usize) -> BenchMetric {
498    reset_reactive_runtime();
499    let count: usize = iterations.max(1);
500    let scene: SceneHandle = SceneHandle::new_tree();
501    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
502    let (leaf_nodes, page): (Vec<NodeId>, NodeId) = with_context(ctx, || {
503        let mut leaves: Vec<NodeId> = Vec::with_capacity(50);
504        let mut sections: Vec<NodeId> = Vec::with_capacity(50);
505        for section_idx in 0..50usize {
506            let mut first_title: NodeId = NodeId::default();
507            let grid_node: NodeId = view! {
508                grid {
509                    style: {
510                        columns: 4
511                        width: Length::Percent(100.0)
512                        gap: SPACE_SM
513                    }
514                    for card_idx in 0..8usize {
515                        column {
516                            style: {
517                                width: Length::Percent(100.0)
518                                padding: Edges::all(SPACE_SM)
519                                gap: SPACE_XS
520                            }
521                            row {
522                                style: {
523                                    width: Length::Percent(100.0)
524                                    justify: JustifyContent::SpaceBetween
525                                }
526                                if card_idx == 0 {
527                                    text {
528                                        node_ref: first_title
529                                        style: {
530                                            font_size: 13.0
531                                        }
532                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
533                                    }
534                                } else {
535                                    text {
536                                        style: {
537                                            font_size: 13.0
538                                        }
539                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
540                                    }
541                                }
542                                text {
543                                    style: {
544                                        font_size: 11.0
545                                    }
546                                    { format!("{section_idx}") }
547                                }
548                            }
549                        }
550                    }
551                }
552            };
553            leaves.push(first_title);
554            sections.push(grid_node);
555        }
556        let p_node: NodeId = view! {
557            column {
558                style: {
559                    width: Length::Px(1280.0)
560                    padding: Edges::all(SPACE_MD)
561                    gap: SPACE_SM
562                }
563                ..sections
564            }
565        };
566        (leaves, p_node)
567    });
568    scene.with_write(
569        |tree: &mut SceneTree| {
570            let root: NodeId = tree.get_root();
571            tree.replace_children(root, vec![page]);
572        },
573        (),
574    );
575    let mut engine: LayoutEngine = LayoutEngine::default();
576    let viewport: Size = Size::new(1280.0, 800.0);
577    let init_stats: LayoutStats = scene.with_write(
578        |tree: &mut SceneTree| engine.compute(tree, viewport),
579        LayoutStats::default(),
580    );
581    let start: Instant = Instant::now();
582    let mut total_computed: usize = 0;
583    let mut total_skipped: usize = 0;
584    for step in 0..count {
585        let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
586        scene.with_write(
587            |tree: &mut SceneTree| {
588                tree.set_text(target, format!("{BENCH_CELL_LABEL} #{step}"));
589                let stats: LayoutStats = engine.compute(tree, viewport);
590                total_computed += stats.get_nodes_computed();
591                total_skipped += stats.get_subtrees_skipped();
592            },
593            (),
594        );
595    }
596    build_metric(
597        BENCH_STRESS_COMPLEX_LAYOUT_NAME,
598        count,
599        start.elapsed(),
600        format!(
601            "initial_nodes={} avg_computed={} avg_skipped={}",
602            init_stats.get_nodes_computed(),
603            total_computed / count,
604            total_skipped / count
605        ),
606    )
607}
608
609/// Stress-benchmarks bulk batched updates across 1,000 live reactive UI components with subscribed signals and memos.
610///
611/// # Arguments
612///
613/// - `usize` - Number of full 1,000-component batch update ticks to measure.
614///
615/// # Returns
616///
617/// - `BenchMetric` - Measured batch update + reactive flush + scene patch latency.
618#[must_use]
619pub fn bench_stress_bulk_reactive_1000(iterations: usize) -> BenchMetric {
620    reset_reactive_runtime();
621    let count: usize = iterations.max(1);
622    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
623    let p: ThemePalette = tokens.get_palette();
624    let mut win: WindowConfig = WindowConfig::default();
625    win.set_size(800, 600).set_render(RenderConfig::hardware());
626    let mut cfg: AppConfig = AppConfig::default();
627    cfg.set_window(win);
628    let Ok(mut app) = App::headless(cfg) else {
629        return build_metric(
630            BENCH_STRESS_BULK_REACTIVE_NAME,
631            count,
632            Duration::ZERO,
633            String::new(),
634        );
635    };
636    let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
637    for idx in 0..1_000u32 {
638        signals.push(Signal::new(idx));
639    }
640    let signals_mount: Vec<Signal<u32>> = signals.clone();
641    let _: NodeId = app.mount(move || {
642        let derived_memos: Vec<Memo<u32>> = signals_mount
643            .into_iter()
644            .map(|sig: Signal<u32>| Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1)))
645            .collect();
646        view! {
647            scroll {
648                style: {
649                    width: Length::Percent(100.0)
650                    height: Length::Percent(100.0)
651                    gap: 2.0
652                }
653                for derived in derived_memos.into_iter() {
654                    text {
655                        style: {
656                            font_size: 12.0
657                            color: p.get_foreground()
658                        }
659                        { move || format!("{BENCH_CELL_LABEL} {}", derived.get()) }
660                    }
661                }
662            }
663        }
664    });
665    let _: Result<FrameStats, PlatformError> = app.step_frame();
666    let start: Instant = Instant::now();
667    let mut last_rev: u64 = 0;
668    for tick in 1..=(count as u32) {
669        batch(|| {
670            for (idx, sig) in signals.iter().enumerate() {
671                let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
672            }
673        });
674        flush_effects();
675        if app.step_frame().is_ok() {
676            last_rev = app.get_last_rendered_revision();
677        }
678    }
679    build_metric(
680        BENCH_STRESS_BULK_REACTIVE_NAME,
681        count,
682        start.elapsed(),
683        format!("components=1000 final_rev={last_rev}"),
684    )
685}
686
687/// Stress-benchmarks end-to-end dynamic `.wasm` binary verification, sandbox execution, hot-swap, and rollback cycles.
688///
689/// # Arguments
690///
691/// - `usize` - Number of v1 -> v2 -> rollback hot-swap cycles to measure.
692///
693/// # Returns
694///
695/// - `BenchMetric` - Measured latency per full dynamic WASM hot-swap cycle.
696#[must_use]
697pub fn bench_stress_wasm_dynamic_hotswap(iterations: usize) -> BenchMetric {
698    reset_reactive_runtime();
699    let count: usize = iterations.max(1);
700    let mut win: WindowConfig = WindowConfig::default();
701    win.set_size(640, 480).set_render(RenderConfig::hardware());
702    let mut cfg: AppConfig = AppConfig::default();
703    cfg.set_window(win);
704    let Ok(mut app) = App::headless(cfg) else {
705        return build_metric(
706            BENCH_STRESS_WASM_LOAD_NAME,
707            count,
708            Duration::ZERO,
709            String::new(),
710        );
711    };
712    let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
713    let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
714    let wasm_v1: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V1, 1, 0x2563EB);
715    let wasm_v2: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V2, 2, 0x7C3AED);
716    let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
717    let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
718    registry.register(
719        BENCH_WASM_URL_V1.to_string(),
720        wasm_v1,
721        BENCH_WASM_ETAG_V1.to_string(),
722        WasmFaultKind::None,
723    );
724    registry.register(
725        BENCH_WASM_URL_V2.to_string(),
726        wasm_v2,
727        BENCH_WASM_ETAG_V2.to_string(),
728        WasmFaultKind::None,
729    );
730    let manager: WasmDynamicManager =
731        WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
732    let hub_slot: DynamicUpdateHub = hub;
733    let _: NodeId = app.mount(move || {
734        view! {
735            slot {
736                id: BENCH_WASM_SLOT
737                hub: hub_slot
738                text {
739                    style: {
740                        font_size: 14.0
741                    }
742                    { BENCH_TITLE }
743                }
744            }
745        }
746    });
747    let _: Result<FrameStats, PlatformError> = app.step_frame();
748    let start: Instant = Instant::now();
749    let mut completed: usize = 0;
750    for cycle in 0..count {
751        let base_ver: u64 = ((cycle as u64) * 2) + 1;
752        let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
753            BENCH_WASM_URL_V1.to_string(),
754            BENCH_WASM_SLOT.to_string(),
755            base_ver,
756        )
757        .with_checksum(csum_v1)
758        .with_allow_downgrade(true);
759        let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
760            BENCH_WASM_URL_V2.to_string(),
761            BENCH_WASM_SLOT.to_string(),
762            base_ver + 1,
763        )
764        .with_checksum(csum_v2)
765        .with_allow_downgrade(true);
766        if manager.load_and_mount(req_v1, BENCH_WASM_SIGN_KEY).is_ok()
767            && manager.load_and_mount(req_v2, BENCH_WASM_SIGN_KEY).is_ok()
768            && manager
769                .rollback_partial(BENCH_WASM_SLOT, BENCH_WASM_ROLLBACK_REASON)
770                .is_ok()
771        {
772            let _: Result<FrameStats, PlatformError> = app.step_frame();
773            completed += 1;
774        }
775    }
776    build_metric(
777        BENCH_STRESS_WASM_LOAD_NAME,
778        count,
779        start.elapsed(),
780        format!("cycles={completed} cache={}", manager.cache_len()),
781    )
782}
783
784/// Stress-benchmarks flagship mobile `1440x3168 @ 4.0x` multi-card shadowed UI scrolling in the multi-core software rasterizer.
785///
786/// # Arguments
787///
788/// - `usize` - Number of full scrolled 4x-DPI frames to measure.
789///
790/// # Returns
791///
792/// - `BenchMetric` - Measured frame latency and FPS throughput at `1440x3168`.
793#[must_use]
794pub fn bench_stress_hidpi_4x_1440x3168(iterations: usize) -> BenchMetric {
795    reset_reactive_runtime();
796    let count: usize = iterations.max(1);
797    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
798    let mut win: WindowConfig = WindowConfig::default();
799    win.set_size(360, 792).set_render(RenderConfig::software());
800    let mut cfg: AppConfig = AppConfig::default();
801    cfg.set_window(win);
802    let Ok(mut app) = App::headless(cfg) else {
803        return build_metric(
804            BENCH_STRESS_HIDPI_4X_NAME,
805            count,
806            Duration::ZERO,
807            String::new(),
808        );
809    };
810    let mut scroll_id: NodeId = NodeId::default();
811    let _: NodeId = app.mount(|| {
812        view! {
813            scroll {
814                node_ref: scroll_id
815                style: {
816                    width: Length::Percent(100.0)
817                    height: Length::Percent(100.0)
818                    padding: Edges::all(SPACE_MD)
819                    gap: SPACE_MD
820                    background: tokens.get_palette().get_background()
821                }
822                for idx in 0..16usize {
823                    EuvCard {
824                        title: format!("{BENCH_TITLE} #{idx}")
825                        tokens: tokens
826                        subtitle: BENCH_CARD_CAPTION
827                        EuvBadge {
828                            label: BENCH_BADGE.to_string()
829                            tone: EuvTone::Primary
830                            tokens: tokens
831                        }
832                        EuvProgress {
833                            value: ((idx % 9) as f32 + 1.0) * 0.1
834                            tokens: tokens
835                        }
836                    }
837                }
838            }
839        }
840    });
841    app.set_exact_physical_viewport(1440, 3168, 4.0);
842    let _: Result<FrameStats, PlatformError> = app.step_frame();
843    let start: Instant = Instant::now();
844    let mut last_shaded: usize = 0;
845    for step in 1..=count {
846        let offset_y: f32 = ((step as f32) * 18.5) % 800.0;
847        app.get_scene().with_write(
848            |tree: &mut SceneTree| {
849                tree.set_scroll_offset(scroll_id, Point::new(0.0, offset_y));
850            },
851            (),
852        );
853        if let Ok(stats) = app.step_frame() {
854            last_shaded = stats.get_pixels_shaded();
855        }
856    }
857    build_metric(
858        BENCH_STRESS_HIDPI_4X_NAME,
859        count,
860        start.elapsed(),
861        format!("res=1440x3168@4x shaded={last_shaded}"),
862    )
863}
864
865/// Stress-benchmarks 240Hz touch-pan scroll physics, thumb-lift anti-reversal filtering, and 1,000-node scene hit-testing.
866///
867/// # Arguments
868///
869/// - `usize` - Number of 240Hz input/hit-test ticks to measure.
870///
871/// # Returns
872///
873/// - `BenchMetric` - Measured input + hit-test latency and throughput.
874#[must_use]
875pub fn bench_stress_scroll_physics_and_hittest(iterations: usize) -> BenchMetric {
876    reset_reactive_runtime();
877    let count: usize = iterations.max(1);
878    let mut win: WindowConfig = WindowConfig::default();
879    win.set_size(360, 792).set_render(RenderConfig::hardware());
880    let mut cfg: AppConfig = AppConfig::default();
881    cfg.set_window(win);
882    let Ok(mut app) = App::headless(cfg) else {
883        return build_metric(
884            BENCH_STRESS_INPUT_HITTEST_NAME,
885            count,
886            Duration::ZERO,
887            String::new(),
888        );
889    };
890    let _: NodeId = app.mount(|| {
891        view! {
892            scroll {
893                style: {
894                    width: Length::Percent(100.0)
895                    height: Length::Percent(100.0)
896                    gap: 4.0
897                }
898                for idx in 0..1_000usize {
899                    row {
900                        style: {
901                            width: Length::Percent(100.0)
902                            height: Length::Px(32.0)
903                            cursor: CursorIcon::Pointer
904                        }
905                        text {
906                            { format!("{BENCH_ROW_LABEL} {idx}") }
907                        }
908                    }
909                }
910            }
911        }
912    });
913    let wid: WindowId = app.get_window_state().get_id();
914    let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 120.0);
915    let start: Instant = Instant::now();
916    let mut hits: usize = 0;
917    app.dispatch_window_event(WindowEvent::PointerDown(
918        wid,
919        PointerEvent::touch(1, 180.0, 620.0),
920    ));
921    for step in 0..count {
922        let y: f32 = 620.0 - ((step % 48) as f32) * 8.0;
923        app.dispatch_window_event(WindowEvent::PointerMove(
924            wid,
925            PointerEvent::touch(1, 180.0, y),
926        ));
927        let found: bool = app.get_scene().with_read(
928            |tree: &SceneTree| hit_test(tree, Point::new(180.0, 320.0)).is_some(),
929            false,
930        );
931        if found {
932            hits += 1;
933        }
934        if step % 2 == 0 {
935            let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
936        }
937    }
938    app.dispatch_window_event(WindowEvent::PointerUp(
939        wid,
940        PointerEvent::touch(1, 180.0, 240.0),
941    ));
942    build_metric(
943        BENCH_STRESS_INPUT_HITTEST_NAME,
944        count,
945        start.elapsed(),
946        format!("nodes=1000 hits={hits}"),
947    )
948}
949
950/// Benchmarks forced 800x600 software redraw of 12 `Overflow::Hidden` rounded cards with borders, shadows, badges, progress bars, and wrapped text.
951///
952/// # Arguments
953///
954/// - `usize` - Number of full software redraw frames to measure.
955///
956/// # Returns
957///
958/// - `BenchMetric` - Measured frame latency, throughput, and pixel hash.
959#[must_use]
960pub fn bench_software_rounded_clip_cards(iterations: usize) -> BenchMetric {
961    reset_reactive_runtime();
962    let count: usize = iterations.max(1);
963    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
964    let p: ThemePalette = tokens.get_palette();
965    let g: ThemeGeometry = tokens.get_geometry();
966    let mut win: WindowConfig = WindowConfig::default();
967    win.set_size(800, 600).set_render(RenderConfig::software());
968    let mut cfg: AppConfig = AppConfig::default();
969    cfg.set_window(win);
970    let Ok(mut app) = App::headless(cfg) else {
971        return build_metric(
972            BENCH_SW_ROUNDED_CLIP_NAME,
973            count,
974            Duration::ZERO,
975            String::new(),
976        );
977    };
978    let _: NodeId = app.mount(|| {
979        view! {
980            grid {
981                style: {
982                    columns: 3
983                    width: Length::Percent(100.0)
984                    height: Length::Percent(100.0)
985                    padding: Edges::all(SPACE_SM)
986                    gap: SPACE_SM
987                    background: p.get_background()
988                }
989                for idx in 0..12usize {
990                    column {
991                        style: {
992                            width: Length::Percent(100.0)
993                            padding: Edges::all(SPACE_SM)
994                            gap: SPACE_XS
995                            background: p.get_card()
996                            border: (g.get_border_width(), p.get_border())
997                            radius: 16.0
998                            shadow: g.get_shadow_md()
999                            overflow: Overflow::Hidden
1000                        }
1001                        row {
1002                            style: {
1003                                width: Length::Percent(100.0)
1004                                justify: JustifyContent::SpaceBetween
1005                                align: AlignItems::Center
1006                            }
1007                            text {
1008                                style: {
1009                                    flex_shrink: 1.0
1010                                    min_width: Length::Px(0.0)
1011                                    font_size: 13.0
1012                                    font_weight: FontWeight::SemiBold
1013                                    color: p.get_card_foreground()
1014                                }
1015                                { format!("{BENCH_TITLE} #{idx}") }
1016                            }
1017                            EuvBadge {
1018                                label: BENCH_BADGE.to_string()
1019                                tone: if idx % 2 == 0 { EuvTone::Primary } else { EuvTone::Success }
1020                                tokens: tokens
1021                            }
1022                        }
1023                        text {
1024                            style: {
1025                                width: Length::Percent(100.0)
1026                                font_size: 11.0
1027                                color: p.get_muted_foreground()
1028                            }
1029                            { BENCH_CARD_WRAP_COPY }
1030                        }
1031                        EuvProgress {
1032                            value: ((idx % 8) as f32 + 1.0) * 0.11
1033                            tokens: tokens
1034                        }
1035                    }
1036                }
1037            }
1038        }
1039    });
1040    let wid: WindowId = app.get_window_state().get_id();
1041    let _: Result<FrameStats, PlatformError> = app.step_frame();
1042    let start: Instant = Instant::now();
1043    let mut last_hash: u64 = 0;
1044    let mut last_shaded: usize = 0;
1045    for _ in 0..count {
1046        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
1047        if let Ok(stats) = app.step_frame() {
1048            last_hash = stats.get_frame_hash();
1049            last_shaded = stats.get_pixels_shaded();
1050        }
1051    }
1052    build_metric(
1053        BENCH_SW_ROUNDED_CLIP_NAME,
1054        count,
1055        start.elapsed(),
1056        format!("cards=12 shaded={last_shaded} hash={last_hash:#018x}"),
1057    )
1058}
1059
1060/// Benchmarks forced 800x600 software redraw of linear gradients, 1:1 & scaled rounded images, sprite regions, circles, thick AA lines, and filled triangles.
1061///
1062/// # Arguments
1063///
1064/// - `usize` - Number of full software redraw frames to measure.
1065///
1066/// # Returns
1067///
1068/// - `BenchMetric` - Measured frame latency, throughput, and pixel hash.
1069#[must_use]
1070pub fn bench_software_primitives_image_vec(iterations: usize) -> BenchMetric {
1071    reset_reactive_runtime();
1072    let count: usize = iterations.max(1);
1073    let mut win: WindowConfig = WindowConfig::default();
1074    win.set_size(800, 600).set_render(RenderConfig::software());
1075    let mut cfg: AppConfig = AppConfig::default();
1076    cfg.set_window(win);
1077    let Ok(mut app) = App::headless(cfg) else {
1078        return build_metric(
1079            BENCH_SW_PRIMITIVES_NAME,
1080            count,
1081            Duration::ZERO,
1082            String::new(),
1083        );
1084    };
1085    let img_opaque: ImageBuffer = build_test_image_buffer(128, 128, 255);
1086    let img_rounded: ImageBuffer = build_test_image_buffer(96, 96, 224);
1087    let sprite_sheet: ImageBuffer = build_test_image_buffer(128, 128, 255);
1088    let img_canvas_opaque: ImageBuffer = img_opaque.clone();
1089    let img_canvas_scaled: ImageBuffer = img_rounded.clone();
1090    let canvas_sprites: ImageBuffer = sprite_sheet;
1091    let _: NodeId = app.mount(move || {
1092        let painter = move |bounds: Rect, dl: &mut DisplayList| {
1093            let bx: f32 = bounds.get_x();
1094            let by: f32 = bounds.get_y();
1095            dl.push(DrawCommand::LinearGradientRect {
1096                rect: Rect::new(bx + 8.0, by + 8.0, 240.0, 110.0),
1097                gradient: LinearGradient::new(
1098                    0.0,
1099                    Color::rgb(37, 99, 235),
1100                    Color::rgb(124, 58, 237),
1101                ),
1102                radius: CornerRadius::all(14.0),
1103            });
1104            dl.push(DrawCommand::LinearGradientRect {
1105                rect: Rect::new(bx + 260.0, by + 8.0, 240.0, 110.0),
1106                gradient: LinearGradient::new(
1107                    45.0,
1108                    Color::rgb(16, 185, 129),
1109                    Color::rgb(14, 165, 233),
1110                ),
1111                radius: CornerRadius::all(14.0),
1112            });
1113            dl.push(DrawCommand::Image {
1114                rect: Rect::new(bx + 516.0, by + 8.0, 128.0, 128.0),
1115                buffer: img_canvas_opaque.clone(),
1116                radius: CornerRadius::all(0.0),
1117            });
1118            dl.push(DrawCommand::Image {
1119                rect: Rect::new(bx + 654.0, by + 8.0, 130.0, 116.0),
1120                buffer: img_canvas_scaled.clone(),
1121                radius: CornerRadius::all(18.0),
1122            });
1123            for idx in 0..8usize {
1124                let fx: f32 = bx + 12.0 + (idx as f32) * 94.0;
1125                let tint: Color = if idx % 2 == 0 {
1126                    Color::rgb(255, 255, 255)
1127                } else {
1128                    Color::rgba(220, 235, 255, 220)
1129                };
1130                dl.push(DrawCommand::SpriteRegion {
1131                    rect: Rect::new(fx, by + 150.0, 76.0, 64.0),
1132                    buffer: canvas_sprites.clone(),
1133                    src_rect: Rect::new(
1134                        ((idx % 4) as f32) * 32.0,
1135                        ((idx / 4) as f32) * 64.0,
1136                        32.0,
1137                        64.0,
1138                    ),
1139                    tint,
1140                });
1141            }
1142            for idx in 0..12usize {
1143                let cx: f32 = bx + 42.0 + (idx as f32) * 62.0;
1144                let cy: f32 = by + 258.0 + ((idx % 2) as f32) * 26.0;
1145                dl.push(DrawCommand::Circle {
1146                    center: Point::new(cx, cy),
1147                    radius: 14.0 + ((idx % 4) as f32) * 4.0,
1148                    color: Color::rgba(59 + ((idx as u8) * 14), 130, 246 - ((idx as u8) * 12), 235),
1149                });
1150            }
1151            for idx in 0..16usize {
1152                let lx: f32 = bx + 16.0 + (idx as f32) * 46.0;
1153                dl.push(DrawCommand::Line {
1154                    from: Point::new(lx, by + 312.0),
1155                    to: Point::new(lx + 72.0, by + 372.0),
1156                    color: Color::rgba(244, 63, 94, 230),
1157                    width: 2.5 + ((idx % 3) as f32) * 1.5,
1158                });
1159            }
1160            for idx in 0..12usize {
1161                let tx: f32 = bx + 18.0 + (idx as f32) * 62.0;
1162                let ty: f32 = by + 392.0;
1163                let (p0, p1, p2): (Point, Point, Point) = if idx % 2 == 0 {
1164                    (
1165                        Point::new(tx, ty + 48.0),
1166                        Point::new(tx + 28.0, ty),
1167                        Point::new(tx + 54.0, ty + 48.0),
1168                    )
1169                } else {
1170                    (
1171                        Point::new(tx, ty),
1172                        Point::new(tx + 54.0, ty),
1173                        Point::new(tx + 27.0, ty + 48.0),
1174                    )
1175                };
1176                dl.push(DrawCommand::Triangle {
1177                    p0,
1178                    p1,
1179                    p2,
1180                    color: Color::rgba(234, 179, 8, 225),
1181                });
1182            }
1183        };
1184        view! {
1185            column {
1186                style: {
1187                    width: Length::Percent(100.0)
1188                    height: Length::Percent(100.0)
1189                    padding: Edges::all(SPACE_SM)
1190                    gap: SPACE_SM
1191                    background: Color::rgb(15, 23, 42)
1192                }
1193                row {
1194                    style: {
1195                        width: Length::Percent(100.0)
1196                        height: Length::Px(104.0)
1197                        gap: SPACE_SM
1198                    }
1199                    view {
1200                        style: {
1201                            flex_grow: 1.0
1202                            height: Length::Percent(100.0)
1203                            gradient: LinearGradient::new(
1204                                0.0,
1205                                Color::rgb(30, 64, 175),
1206                                Color::rgb(15, 23, 42),
1207                            )
1208                            radius: 12.0
1209                        }
1210                    }
1211                    view {
1212                        style: {
1213                            flex_grow: 1.0
1214                            height: Length::Percent(100.0)
1215                            gradient: LinearGradient::new(
1216                                135.0,
1217                                Color::rgb(168, 85, 247),
1218                                Color::rgb(236, 72, 153),
1219                            )
1220                            radius: 12.0
1221                        }
1222                    }
1223                    image {
1224                        source: img_opaque
1225                        style: {
1226                            width: Length::Px(96.0)
1227                            height: Length::Px(96.0)
1228                        }
1229                    }
1230                    image {
1231                        source: img_rounded
1232                        style: {
1233                            width: Length::Px(132.0)
1234                            height: Length::Px(96.0)
1235                            radius: 14.0
1236                        }
1237                    }
1238                }
1239                canvas {
1240                    style: {
1241                        width: Length::Percent(100.0)
1242                        flex_grow: 1.0
1243                    }
1244                    painter: painter
1245                }
1246            }
1247        }
1248    });
1249    let wid: WindowId = app.get_window_state().get_id();
1250    let _: Result<FrameStats, PlatformError> = app.step_frame();
1251    let start: Instant = Instant::now();
1252    let mut last_hash: u64 = 0;
1253    let mut last_shaded: usize = 0;
1254    for _ in 0..count {
1255        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
1256        if let Ok(stats) = app.step_frame() {
1257            last_hash = stats.get_frame_hash();
1258            last_shaded = stats.get_pixels_shaded();
1259        }
1260    }
1261    build_metric(
1262        BENCH_SW_PRIMITIVES_NAME,
1263        count,
1264        start.elapsed(),
1265        format!("shaded={last_shaded} hash={last_hash:#018x}"),
1266    )
1267}
1268
1269/// Benchmarks 720x1280@2x software `EuvDrawer` portal slide-in and slide-out animation over 8 shadowed cards.
1270///
1271/// # Arguments
1272///
1273/// - `usize` - Number of 120Hz animated overlay frames to measure.
1274///
1275/// # Returns
1276///
1277/// - `BenchMetric` - Measured portal animation frame latency and throughput.
1278#[must_use]
1279pub fn bench_software_portal_overlay_anim(iterations: usize) -> BenchMetric {
1280    reset_reactive_runtime();
1281    let count: usize = iterations.max(1);
1282    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1283    let p: ThemePalette = tokens.get_palette();
1284    let mut win: WindowConfig = WindowConfig::default();
1285    win.set_size(360, 640).set_render(RenderConfig::software());
1286    let mut cfg: AppConfig = AppConfig::default();
1287    cfg.set_window(win);
1288    let Ok(mut app) = App::headless(cfg) else {
1289        return build_metric(
1290            BENCH_SW_PORTAL_ANIM_NAME,
1291            count,
1292            Duration::ZERO,
1293            String::new(),
1294        );
1295    };
1296    let drawer_open: Signal<bool> = Signal::new(false);
1297    let _: NodeId = app.mount(move || {
1298        let drawer_body: NodeId = view! {
1299            column {
1300                style: {
1301                    width: Length::Percent(100.0)
1302                    gap: SPACE_SM
1303                }
1304                text {
1305                    style: {
1306                        width: Length::Percent(100.0)
1307                        font_size: 13.0
1308                        color: p.get_muted_foreground()
1309                    }
1310                    { BENCH_DRAWER_BODY }
1311                }
1312                EuvBadge {
1313                    label: BENCH_BADGE.to_string()
1314                    tone: EuvTone::Primary
1315                    tokens: tokens
1316                }
1317                EuvProgress {
1318                    value: 0.68
1319                    tokens: tokens
1320                }
1321            }
1322        };
1323        view! {
1324            column {
1325                style: {
1326                    width: Length::Percent(100.0)
1327                    height: Length::Percent(100.0)
1328                    padding: Edges::all(SPACE_SM)
1329                    gap: SPACE_SM
1330                    background: p.get_background()
1331                }
1332                grid {
1333                    style: {
1334                        columns: 2
1335                        width: Length::Percent(100.0)
1336                        gap: SPACE_SM
1337                    }
1338                    for idx in 0..8usize {
1339                        EuvCard {
1340                            title: format!("{BENCH_TITLE} #{idx}")
1341                            tokens: tokens
1342                            subtitle: BENCH_CARD_CAPTION
1343                            EuvBadge {
1344                                label: BENCH_BADGE.to_string()
1345                                tone: EuvTone::Primary
1346                                tokens: tokens
1347                            }
1348                            EuvProgress {
1349                                value: ((idx % 7) as f32 + 1.0) * 0.12
1350                                tokens: tokens
1351                            }
1352                        }
1353                    }
1354                }
1355                EuvDrawer {
1356                    open: drawer_open
1357                    title: BENCH_DRAWER_TITLE.to_string()
1358                    body: drawer_body
1359                    tokens: tokens
1360                }
1361            }
1362        }
1363    });
1364    app.set_exact_physical_viewport(720, 1280, 2.0);
1365    let _: Result<FrameStats, PlatformError> = app.step_frame();
1366    let toggle_step: usize = (count / 2).max(1);
1367    let start: Instant = Instant::now();
1368    let mut last_hash: u64 = 0;
1369    let mut last_shaded: usize = 0;
1370    let _: bool = drawer_open.set_if_changed(true);
1371    for step in 0..count {
1372        if step == toggle_step && count > 1 {
1373            let _: bool = drawer_open.set_if_changed(false);
1374        }
1375        if let Ok(stats) = app.step_game_frame(1.0 / 120.0) {
1376            last_hash = stats.get_frame_hash();
1377            last_shaded = stats.get_pixels_shaded();
1378        }
1379    }
1380    build_metric(
1381        BENCH_SW_PORTAL_ANIM_NAME,
1382        count,
1383        start.elapsed(),
1384        format!("res=720x1280@2x shaded={last_shaded} hash={last_hash:#018x}"),
1385    )
1386}
1387
1388/// Benchmarks active per-frame dirty mutation through `PaintPass::build` and `HardwareRenderer::render` on every iteration.
1389///
1390/// # Arguments
1391///
1392/// - `usize` - Number of actively mutated hardware frames to measure.
1393///
1394/// # Returns
1395///
1396/// - `BenchMetric` - Measured active hardware batching latency and total draw batches.
1397#[must_use]
1398pub fn bench_hardware_active_batching(iterations: usize) -> BenchMetric {
1399    reset_reactive_runtime();
1400    let count: usize = iterations.max(1);
1401    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1402    let p: ThemePalette = tokens.get_palette();
1403    let mut win: WindowConfig = WindowConfig::default();
1404    win.set_size(800, 600).set_render(RenderConfig::hardware());
1405    let mut cfg: AppConfig = AppConfig::default();
1406    cfg.set_window(win);
1407    let Ok(mut app) = App::headless(cfg) else {
1408        return build_metric(
1409            BENCH_HW_ACTIVE_BATCH_NAME,
1410            count,
1411            Duration::ZERO,
1412            String::new(),
1413        );
1414    };
1415    let mut accent_node: NodeId = NodeId::default();
1416    let _: NodeId = app.mount(|| {
1417        view! {
1418            column {
1419                style: {
1420                    width: Length::Percent(100.0)
1421                    height: Length::Percent(100.0)
1422                    padding: Edges::all(SPACE_MD)
1423                    gap: SPACE_SM
1424                    background: p.get_background()
1425                }
1426                EuvHeader {
1427                    title: BENCH_TITLE.to_string()
1428                    subtitle: BENCH_SUBTITLE.to_string()
1429                    tokens: tokens
1430                }
1431                view {
1432                    node_ref: accent_node
1433                    style: {
1434                        width: Length::Percent(100.0)
1435                        height: Length::Px(12.0)
1436                        radius: 6.0
1437                        background: p.get_primary()
1438                    }
1439                }
1440                grid {
1441                    style: {
1442                        columns: 2
1443                        width: Length::Percent(100.0)
1444                        gap: SPACE_SM
1445                    }
1446                    for idx in 0..8usize {
1447                        EuvCard {
1448                            title: format!("{BENCH_TITLE} #{idx}")
1449                            tokens: tokens
1450                            subtitle: BENCH_SUBTITLE
1451                            EuvBadge {
1452                                label: BENCH_BADGE.to_string()
1453                                tone: EuvTone::Primary
1454                                tokens: tokens
1455                            }
1456                            EuvProgress {
1457                                value: ((idx % 7) as f32 + 1.0) * 0.12
1458                                tokens: tokens
1459                            }
1460                        }
1461                    }
1462                }
1463            }
1464        }
1465    });
1466    let _: Result<FrameStats, PlatformError> = app.step_frame();
1467    let start: Instant = Instant::now();
1468    let mut last_batches: usize = 0;
1469    let mut total_batches: usize = 0;
1470    for step in 0..count {
1471        let next_opacity: f32 = if step % 2 == 0 { 0.85 } else { 1.0 };
1472        app.get_scene().with_write(
1473            |tree: &mut SceneTree| {
1474                if let Some(node) = tree.get_node(accent_node) {
1475                    let mut st: Style = *node.style_ref();
1476                    st.get_mut_paint().set_opacity(next_opacity);
1477                    tree.set_style(accent_node, st);
1478                }
1479            },
1480            (),
1481        );
1482        if let Ok(stats) = app.step_frame() {
1483            last_batches = stats.get_draw_batches();
1484            total_batches += last_batches;
1485        }
1486    }
1487    build_metric(
1488        BENCH_HW_ACTIVE_BATCH_NAME,
1489        count,
1490        start.elapsed(),
1491        format!("batches={last_batches} total_batches={total_batches}"),
1492    )
1493}
1494
1495/// Benchmarks `DeterministicTextMeasurer::measure` and `measure_size` on mixed ASCII/CJK paragraphs alongside hot `GlyphAtlas` hits.
1496///
1497/// # Arguments
1498///
1499/// - `usize` - Number of text measurement and glyph lookup iterations to measure.
1500///
1501/// # Returns
1502///
1503/// - `BenchMetric` - Measured latency, throughput, and checksum.
1504#[must_use]
1505pub fn bench_font_text_wrap_measure_cache(iterations: usize) -> BenchMetric {
1506    let count: usize = iterations.max(1);
1507    let measurer: DeterministicTextMeasurer = DeterministicTextMeasurer;
1508    let style: TextStyle = TextStyle::default();
1509    let mut atlas: GlyphAtlas = GlyphAtlas::default();
1510    let hot_chars: [char; 12] = [
1511        'E', 'u', 'v', 'R', 's', 't', '0', '9', '跨', '端', '原', '生',
1512    ];
1513    let keys: Vec<GlyphKey> = hot_chars
1514        .iter()
1515        .map(|ch: &char| GlyphKey::new(*ch, 140, false))
1516        .collect();
1517    for key in keys.iter().copied() {
1518        let _: &RasterizedGlyph = atlas.get_or_rasterize(key);
1519    }
1520    let start: Instant = Instant::now();
1521    let mut checksum: f32 = 0.0;
1522    for _ in 0..count {
1523        let wrapped: TextLayoutResult = measurer.measure(BENCH_PARA_MIXED_A, style, Some(280.0));
1524        let sz_wrapped: Size = measurer.measure_size(BENCH_PARA_MIXED_B, style, Some(280.0));
1525        let sz_single: Size = measurer.measure_size(BENCH_PARA_SINGLE, style, None);
1526        checksum +=
1527            wrapped.get_size().get_height() + sz_wrapped.get_width() + sz_single.get_width();
1528        for key in keys.iter().copied() {
1529            let glyph: &RasterizedGlyph = atlas.get_or_rasterize(key);
1530            checksum += glyph.get_advance() as f32;
1531        }
1532    }
1533    build_metric(
1534        BENCH_FONT_WRAP_CACHE_NAME,
1535        count,
1536        start.elapsed(),
1537        format!("atlas_glyphs={} checksum={checksum:.0}", atlas.len()),
1538    )
1539}
1540
1541/// Benchmarks fractional `+3.7px` wheel scrolling and active pointer hover moves at 240Hz across a 1,000-row scroll viewport.
1542///
1543/// # Arguments
1544///
1545/// - `usize` - Number of 240Hz fractional scroll ticks to measure.
1546///
1547/// # Returns
1548///
1549/// - `BenchMetric` - Measured smooth-scroll latency and throughput.
1550#[must_use]
1551pub fn bench_app_smooth_scroll_fractional(iterations: usize) -> BenchMetric {
1552    reset_reactive_runtime();
1553    let count: usize = iterations.max(1);
1554    let mut win: WindowConfig = WindowConfig::default();
1555    win.set_size(360, 792).set_render(RenderConfig::hardware());
1556    let mut cfg: AppConfig = AppConfig::default();
1557    cfg.set_window(win);
1558    let Ok(mut app) = App::headless(cfg) else {
1559        return build_metric(
1560            BENCH_APP_SMOOTH_SCROLL_NAME,
1561            count,
1562            Duration::ZERO,
1563            String::new(),
1564        );
1565    };
1566    let _: NodeId = app.mount(|| {
1567        view! {
1568            scroll {
1569                style: {
1570                    width: Length::Percent(100.0)
1571                    height: Length::Percent(100.0)
1572                    gap: 4.0
1573                }
1574                for idx in 0..1_000usize {
1575                    row {
1576                        style: {
1577                            width: Length::Percent(100.0)
1578                            height: Length::Px(32.0)
1579                            cursor: CursorIcon::Pointer
1580                        }
1581                        text {
1582                            { format!("{BENCH_ROW_LABEL} #{idx}") }
1583                        }
1584                    }
1585                }
1586            }
1587        }
1588    });
1589    let wid: WindowId = app.get_window_state().get_id();
1590    let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 120.0);
1591    let start: Instant = Instant::now();
1592    let mut total_layout_nodes: usize = 0;
1593    let mut total_batches: usize = 0;
1594    for step in 0..count {
1595        let hover_y: f32 = 120.0 + ((step % 40) as f32) * 8.0;
1596        app.dispatch_window_event(WindowEvent::PointerMove(
1597            wid,
1598            PointerEvent::mouse(180.0, hover_y),
1599        ));
1600        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 3.7)));
1601        if let Ok(stats) = app.step_game_frame(1.0 / 240.0) {
1602            total_layout_nodes += stats.get_layout_nodes();
1603            total_batches += stats.get_draw_batches();
1604        }
1605    }
1606    build_metric(
1607        BENCH_APP_SMOOTH_SCROLL_NAME,
1608        count,
1609        start.elapsed(),
1610        format!("rows=1000 layout_nodes={total_layout_nodes} batches={total_batches}"),
1611    )
1612}
1613
1614/// Benchmarks parsing, mounting, and disposing a full GFM `EuvMarkdown` document containing a 6x4 table, task list, alert, and 60-line Rust `EuvCodeBlock`.
1615///
1616/// # Arguments
1617///
1618/// - `usize` - Number of mount + dispose cycles to measure.
1619///
1620/// # Returns
1621///
1622/// - `BenchMetric` - Measured Markdown mount latency and scene node count.
1623#[must_use]
1624pub fn bench_ui_markdown_codeblock_mount(iterations: usize) -> BenchMetric {
1625    reset_reactive_runtime();
1626    let count: usize = iterations.max(1);
1627    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Dark);
1628    let scene: SceneHandle = SceneHandle::new_tree();
1629    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
1630    let start: Instant = Instant::now();
1631    let mut peak_nodes: usize = 0;
1632    for _ in 0..count {
1633        let (scope, root_node): (Scope, NodeId) = with_context(ctx.clone(), || {
1634            Scope::run(|_: Scope| {
1635                view! {
1636                    EuvMarkdown {
1637                        source: BENCH_MARKDOWN_DOC.to_string()
1638                        tokens: tokens
1639                    }
1640                }
1641            })
1642        });
1643        let live: usize = scene.with_read(|tree: &SceneTree| tree.live_node_count(), 0);
1644        peak_nodes = peak_nodes.max(live);
1645        scope.dispose();
1646        scene.with_write(|tree: &mut SceneTree| tree.dispose_subtree(root_node), ());
1647    }
1648    build_metric(
1649        BENCH_UI_MARKDOWN_MOUNT_NAME,
1650        count,
1651        start.elapsed(),
1652        format!(
1653            "peak_nodes={peak_nodes} doc_bytes={}",
1654            BENCH_MARKDOWN_DOC.len()
1655        ),
1656    )
1657}
1658
1659/// Benchmarks mounting and disposing a ~500-node declarative `view!` tree combining `style!` with `EuvCard`, `EuvButton`, `EuvBadge`, `EuvProgress`, `EuvTag`, and `EuvStatCard`.
1660///
1661/// # Arguments
1662///
1663/// - `usize` - Number of mount + dispose cycles to measure.
1664///
1665/// # Returns
1666///
1667/// - `BenchMetric` - Measured declarative mount latency and live node count per mount.
1668#[must_use]
1669pub fn bench_ui_view_macro_mount_500_nodes(iterations: usize) -> BenchMetric {
1670    reset_reactive_runtime();
1671    let count: usize = iterations.max(1);
1672    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1673    let p: ThemePalette = tokens.get_palette();
1674    let g: ThemeGeometry = tokens.get_geometry();
1675    let scene: SceneHandle = SceneHandle::new_tree();
1676    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
1677    let start: Instant = Instant::now();
1678    let mut nodes_per_mount: usize = 0;
1679    for _ in 0..count {
1680        let (scope, root_node): (Scope, NodeId) = with_context(ctx.clone(), || {
1681            Scope::run(|_: Scope| {
1682                let shell_style: Style = style! {
1683                    FlexDirection::Column
1684                    Overflow::Hidden
1685                    width: Length::Px(1200.0)
1686                    padding: Edges::all(SPACE_MD)
1687                    gap: SPACE_SM
1688                    background: p.get_background()
1689                };
1690                let strip_style: Style = style! {
1691                    FlexDirection::Row
1692                    AlignItems::Center
1693                    gap: SPACE_XS
1694                    width: Length::Percent(100.0)
1695                    border: (g.get_border_width(), p.get_border())
1696                    radius: g.get_radius_sm()
1697                    padding: Edges::all(SPACE_XS)
1698                };
1699                view! {
1700                    view {
1701                        style: shell_style
1702                        for idx in 0..27usize {
1703                            EuvCard {
1704                                title: format!("{BENCH_TITLE} #{idx}")
1705                                tokens: tokens
1706                                subtitle: BENCH_SUBTITLE
1707                                view {
1708                                    style: strip_style
1709                                    EuvButton {
1710                                        label: BENCH_BTN_LABEL.to_string()
1711                                        variant: EuvButtonVariant::Secondary
1712                                        size: EuvButtonSize::Small
1713                                        tokens: tokens
1714                                    }
1715                                    EuvBadge {
1716                                        label: BENCH_BADGE.to_string()
1717                                        tone: EuvTone::Primary
1718                                        tokens: tokens
1719                                    }
1720                                    EuvTag {
1721                                        label: BENCH_TAG_LABEL.to_string()
1722                                        tone: EuvTone::Neutral
1723                                        tokens: tokens
1724                                    }
1725                                }
1726                                EuvProgress {
1727                                    value: ((idx % 9) as f32 + 1.0) * 0.1
1728                                    tokens: tokens
1729                                }
1730                                EuvStatCard {
1731                                    label: BENCH_STAT_LABEL.to_string()
1732                                    value: format!("{}k", idx + 10)
1733                                    caption: BENCH_STAT_CAPTION.to_string()
1734                                    tokens: tokens
1735                                }
1736                            }
1737                        }
1738                    }
1739                }
1740            })
1741        });
1742        nodes_per_mount = scene.with_read(|tree: &SceneTree| tree.live_node_count(), 0);
1743        scope.dispose();
1744        scene.with_write(|tree: &mut SceneTree| tree.dispose_subtree(root_node), ());
1745    }
1746    build_metric(
1747        BENCH_UI_VIEW_MOUNT_500_NAME,
1748        count,
1749        start.elapsed(),
1750        format!("nodes_per_mount={nodes_per_mount}"),
1751    )
1752}
1753
1754/// Benchmarks cycling across 8 `PageRetention::Freeze` routes in `EuvRouter` + `EuvRouterOutlet` paired with `EuvSidebarNav` and `EuvTabs`.
1755///
1756/// # Arguments
1757///
1758/// - `usize` - Number of route switches and frame steps to measure.
1759///
1760/// # Returns
1761///
1762/// - `BenchMetric` - Measured route switch latency and frozen route count.
1763#[must_use]
1764pub fn bench_ui_router_freeze_switch(iterations: usize) -> BenchMetric {
1765    reset_reactive_runtime();
1766    let count: usize = iterations.max(1);
1767    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1768    let mut win: WindowConfig = WindowConfig::default();
1769    win.set_size(800, 600).set_render(RenderConfig::hardware());
1770    let mut cfg: AppConfig = AppConfig::default();
1771    cfg.set_window(win);
1772    let Ok(mut app) = App::headless(cfg) else {
1773        return build_metric(
1774            BENCH_UI_ROUTER_FREEZE_NAME,
1775            count,
1776            Duration::ZERO,
1777            String::new(),
1778        );
1779    };
1780    let mut router: EuvRouter =
1781        EuvRouter::new(BENCH_ROUTE_PATHS[0]).with_default_retention(PageRetention::Freeze);
1782    for idx in 0..BENCH_ROUTE_PATHS.len() {
1783        let route_label: &'static str = BENCH_ROUTE_LABELS[idx];
1784        router = router.route(
1785            BENCH_ROUTE_PATHS[idx],
1786            route_label,
1787            move |_matched: &EuvRouteMatch| {
1788                let counter: Signal<u32> = Signal::new(idx as u32);
1789                let label_text: Box<dyn Fn() -> String> =
1790                    Box::new(move || format!("{route_label} active={}", counter.get()));
1791                view! {
1792                    EuvCard {
1793                        title: route_label.to_string()
1794                        tokens: tokens
1795                        subtitle: BENCH_SUBTITLE
1796                        text {
1797                            style: {
1798                                width: Length::Percent(100.0)
1799                                font_size: 13.0
1800                            }
1801                            { label_text }
1802                        }
1803                        EuvProgress {
1804                            value: ((idx as f32) + 1.0) * 0.11
1805                            tokens: tokens
1806                        }
1807                    }
1808                }
1809            },
1810        );
1811    }
1812    let active_tab: Signal<usize> = Signal::new(0);
1813    let router_mount: EuvRouter = router.clone();
1814    let _: NodeId = app.mount(move || {
1815        let nav_items: Vec<EuvNavItem> = BENCH_ROUTE_PATHS
1816            .iter()
1817            .zip(BENCH_ROUTE_LABELS.iter())
1818            .map(|(path, label): (&&str, &&str)| {
1819                EuvNavItem::new((*path).to_string(), (*label).to_string())
1820            })
1821            .collect();
1822        let tab_labels: Vec<String> = BENCH_ROUTE_LABELS
1823            .iter()
1824            .map(|label: &&str| (*label).to_string())
1825            .collect();
1826        let outlet: EuvRouterOutlet = router_mount.outlet(|_m: &EuvRouteMatch| {
1827            view! {
1828                text {
1829                    { BENCH_FALLBACK_LABEL }
1830                }
1831            }
1832        });
1833        let outlet_node: NodeId = outlet.mount();
1834        view! {
1835            row {
1836                style: {
1837                    width: Length::Percent(100.0)
1838                    height: Length::Percent(100.0)
1839                    padding: Edges::all(SPACE_SM)
1840                    gap: SPACE_MD
1841                }
1842                column {
1843                    style: {
1844                        width: Length::Px(180.0)
1845                    }
1846                    EuvSidebarNav {
1847                        items: nav_items
1848                        active_route: router_mount.get_current_path()
1849                        tokens: tokens
1850                    }
1851                }
1852                column {
1853                    style: {
1854                        flex_grow: 1.0
1855                        gap: SPACE_SM
1856                    }
1857                    EuvTabs {
1858                        labels: tab_labels
1859                        active: active_tab
1860                        tokens: tokens
1861                    }
1862                    { outlet_node }
1863                }
1864            }
1865        }
1866    });
1867    let _: Result<FrameStats, PlatformError> = app.step_frame();
1868    let start: Instant = Instant::now();
1869    for step in 0..count {
1870        let idx: usize = (step + 1) % BENCH_ROUTE_PATHS.len();
1871        router.push(BENCH_ROUTE_PATHS[idx]);
1872        let _: bool = active_tab.set_if_changed(idx);
1873        let _: Result<FrameStats, PlatformError> = app.step_frame();
1874    }
1875    build_metric(
1876        BENCH_UI_ROUTER_FREEZE_NAME,
1877        count,
1878        start.elapsed(),
1879        format!(
1880            "routes=8 frozen={} switches={count}",
1881            router.get_frozen_count().get_untracked()
1882        ),
1883    )
1884}
1885
1886/// Benchmarks filter query updates, sort-order toggles, and single-row selection changes on a 120-row by 5-column `EuvDataTable`.
1887///
1888/// # Arguments
1889///
1890/// - `usize` - Number of alternating table mutation + frame steps to measure.
1891///
1892/// # Returns
1893///
1894/// - `BenchMetric` - Measured data table update latency and throughput.
1895#[must_use]
1896pub fn bench_ui_datatable_filter_select(iterations: usize) -> BenchMetric {
1897    reset_reactive_runtime();
1898    let count: usize = iterations.max(1);
1899    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1900    let mut win: WindowConfig = WindowConfig::default();
1901    win.set_size(800, 600).set_render(RenderConfig::hardware());
1902    let mut cfg: AppConfig = AppConfig::default();
1903    cfg.set_window(win);
1904    let Ok(mut app) = App::headless(cfg) else {
1905        return build_metric(
1906            BENCH_UI_DATATABLE_NAME,
1907            count,
1908            Duration::ZERO,
1909            String::new(),
1910        );
1911    };
1912    let headers: Vec<String> = BENCH_TABLE_HEADERS
1913        .iter()
1914        .map(|h: &&str| (*h).to_string())
1915        .collect();
1916    let mut rows: Vec<Vec<String>> = Vec::with_capacity(120);
1917    for idx in 0..120usize {
1918        let team: &'static str = BENCH_TABLE_TEAMS[idx % BENCH_TABLE_TEAMS.len()];
1919        let status: &'static str = BENCH_TABLE_STATUSES[idx % BENCH_TABLE_STATUSES.len()];
1920        rows.push(vec![
1921            format!("{idx:03}"),
1922            format!("{team}-{idx:03}"),
1923            team.to_string(),
1924            format!("{}.{}ms", 1 + (idx % 9), idx % 10),
1925            status.to_string(),
1926        ]);
1927    }
1928    let filter_sig: Signal<String> = Signal::new(String::new());
1929    let sort_sig: Signal<bool> = Signal::new(true);
1930    let selected_sig: Signal<Option<usize>> = Signal::new(None);
1931    let _: NodeId = app.mount(move || {
1932        view! {
1933            scroll {
1934                style: {
1935                    width: Length::Percent(100.0)
1936                    height: Length::Percent(100.0)
1937                    padding: Edges::all(SPACE_SM)
1938                }
1939                EuvDataTable {
1940                    headers: headers
1941                    rows: rows
1942                    filter: filter_sig
1943                    sort_ascending: sort_sig
1944                    selected_row: selected_sig
1945                    tokens: tokens
1946                }
1947            }
1948        }
1949    });
1950    let _: Result<FrameStats, PlatformError> = app.step_frame();
1951    let start: Instant = Instant::now();
1952    for step in 0..count {
1953        match step % 3 {
1954            0 => {
1955                let query: &'static str =
1956                    BENCH_TABLE_FILTERS[(step / 3) % BENCH_TABLE_FILTERS.len()];
1957                let _: bool = filter_sig.set_if_changed(query.to_string());
1958            }
1959            1 => {
1960                let next_sort: bool = !sort_sig.get_untracked();
1961                let _: bool = sort_sig.set_if_changed(next_sort);
1962            }
1963            _ => {
1964                let _: bool = selected_sig.set_if_changed(Some(step % 40));
1965            }
1966        }
1967        let _: Result<FrameStats, PlatformError> = app.step_frame();
1968    }
1969    build_metric(
1970        BENCH_UI_DATATABLE_NAME,
1971        count,
1972        start.elapsed(),
1973        format!("rows=120 cols=5 updates={count}"),
1974    )
1975}
1976
1977/// Runs the complete reproducible benchmark and stress-test suite across reactivity, layout, virtual lists, WASM OTA, high-DPI rendering, input, UI, and game physics.
1978///
1979/// # Returns
1980///
1981/// - `BenchReport` - Aggregated benchmark results.
1982#[must_use]
1983pub fn run_full_benchmark_suite() -> BenchReport {
1984    run_filtered_benchmark_suite(None)
1985}
1986
1987/// Runs the benchmark suite optionally restricted to metrics whose canonical name contains `filter`.
1988///
1989/// # Arguments
1990///
1991/// - `Option<&str>` - Optional case-sensitive substring filter; `None` executes all 27 benchmarks.
1992///
1993/// # Returns
1994///
1995/// - `BenchReport` - Aggregated results for all matching benchmarks.
1996#[must_use]
1997pub fn run_filtered_benchmark_suite(filter: Option<&str>) -> BenchReport {
1998    let entries: [BenchEntry; 27] = [
1999        (BENCH_REACTIVE_NAME, || {
2000            bench_reactive_signals_and_memos(10_000)
2001        }),
2002        (BENCH_SELECTOR_NAME, || bench_selector_o1(10_000)),
2003        (BENCH_LAYOUT_CACHE_NAME, || bench_layout_cache(1_000)),
2004        (BENCH_GLYPH_ATLAS_NAME, || bench_unicode_glyph_atlas(100)),
2005        (BENCH_SW_FULL_NAME, || bench_software_full_redraw(20)),
2006        (BENCH_SW_RASTER_NAME, || bench_software_rasterizer(20)),
2007        (BENCH_HW_BATCH_NAME, || bench_hardware_gpu_batching(200)),
2008        (BENCH_GAME_PHYSICS_NAME, || bench_game_ecs_physics(200)),
2009        (BENCH_GAME_PARTICLES_NAME, || bench_game_particles(1_000)),
2010        (BENCH_GAME_3D_RT_NAME, || bench_game3d_pbr_bvh_raytrace(10)),
2011        (BENCH_GAME_3D_MAX_RT_NAME, || {
2012            bench_game3d_cinematic_max_rt(10)
2013        }),
2014        (BENCH_STRESS_LONG_LIST_NAME, || {
2015            bench_stress_long_list_100k(30)
2016        }),
2017        (BENCH_STRESS_COMPLEX_LAYOUT_NAME, || {
2018            bench_stress_complex_layout_2000(40)
2019        }),
2020        (BENCH_STRESS_BULK_REACTIVE_NAME, || {
2021            bench_stress_bulk_reactive_1000(20)
2022        }),
2023        (BENCH_STRESS_WASM_LOAD_NAME, || {
2024            bench_stress_wasm_dynamic_hotswap(30)
2025        }),
2026        (BENCH_STRESS_HIDPI_4X_NAME, || {
2027            bench_stress_hidpi_4x_1440x3168(15)
2028        }),
2029        (BENCH_STRESS_INPUT_HITTEST_NAME, || {
2030            bench_stress_scroll_physics_and_hittest(240)
2031        }),
2032        (BENCH_SW_ROUNDED_CLIP_NAME, || {
2033            bench_software_rounded_clip_cards(20)
2034        }),
2035        (BENCH_SW_PRIMITIVES_NAME, || {
2036            bench_software_primitives_image_vec(25)
2037        }),
2038        (BENCH_SW_PORTAL_ANIM_NAME, || {
2039            bench_software_portal_overlay_anim(30)
2040        }),
2041        (BENCH_HW_ACTIVE_BATCH_NAME, || {
2042            bench_hardware_active_batching(200)
2043        }),
2044        (BENCH_FONT_WRAP_CACHE_NAME, || {
2045            bench_font_text_wrap_measure_cache(2_000)
2046        }),
2047        (BENCH_APP_SMOOTH_SCROLL_NAME, || {
2048            bench_app_smooth_scroll_fractional(240)
2049        }),
2050        (BENCH_UI_MARKDOWN_MOUNT_NAME, || {
2051            bench_ui_markdown_codeblock_mount(40)
2052        }),
2053        (BENCH_UI_VIEW_MOUNT_500_NAME, || {
2054            bench_ui_view_macro_mount_500_nodes(50)
2055        }),
2056        (BENCH_UI_ROUTER_FREEZE_NAME, || {
2057            bench_ui_router_freeze_switch(100)
2058        }),
2059        (BENCH_UI_DATATABLE_NAME, || {
2060            bench_ui_datatable_filter_select(100)
2061        }),
2062    ];
2063    let mut metrics: Vec<BenchMetric> = Vec::with_capacity(entries.len());
2064    for (name, runner) in entries.iter() {
2065        let selected: bool = filter
2066            .map(|substr: &str| name.contains(substr))
2067            .unwrap_or(true);
2068        if selected {
2069            metrics.push(runner());
2070        }
2071    }
2072    BenchReport::new(metrics)
2073}
2074
2075/// Builds a deterministic RGBA8 test image buffer for image and sprite-sheet raster benchmarks.
2076///
2077/// # Arguments
2078///
2079/// - `u32` - Width in pixels.
2080/// - `u32` - Height in pixels.
2081/// - `u8` - Constant alpha channel value.
2082///
2083/// # Returns
2084///
2085/// - `ImageBuffer` - Populated deterministic RGBA8 pixel buffer.
2086fn build_test_image_buffer(width: u32, height: u32, alpha: u8) -> ImageBuffer {
2087    let pixel_count: usize = (width as usize).saturating_mul(height as usize);
2088    let mut pixels: Vec<u8> = Vec::with_capacity(pixel_count.saturating_mul(4));
2089    for y in 0..height {
2090        for x in 0..width {
2091            pixels.push(((x.wrapping_mul(3) + y) & 0xFF) as u8);
2092            pixels.push(((y.wrapping_mul(3) + x) & 0xFF) as u8);
2093            pixels.push(((x ^ y).wrapping_mul(5) & 0xFF) as u8);
2094            pixels.push(alpha);
2095        }
2096    }
2097    ImageBuffer::new(width, height, pixels)
2098}
2099
2100/// Formats a `BenchReport` into an aligned terminal summary table.
2101///
2102/// # Arguments
2103///
2104/// - `&BenchReport` - Completed benchmark report.
2105///
2106/// # Returns
2107///
2108/// - `String` - Human-readable report table.
2109#[must_use]
2110pub fn format_bench_report(report: &BenchReport) -> String {
2111    let mut out: String = String::from(REPORT_HEADER);
2112    for m in report.get_metrics().iter() {
2113        out.push_str(&format!(
2114            "{:32} iters={:6} avg={:10.1} ns/op  throughput={:10.0} ops/s  {}\n",
2115            m.get_name(),
2116            m.get_iterations(),
2117            m.get_ns_per_op(),
2118            m.get_ops_per_sec(),
2119            m.get_detail()
2120        ));
2121    }
2122    out
2123}
2124
2125/// Serializes a `BenchReport` to formatted JSON.
2126///
2127/// # Arguments
2128///
2129/// - `&BenchReport` - Completed benchmark report.
2130///
2131/// # Returns
2132///
2133/// - `String` - Pretty-printed JSON string.
2134#[must_use]
2135pub fn report_to_json(report: &BenchReport) -> String {
2136    to_string_pretty(report).unwrap_or_default()
2137}
2138
2139/// Shared rendering benchmark harness supporting both Software and Hardware modes.
2140///
2141/// # Arguments
2142///
2143/// - `&str` - Benchmark name.
2144/// - `RenderConfig` - Renderer pipeline configuration.
2145/// - `usize` - Number of frames to step.
2146///
2147/// # Returns
2148///
2149/// - `BenchMetric` - Measured frame telemetry.
2150fn bench_render_pipeline(name: &str, render: RenderConfig, iterations: usize) -> BenchMetric {
2151    reset_reactive_runtime();
2152    let count: usize = iterations.max(1);
2153    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
2154    let mut win: WindowConfig = WindowConfig::default();
2155    win.set_size(800, 600).set_render(render);
2156    let mut cfg: AppConfig = AppConfig::default();
2157    cfg.set_window(win);
2158    let Ok(mut app) = App::headless(cfg) else {
2159        return build_metric(name, count, Duration::ZERO, String::new());
2160    };
2161    let _: NodeId = app.mount(|| {
2162        view! {
2163            column {
2164                style: {
2165                    width: Length::Percent(100.0)
2166                    padding: Edges::all(SPACE_LG)
2167                    gap: SPACE_MD
2168                }
2169                EuvHeader {
2170                    title: BENCH_TITLE.to_string()
2171                    subtitle: BENCH_SUBTITLE.to_string()
2172                    tokens: tokens
2173                }
2174                EuvCard {
2175                    title: BENCH_TITLE.to_string()
2176                    tokens: tokens
2177                    subtitle: BENCH_SUBTITLE
2178                    EuvBadge {
2179                        label: BENCH_BADGE.to_string()
2180                        tone: EuvTone::Primary
2181                        tokens: tokens
2182                    }
2183                    EuvProgress {
2184                        value: 0.72
2185                        tokens: tokens
2186                    }
2187                }
2188            }
2189        }
2190    });
2191    let start: Instant = Instant::now();
2192    let mut last_hash: u64 = 0;
2193    let mut last_batches: usize = 0;
2194    for _ in 0..count {
2195        if let Ok(stats) = app.step_frame() {
2196            last_hash = stats.get_frame_hash();
2197            last_batches = stats.get_draw_batches();
2198        }
2199    }
2200    build_metric(
2201        name,
2202        count,
2203        start.elapsed(),
2204        format!("batches={last_batches} hash={last_hash:#018x}"),
2205    )
2206}
2207
2208/// Constructs a `BenchMetric` from elapsed wall time and iteration count.
2209///
2210/// # Arguments
2211///
2212/// - `&str` - Metric name.
2213/// - `usize` - Completed iterations.
2214/// - `Duration` - Total elapsed time.
2215/// - `String` - Extra metadata string.
2216///
2217/// # Returns
2218///
2219/// - `BenchMetric` - Computed timing metric.
2220fn build_metric(name: &str, iterations: usize, elapsed: Duration, detail: String) -> BenchMetric {
2221    let total_nanos: f64 = elapsed.as_nanos().max(1) as f64;
2222    let ns_per_op: f64 = total_nanos / (iterations.max(1) as f64);
2223    let ops_per_sec: f64 = 1_000_000_000.0 / ns_per_op.max(1.0);
2224    BenchMetric::new(
2225        name.to_string(),
2226        iterations,
2227        elapsed.as_micros() as u64,
2228        ns_per_op,
2229        ops_per_sec,
2230        detail,
2231    )
2232}