indicatrix-cut 0.7.1

Desktop faceting-design editor: library browsing, spectral 3D rendering, material retargeting, and a solid inspection view.
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Off-UI-thread computation of the Tilt Performance dialog's full-axis (±90°, 1° step)
//! sweeps for all four `indicatrix::color::metrics::PROFILE_AZIMUTHS_DEG` axes.
//!
//! One sample point (`evaluate_gem_optical_metrics`, round brilliant/diamond, release,
//! single-threaded) measures ~1.875 ms. A full-axis profile is 181 points across all
//! four axes, so one complete sweep costs roughly `181 * 4 * 1.875 ms` ~= 1.36
//! seconds -- a real, user-visible wait, which is why:
//!
//! - This work runs on its own `std::thread::spawn` worker, never the UI thread.
//! - `AxesCacheKey`/`launched_key` short-circuit re-opening the dialog (or a `changed`
//!   re-fire with unchanged inputs) against a second ~1.4s sweep. `AxesCacheKey` keys
//!   on the fully resolved [`GemMaterial`], not just its display name -- a custom
//!   material can be edited (RI, birefringence, dispersion, ...) while a tier keeps
//!   referencing the same name, and keying on the name alone would make that register
//!   as "nothing changed," causing both the "Re-render" button to read as a no-op and
//!   a newly opened dialog to show a curve for a material it no longer matches.
//!   [`should_recompute_axes`] is that dedup decision pulled out as its own pure
//!   function.
//! - The `generation` counter lets a stale in-flight computation be abandoned: at
//!   ~1.36s per run, a superseded sweep landing after the user has moved on (changed
//!   material, orbited the camera, reopened against different geometry) would
//!   otherwise be a visible glitch.
//! - `PerformanceGraphDialog.extra_axes_loading` is a real loading state the dialog
//!   must show for over a second, not a brief flicker.
//!
//! This sweeps all four axes uniformly (not just the three non-canonical azimuths),
//! including axis 0, rather than special-casing it to reuse the live render thread's
//! own positive-half-only value (`graph_brilliance`/etc., still computed every frame
//! for `settings_dialog.slint`'s mini tilt chart) -- that value cannot supply the
//! negative half a full-axis sweep needs anyway. One code path, one cache key, one
//! generation counter, no cross-thread reuse of a value that could itself be
//! mid-update, at the cost of one redundant azimuth-0-positive-half resweep (~12% of
//! the ~724 total raytrace evaluations per run).
//!
//! Reads `RenderContext::active_planes`/`material_name`/`custom_materials`/
//! `lighting_preset`/`light_yaw`/`light_pitch` directly -- the same inputs
//! `bridge::render_thread::metrics::compute_or_reuse_metrics` keys its own cache on,
//! minus camera yaw/pitch (irrelevant here since this always sweeps the full axis at
//! four fixed azimuths).

use crate::{
    ActivityModel, MainWindow, TiltModel,
    bridge::render_thread::{RenderContext, resolve_material_with_override},
    gui::optics::curve_path::full_axis_curve_path,
    settings::SettingsPersister,
};
use indicatrix::{
    color::metrics::evaluate_all_axes_profiles_geom,
    geometry::{
        plane::GpuFacetPlane,
        tool::{StoneGeometry, ToolPrimitive},
    },
    optics::{materials::GemMaterial, raytracer::LightingPreset},
    render_setup::hash_geometry,
};
use indicatrix_solid::preview::StoneGeometryBuf;
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use std::sync::{
    Arc, Mutex,
    atomic::{AtomicU64, Ordering},
};

/// Cheap identity for "would recomputing the four full-axis sweeps produce a different
/// result" -- the same fields `indicatrix::color::metrics::MetricsCacheKey` keys on,
/// minus camera yaw/pitch (irrelevant here, see this module's doc comment).
#[derive(Clone, PartialEq)]
struct AxesCacheKey {
    /// The selected lighting preset: the same stone scores differently under another.
    lighting_preset: LightingPreset,
    light_yaw: f32,
    light_pitch: f32,
    /// The fully resolved material (`resolve_material`'s output), not merely its
    /// display name. `GemMaterial`'s derived, field-by-field `PartialEq` is what makes
    /// editing a custom material's own RI/birefringence/dispersion under the same name
    /// register as a real cache-key change -- keying on a bare name would silently
    /// treat "same name, different optics" as "nothing changed."
    material: GemMaterial,
    planes_hash: u64,
}

/// Whether launching a fresh four-axis sweep for `requested` is actually necessary
/// given whatever was last launched (`current`) -- pulled out of the mutex-guarded
/// dedup check in [`setup_tilt_profile_callback`] purely so it is unit-testable.
/// `true` means the ~1.36s sweep must actually run; `false` means the existing
/// `graph_*_extra_axes` data already describes exactly this material/light/geometry.
#[must_use]
fn should_recompute_axes(current: Option<&AxesCacheKey>, requested: &AxesCacheKey) -> bool {
    current != Some(requested)
}

/// One metric's curve for every `PROFILE_AZIMUTHS_DEG` axis, in axis order: four rows,
/// each a full 181-point ±90° profile. Named rather than written inline purely so
/// [`sweep_all_axes`]'s three-of-these return type stays readable (and under clippy's
/// `type_complexity` bar).
type AxisCurveRows = Vec<[f32; 181]>;

/// Sweeps all four [`PROFILE_AZIMUTHS_DEG`] axes, each a full 181-point ±90° profile,
/// returning `(brilliance, extinction, windowing)` rows in axis order.
///
/// Axis 0 is swept here too, rather than reusing the live render thread's own value:
/// that one covers only the positive half and cannot supply the negative half a
/// full-axis sweep needs.
///
/// Split out of [`setup_tilt_profile_callback`] purely to keep that function under
/// clippy's function-length lint. It is also the entire ~1.36s cost of a sweep in one
/// place, which makes that cost easy to find and measure.
fn sweep_all_axes(
    geom: StoneGeometry<'_>,
    material: &GemMaterial,
    lighting_preset: LightingPreset,
    light_yaw: f32,
    light_pitch: f32,
) -> (AxisCurveRows, AxisCurveRows, AxisCurveRows) {
    // The sweep itself lives in `indicatrix::color::metrics` (the browser app's Worker
    // runs the same one); this only splits its axes into the dialog's three row sets.
    // Scored under the selected preset at the current light pose, the lighting the
    // viewport renders with.
    let environment = lighting_preset.studio(1.0, light_yaw, light_pitch);
    let axes = evaluate_all_axes_profiles_geom(geom, material, environment);
    let mut brilliance_rows: AxisCurveRows = Vec::with_capacity(axes.len());
    let mut extinction_rows: AxisCurveRows = Vec::with_capacity(axes.len());
    let mut windowing_rows: AxisCurveRows = Vec::with_capacity(axes.len());
    for axis in axes {
        brilliance_rows.push(axis.brilliance);
        extinction_rows.push(axis.extinction);
        windowing_rows.push(axis.windowing);
    }
    (brilliance_rows, extinction_rows, windowing_rows)
}

/// `on_request_tilt_profile_axes`'s own handler body -- checks `launched_key` for a
/// duplicate request, then spawns the background sweep and pushes its results back
/// onto the UI thread once done (dropping a stale result if superseded by a newer
/// request via `generation`). Split out of [`setup_tilt_profile_callback`] purely to
/// keep that function under clippy's function-length lint; see that function's own
/// doc comment for the full behaviour.
fn handle_request_tilt_profile_axes(
    ui: &MainWindow,
    render_ctx: &Arc<Mutex<RenderContext>>,
    launched_key: &Arc<Mutex<Option<AxesCacheKey>>>,
    completed_key: &Arc<Mutex<Option<AxesCacheKey>>>,
    generation: &Arc<AtomicU64>,
) {
    // The curves describe the FINISHED gem, whatever the Cut slider says: they are printed
    // on the tilt video, which shows the finished gem (`gui::editor::finished_stone`). Asked
    // for before the context is locked below -- it takes that lock itself. With the slider
    // cut back and no current solve in the editor's cache, the stone comes from the solve
    // worker and the rest of this request runs when it lands (never a solve on this
    // thread); the request is the same one, so the dedup keys below still apply.
    let render_ctx_later = Arc::clone(render_ctx);
    let launched_key = Arc::clone(launched_key);
    let completed_key = Arc::clone(completed_key);
    let generation = Arc::clone(generation);
    crate::gui::editor::finished_stone_then(
        ui,
        render_ctx,
        |_| {},
        move |ui, finished| match axes_step(finished) {
            AxesStep::Sweep(finished) => request_axes_for_stone(
                ui,
                &render_ctx_later,
                &launched_key,
                &completed_key,
                &generation,
                finished,
            ),
            AxesStep::MarkStale => ui.global::<TiltModel>().set_curves_stale(true),
            AxesStep::Skip => {}
        },
    );
}

/// What a tilt-curve request does once the finished stone's outcome is known.
#[derive(Debug, PartialEq)]
enum AxesStep {
    /// Dedup against the last launch and sweep this stone (`None`: the render context
    /// already holds the finished stone).
    Sweep(Option<StoneGeometryBuf>),
    /// There is no finished stone to sweep (the design does not solve): the curves on screen
    /// no longer describe the design, so say so. The viewport's own banner tells the cutter
    /// why.
    MarkStale,
    /// The design changed while its stone was being solved. The newer edit's own viewport
    /// push has already asked for ITS sweep; launching one for the superseded design would
    /// bump the sweep generation and make that newer sweep land as "superseded", leaving the
    /// dialog showing the curves of the design one edit ago as if they were current. Does
    /// nothing at all, so the generation counter is not touched. The same for a solve the
    /// worker displaced for a newer request: no stone came back, and the next viewport push
    /// asks again.
    Skip,
}

/// The decision of [`handle_request_tilt_profile_axes`]' continuation, pure so it can be
/// tested without a window.
fn axes_step(finished: crate::gui::editor::Finished) -> AxesStep {
    use crate::gui::editor::Withheld;
    match finished {
        Ok(stone) => AxesStep::Sweep(stone),
        Err(Withheld::Stale | Withheld::Displaced) => AxesStep::Skip,
        Err(Withheld::Unsolvable(_)) => AxesStep::MarkStale,
    }
}

/// [`handle_request_tilt_profile_axes`]' second half: the dedup check and the sweep launch,
/// for the render context's stone with `finished` (the finished stone, when the Cut slider
/// has the design cut back) swapped in.
fn request_axes_for_stone(
    ui: &MainWindow,
    render_ctx: &Arc<Mutex<RenderContext>>,
    launched_key: &Arc<Mutex<Option<AxesCacheKey>>>,
    completed_key: &Arc<Mutex<Option<AxesCacheKey>>>,
    generation: &Arc<AtomicU64>,
    finished: Option<StoneGeometryBuf>,
) {
    let (
        planes,
        tools,
        material_name,
        material_override,
        custom_materials,
        lighting_preset,
        light_yaw,
        light_pitch,
    ) = {
        let ctx = render_ctx
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        (
            ctx.active_planes.clone(),
            ctx.active_tools.clone(),
            ctx.material_name.clone(),
            // Includes the Live Render toolbar's view-only colour, so the curves describe
            // the stone the cutter is looking at.
            ctx.tinted_material_override(),
            ctx.custom_materials.clone(),
            ctx.lighting_preset,
            ctx.light_yaw,
            ctx.light_pitch,
        )
    };
    let (planes, tools) = finished.map_or((planes, tools), |stone| {
        (Arc::new(stone.planes), Arc::new(stone.tools))
    });
    // Resolved once, up front -- both to build a key capturing the material's full
    // identity and to hand the same resolved value to the worker thread below
    // rather than re-resolving it there from a name that could resolve to
    // something else by the time the thread runs.
    // Prefers the editor's fully resolved material over a name lookup: a
    // catalogue custom material or a typed RI override has no built-in name to
    // find, so resolving by name alone would silently sweep a different stone
    // from the one being edited.
    // Refuses (see `resolve_material`'s own doc comment) rather than sweeping tilt
    // curves for Diamond or a previous design's material when the current one does
    // not resolve -- there is nothing honest to sweep, and the viewport's own
    // `ViewportModel.trace_refusal` banner already tells the cutter why.
    let Some(material) = resolve_material_with_override(
        &GemMaterial::all_materials(),
        &custom_materials,
        material_override.as_ref(),
        &material_name,
    ) else {
        return;
    };

    let key = AxesCacheKey {
        lighting_preset,
        light_yaw,
        light_pitch,
        material: material.clone(),
        // `hash_geometry` is `hash_planes` for a planar stone, so its keys are unchanged.
        planes_hash: hash_geometry(StoneGeometry {
            planes: &planes,
            tools: &tools,
        }),
    };
    // Whether the curves already on screen (`completed_key`, the last sweep that
    // actually FINISHED and pushed `graph_*` rows -- as opposed to `launched_key`
    // below, which flips as soon as a sweep merely STARTS) still describe these
    // exact inputs. Pushed unconditionally, even when the dedup check just below
    // decides nothing needs to run: a stale curve stays stale until a fresh sweep
    // actually completes, it doesn't clear itself just because nothing new was
    // launched this time.
    let stale_now = should_recompute_axes(
        completed_key
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .as_ref(),
        &key,
    );
    ui.global::<TiltModel>().set_curves_stale(stale_now);
    {
        let mut launched = launched_key.lock().unwrap();
        if !should_recompute_axes(launched.as_ref(), &key) {
            // Already computed (or currently computing) for these exact inputs.
            return;
        }
        *launched = Some(key.clone());
    }

    let my_generation = generation.fetch_add(1, Ordering::SeqCst) + 1;
    let generation = generation.clone();
    ui.global::<TiltModel>().set_extra_axes_loading(true);
    // This ~1.36s sweep reports no completion fraction (see the module doc
    // comment), so it registers indeterminate -- `ui/models/activity.slint`'s own
    // doc comment on `start_external`/`finish_external` explains why this crosses
    // through the Slint global rather than `gui::editor::activity::
    // ActivityRegistry` directly (this module is outside `gui::editor`'s module
    // tree). Not cancellable: the sweep has no cancel probe of its own, only
    // supersession via `generation`.
    let activity_id = ui.global::<ActivityModel>().invoke_start_external(
        "tilt_curve".into(),
        "Computing tilt curves".into(),
        false,
    );
    let ui_weak_bg = ui.as_weak();

    spawn_tilt_profile_sweep(
        SweepRequest {
            planes,
            tools,
            material,
            lighting_preset,
            light_yaw,
            light_pitch,
            key,
        },
        SweepBookkeeping {
            generation,
            my_generation,
            completed_key: Arc::clone(completed_key),
            activity_id,
        },
        ui_weak_bg,
    );
}

/// The per-sweep inputs [`spawn_tilt_profile_sweep`] needs, bundled so that
/// function's own signature stays under clippy's `too_many_arguments` threshold --
/// see [`SweepBookkeeping`] for the other half.
struct SweepRequest {
    planes: Arc<Vec<GpuFacetPlane>>,
    /// The concave tools cut out of `planes`; empty for a planar stone.
    tools: Arc<Vec<ToolPrimitive>>,
    material: GemMaterial,
    lighting_preset: LightingPreset,
    light_yaw: f32,
    light_pitch: f32,
    /// The exact [`AxesCacheKey`] this sweep was launched for -- stamped into
    /// [`SweepBookkeeping::completed_key`] once the sweep actually lands, so a
    /// later staleness check (`request_axes_for_stone`'s own
    /// `stale_now`) compares against what ACTUALLY finished, not merely what was
    /// last launched.
    key: AxesCacheKey,
}

/// The generation/activity/cache-key bookkeeping [`spawn_tilt_profile_sweep`] needs
/// beyond the sweep's own inputs -- see [`SweepRequest`].
struct SweepBookkeeping {
    generation: Arc<AtomicU64>,
    my_generation: u64,
    /// Set to `Some(request.key)` once this sweep's results are actually pushed --
    /// see [`SweepRequest::key`]'s own doc comment.
    completed_key: Arc<Mutex<Option<AxesCacheKey>>>,
    /// The [`crate::ActivityModel`] id [`request_axes_for_stone`]
    /// registered for this sweep via `invoke_start_external` -- finished here
    /// regardless of whether the result is applied or dropped as stale (an
    /// abandoned sweep's own activity must not linger in the status strip
    /// forever).
    activity_id: i32,
}

/// The background-thread half of [`request_axes_for_stone`]: runs the full
/// four-curve sweep off the UI thread, then pushes the results back via
/// `upgrade_in_event_loop`, dropping a stale result superseded by a newer request
/// (see `generation`'s own doc comment on `setup_tilt_profile_callback`). Split out
/// purely to keep that caller under clippy's function-length lint.
fn spawn_tilt_profile_sweep(
    request: SweepRequest,
    bookkeeping: SweepBookkeeping,
    ui_weak_bg: slint::Weak<MainWindow>,
) {
    let SweepRequest {
        planes,
        tools,
        material,
        lighting_preset,
        light_yaw,
        light_pitch,
        key,
    } = request;
    let SweepBookkeeping {
        generation,
        my_generation,
        completed_key,
        activity_id,
    } = bookkeeping;
    std::thread::spawn(move || {
        let (brilliance_rows, extinction_rows, windowing_rows) = sweep_all_axes(
            StoneGeometry {
                planes: &planes,
                tools: &tools,
            },
            &material,
            lighting_preset,
            light_yaw,
            light_pitch,
        );

        let brilliance_paths: Vec<SharedString> = brilliance_rows
            .iter()
            .map(|row| full_axis_curve_path(row).into())
            .collect();
        let extinction_paths: Vec<SharedString> = extinction_rows
            .iter()
            .map(|row| full_axis_curve_path(row).into())
            .collect();
        let windowing_paths: Vec<SharedString> = windowing_rows
            .iter()
            .map(|row| full_axis_curve_path(row).into())
            .collect();

        let to_model_rows = |rows: Vec<[f32; 181]>| -> ModelRc<ModelRc<f32>> {
            ModelRc::new(VecModel::from(
                rows.into_iter()
                    .map(|row| ModelRc::new(VecModel::from(row.to_vec())))
                    .collect::<Vec<_>>(),
            ))
        };

        let _ = ui_weak_bg.upgrade_in_event_loop(move |ui| {
            // Finished regardless of whether this result is superseded below --
            // an abandoned sweep still stops "running" from the status strip's
            // point of view.
            ui.global::<ActivityModel>()
                .invoke_finish_external(activity_id);
            if generation.load(Ordering::SeqCst) != my_generation {
                // Superseded by a newer request -- drop this stale result rather
                // than overwriting whatever the newer computation lands.
                return;
            }
            ui.global::<TiltModel>()
                .set_graph_brilliance_extra_axes(to_model_rows(brilliance_rows));
            ui.global::<TiltModel>()
                .set_graph_extinction_extra_axes(to_model_rows(extinction_rows));
            ui.global::<TiltModel>()
                .set_graph_windowing_extra_axes(to_model_rows(windowing_rows));
            ui.global::<TiltModel>()
                .set_graph_brilliance_extra_paths(ModelRc::new(VecModel::from(brilliance_paths)));
            ui.global::<TiltModel>()
                .set_graph_extinction_extra_paths(ModelRc::new(VecModel::from(extinction_paths)));
            ui.global::<TiltModel>()
                .set_graph_windowing_extra_paths(ModelRc::new(VecModel::from(windowing_paths)));
            ui.global::<TiltModel>().set_extra_axes_loading(false);
            // See `SweepRequest::key`'s own doc comment: this is what a LATER
            // sweep's own staleness check compares against.
            *completed_key
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(key);
            ui.global::<TiltModel>().set_curves_stale(false);
        });
    });
}

/// Wires `MainWindow::request_tilt_profile_axes` to a background computation of all
/// four full-axis (±90°, 1° step) tilt-elevation sweeps, pushing the results into
/// `graph_*_extra_axes`/`graph_*_extra_paths` (and `extra_axes_loading` around the
/// computation) once done. Split out of `run_gui`/`build_main_window` purely to keep
/// those functions under clippy's function-length lint.
pub(in crate::gui) fn setup_tilt_profile_callback(
    ui: &MainWindow,
    render_ctx: &Arc<Mutex<RenderContext>>,
    settings_store: &Arc<SettingsPersister>,
) {
    // `Some(key)` once a request for exactly these inputs has been launched (whether
    // or not it has finished yet) -- deduplicates re-opening the dialog against the
    // same geometry/material/light without a second ~1.36s background sweep.
    let launched_key: Arc<Mutex<Option<AxesCacheKey>>> = Arc::new(Mutex::new(None));
    // Cloned out before `on_request_tilt_profile_axes` moves the original in below --
    // `on_rerender_curve_with_current_material` needs its own handle to force a fresh
    // sweep regardless of what the dedup check thinks.
    let launched_key_for_rerender = Arc::clone(&launched_key);
    // `Some(key)` once a sweep for exactly these inputs has actually LANDED (as
    // opposed to `launched_key`, which flips the instant one merely starts) --
    // see `TiltModel.curves_stale`'s own staleness check in
    // `request_axes_for_stone`.
    let completed_key: Arc<Mutex<Option<AxesCacheKey>>> = Arc::new(Mutex::new(None));
    // Bumped on every newly-launched computation; a background thread checks its own
    // snapshot against the latest value before applying results, so a stale
    // computation is silently dropped instead of overwriting fresher data.
    let generation = Arc::new(AtomicU64::new(0));

    let ui_weak = ui.as_weak();
    // `render_ctx` is cloned into its OWN binding for the closure below, rather
    // than shadowing the outer `render_ctx`: shadowing it would move the outer
    // binding into the closure, leaving nothing for `setup_video_export_callback`
    // below to borrow.
    let render_ctx_axes = render_ctx.clone();
    ui.global::<TiltModel>()
        .on_request_tilt_profile_axes(move || {
            let Some(ui) = ui_weak.upgrade() else {
                return;
            };
            handle_request_tilt_profile_axes(
                &ui,
                &render_ctx_axes,
                &launched_key,
                &completed_key,
                &generation,
            );
        });

    // The decision-logic callback `performance_graph_dialog.slint`'s `cache_is_stale`
    // property calls into. `cached` arrives from `MainWindow::cached_curve_material`,
    // pushed by `gui::detail::load_diagram_detail`/`_remote` on every design selection.
    ui.global::<TiltModel>().on_is_cached_curve_material_stale(
        |cached: SharedString, current: SharedString| {
            let cached = if cached.is_empty() {
                None
            } else {
                Some(cached.as_str())
            };
            cached_curve_material_is_stale(cached, &current)
        },
    );

    // Re-renders the tilt curve fresh against the current material -- the "discard the
    // stale cached curve, sweep a fresh one" action the stale-cache banner promises.
    // `invoke_request_tilt_profile_axes` alone dedupes against `launched_key` exactly
    // like a dialog-open re-fire does, so clicking this while the live inputs still
    // hash to the last-launched `AxesCacheKey` would silently do nothing. This button
    // means "redo it now regardless," so it clears `launched_key` first, forcing the
    // next call to treat this as a brand-new request.
    let ui_weak_rerender = ui.as_weak();
    ui.global::<TiltModel>()
        .on_rerender_curve_with_current_material(move || {
            if let Some(ui) = ui_weak_rerender.upgrade() {
                *launched_key_for_rerender.lock().unwrap() = None;
                ui.global::<TiltModel>().invoke_request_tilt_profile_axes();
            }
        });

    // The tilt-video export's own wiring is registered from here rather than
    // `gui::mod::run_gui` directly, piggy-backing on the fact that
    // `setup_tilt_profile_callback` is already invoked once from there at
    // startup -- see `video_export`'s own module doc comment.
    super::video_export::setup_video_export_callback(ui, render_ctx, settings_store);
}

/// Whether the tilt-curve/preview data currently cached for this design was rendered
/// under a different `GemMaterial` than the one the viewport currently has loaded, and
/// the dialog should therefore offer to re-render fresh rather than silently show a
/// stale-colored cached curve/image.
///
/// `cached_material_name` is `None` whenever there is no cached curve to compare
/// against at all (e.g. no preview generated yet, or browsing a remote library whose
/// wire protocol carries no preview-material field), in which case this always
/// returns `false`: "no cached data" is not "stale cached data". Name comparison is
/// exact (matching `resolve_material`'s `eq_ignore_ascii_case`).
///
/// The caller (`gui::detail::load_diagram_detail`) sources `cached_material_name` from
/// `Database::get_preview_images(entry_id).material`.
#[must_use]
pub fn cached_curve_material_is_stale(
    cached_material_name: Option<&str>,
    current_material_name: &str,
) -> bool {
    cached_material_name.is_some_and(|cached| !cached.eq_ignore_ascii_case(current_material_name))
}

#[cfg(test)]
mod tests {
    use super::{
        AxesCacheKey, AxesStep, axes_step, cached_curve_material_is_stale, should_recompute_axes,
    };
    use crate::gui::editor::Withheld;
    use indicatrix::optics::{materials::GemMaterial, raytracer::LightingPreset};
    use indicatrix_solid::preview::StoneGeometryBuf;

    /// F4-6: a finished stone that was solved for a design the editor has since left must not
    /// launch a sweep -- that would bump the sweep generation and supersede the newer edit's
    /// own sweep. A design that does not solve marks the curves stale instead of sweeping the
    /// half-cut stone; a good outcome sweeps as before.
    #[test]
    fn a_stale_stone_launches_no_sweep_and_an_unsolvable_one_marks_the_curves_stale() {
        assert_eq!(axes_step(Err(Withheld::Stale)), AxesStep::Skip);
        assert_eq!(
            axes_step(Err(Withheld::Displaced)),
            AxesStep::Skip,
            "a displaced solve says nothing about the design: no sweep, no stale curves"
        );
        assert_eq!(
            axes_step(Err(Withheld::Unsolvable(
                "tier C1 meets nothing".to_string()
            ))),
            AxesStep::MarkStale
        );
        assert_eq!(axes_step(Ok(None)), AxesStep::Sweep(None));
        let stone = StoneGeometryBuf::default();
        assert_eq!(
            axes_step(Ok(Some(stone.clone()))),
            AxesStep::Sweep(Some(stone))
        );
    }

    #[test]
    fn no_cached_material_is_never_stale() {
        assert!(!cached_curve_material_is_stale(None, "Diamond"));
    }

    #[test]
    fn matching_material_is_not_stale() {
        assert!(!cached_curve_material_is_stale(Some("Diamond"), "Diamond"));
        assert!(!cached_curve_material_is_stale(Some("diamond"), "Diamond"));
    }

    #[test]
    fn differing_material_is_stale() {
        assert!(cached_curve_material_is_stale(Some("Diamond"), "Sapphire"));
    }

    fn sample_key(material: GemMaterial) -> AxesCacheKey {
        AxesCacheKey {
            lighting_preset: LightingPreset::RingLights,
            light_yaw: 48.0,
            light_pitch: 54.0,
            material,
            planes_hash: 42,
        }
    }

    #[test]
    fn should_recompute_axes_is_true_the_first_time() {
        let key = sample_key(GemMaterial::all_materials()[0].clone());
        assert!(should_recompute_axes(None, &key));
    }

    #[test]
    fn should_recompute_axes_is_false_once_the_exact_key_was_already_launched() {
        let key = sample_key(GemMaterial::all_materials()[0].clone());
        assert!(!should_recompute_axes(Some(&key), &key));
    }

    #[test]
    fn should_recompute_axes_is_true_when_light_or_geometry_differ() {
        let material = GemMaterial::all_materials()[0].clone();
        let current = sample_key(material);
        let mut moved_light = current.clone();
        moved_light.light_yaw += 1.0;
        assert!(should_recompute_axes(Some(&current), &moved_light));
        let mut moved_geometry = current.clone();
        moved_geometry.planes_hash = 43;
        assert!(should_recompute_axes(Some(&current), &moved_geometry));
    }

    /// The curves are scored under the selected preset, so switching preset alone must
    /// re-launch the sweep.
    #[test]
    fn should_recompute_axes_is_true_when_only_the_lighting_preset_differs() {
        let current = sample_key(GemMaterial::all_materials()[0].clone());
        let mut other_preset = current.clone();
        other_preset.lighting_preset = LightingPreset::LightTent;
        assert!(should_recompute_axes(Some(&current), &other_preset));
    }

    /// A custom material can be edited (RI, birefringence, dispersion, ...) while a
    /// tier keeps referencing the same name -- so the dedup key must change even
    /// though the name didn't. Folding the fully resolved `GemMaterial` into
    /// `AxesCacheKey` is what makes that true, via its derived `PartialEq`.
    #[test]
    fn should_recompute_axes_is_true_when_only_the_resolved_materials_optics_differ() {
        let mut edited = GemMaterial::all_materials()[0].clone();
        let current = sample_key(edited.clone());
        edited.birefringence_delta += 0.01;
        let requested = sample_key(edited);
        assert_eq!(
            current.material.name, requested.material.name,
            "the display name must be unchanged -- that is the whole point of this case"
        );
        assert!(should_recompute_axes(Some(&current), &requested));
    }
}