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
//! [`SceneSnapshot`]: a read-only capture of everything a render needs, taken out of
//! the live `RenderContext` under one short lock.
//!
//! Split out of `bridge::export_thread` purely to keep that module (already sizeable)
//! from growing further.
use crate::bridge::{
frame_cache::stone_width::StoneWidthCache,
render_thread::{
MaterialOverrides, RenderContext, apply_material_overrides, resolve_material_with_override,
},
};
use indicatrix::{
geometry::{girdle_facet_finishes, plane::GpuFacetPlane, tool::ToolPrimitive},
optics::{
fluorescence::Fluorescence,
materials::GemMaterial,
raytracer::{FacetFinish, LightingPreset},
},
renderer::env_map::EnvironmentMap,
};
use indicatrix_solid::preview::StoneGeometryBuf;
use std::sync::{Arc, Mutex};
/// A read-only snapshot of everything a render needs, captured out of the live
/// `RenderContext` under one short lock. Deliberately excludes `width`/`height` and
/// the accumulation buffer -- those belong solely to the interactive viewport; the
/// export worker sizes its own buffer from the user's requested export dimensions.
///
/// `Clone`: a preset-fan-out export clones the current-view capture once per selected
/// preset and overlays that preset's own light/camera/env-map fields on top
/// (`gui::render_export::apply_preset_to_scene`) rather than re-capturing the live
/// viewport per render -- every fanned-out render must share the exact same material,
/// geometry, and bounce cap, which only holds if they all descend from ONE capture.
#[derive(Clone)]
pub struct SceneSnapshot {
/// Camera yaw.
pub yaw: f32,
/// Camera pitch.
pub pitch: f32,
/// Camera distance from the stone.
pub distance: f32,
/// Light yaw.
pub light_yaw: f32,
/// Light pitch.
pub light_pitch: f32,
/// Gem material the stone is rendered with.
pub material: GemMaterial,
/// Lighting preset the render uses.
pub lighting_preset: LightingPreset,
/// Maximum number of ray bounces per path.
pub max_bounces: u32,
/// Exposure multiplier applied when tone-mapping.
pub exposure: f32,
/// Backdrop radiance -- `RenderContext::backdrop` resolved through `Backdrop::level`.
pub backdrop: f32,
/// Surface-glare scale (`RenderContext::surface_glare`, `0.0..=1.0`): exports follow
/// the viewport's value the way they follow its lighting preset. Analytic presets
/// only; an HDR map ignores it.
pub surface_glare: f32,
/// Head-shadow radius in degrees (`RenderContext::head_shadow_deg`, `0.0` = off): exports
/// follow the viewport's value. Lit analytic presets only; an HDR map ignores it.
pub head_shadow_deg: f32,
/// Facet planes of the active design.
pub active_planes: Vec<GpuFacetPlane>,
/// The concave tools cut out of `active_planes` (`RenderContext::active_tools`);
/// empty for a planar design, which is then exported exactly as before. A tool-bearing
/// scene is traced on the CPU alone (`scene_routes_to_gpu`) and sent to a remote
/// worker as `SceneState::tools`.
pub tools: Vec<ToolPrimitive>,
/// The material's fluorescent emitters (`RenderContext::active_fluorescence`, resolved
/// from the physics recipe), empty for every non-fluorescent material, which then exports
/// exactly as before. A fluorescent scene is traced on the CPU alone and sent to a remote
/// worker as `SceneState::fluorescence`. An `Arc` so a fan-out's clones share the sampling
/// tables the first trace builds.
pub fluorescence: Arc<Fluorescence>,
/// Frosted girdle: `girdle_facet_finishes(&active_planes)` when
/// `RenderContext::girdle_frosted` was on at capture time, empty otherwise --
/// already resolved here (rather than a bare `bool` re-classified per batch) since
/// `active_planes` never changes mid-export.
pub facet_finishes: Vec<FacetFinish>,
/// A loaded HDR environment map, captured from `RenderContext::env_map` exactly
/// like the live viewport reads it. `None` means the export uses the analytic
/// studio rig. `run_export`'s `environment`
/// binding reads this via the same `as_deref().map_or_else(studio,
/// EnvironmentSource::HdrMap)` `render_thread::mod` uses, so an export renders an
/// HDR map exactly like the live viewport does: the GPU megakernel has its own
/// `env_mode` for `HdrMap` and renders it directly, falling back to
/// the CPU tracer only on the same generic per-frame decline every other scene
/// gets, not an HDR-specific one.
///
/// `Arc`, not a bare `EnvironmentMap`: a decoded panorama can be tens of
/// megabytes, and this snapshot is cloned once per fanned-out preset render.
pub env_map: Option<Arc<EnvironmentMap>>,
}
impl SceneSnapshot {
/// # Errors
///
/// Refuses (returning the cutter-facing reason) rather than capturing a scene
/// that would trace as the wrong stone: when `RenderContext::material_unresolved`
/// is already set, or when -- despite that check -- neither `material_override`
/// nor `material_name` resolves to a real material. Every caller must handle
/// this by aborting the export/dispatch/tilt-video render, not by substituting
/// a default material (see `resolve_material`'s own doc comment for why).
pub fn capture(ctx: &Mutex<RenderContext>) -> Result<Self, String> {
Self::capture_finished(ctx, None)
}
/// [`Self::capture`] for a scene that leaves the program (the high-resolution export,
/// the tilt video, the tilt curves): `finished` is the whole stone to draw in place of
/// the planes and concave tools the context holds, which follow the Cut slider.
///
/// `None` -- and an empty `finished`, which would draw nothing -- keeps the context's
/// own stone, so the live remote dispatch and every caller that wants what the viewport
/// shows go through [`Self::capture`] unchanged. The substitute is applied before
/// anything is derived from the planes (the stone-width scale of the material, the
/// frosted-girdle classification), so the whole scene describes one stone.
///
/// # Errors
///
/// The same refusals as [`Self::capture`].
pub fn capture_finished(
ctx: &Mutex<RenderContext>,
finished: Option<&StoneGeometryBuf>,
) -> Result<Self, String> {
let finished = finished.filter(|stone| !stone.planes.is_empty());
let guard = ctx
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(reason) = &guard.material_unresolved {
return Err(reason.clone());
}
let materials = GemMaterial::all_materials();
// A high-resolution export must honour the same RI/custom
// material override the live viewport, tilt sweep and hover preview already
// resolve through -- otherwise the export silently reverts to the by-name
// lookup for the one surface that matters most (the delivered image).
// The override carries the Live Render toolbar's view-only colour too (a plain
// clone while none is in force), so an export, a tilt video and a remote worker
// all render the colour the cutter chose.
let material_override = guard.tinted_material_override();
let Some(material) = resolve_material_with_override(
&materials,
&guard.custom_materials,
material_override.as_ref(),
&guard.material_name,
) else {
return Err(format!(
"'{}' is not a built-in preset or a saved custom material -- nothing to \
export.",
guard.material_name
));
};
// Every one of these sliders/toggles is a property of what the user is looking
// at, so an export has to carry it or the file silently differs from the
// viewport. Applied here (not inside `resolve_material`, which `render_thread`
// shares) via the same `MaterialOverrides`/`apply_material_overrides` path, so
// an export with nothing dialled in stays bit-identical to a plain by-name
// resolve. A fresh `StoneWidthCache` since this runs once per export,
// not once per frame like the live loop's persistent cache.
//
// `active_planes`/`tools` are the stone the scene draws: the finished one when the
// caller passed it, else the context's own. Taken before the overrides, which
// measure the planes.
//
// `active_planes` is a plain `Vec` (a one-shot export capture, not
// `RenderContext`'s hot-path per-frame snapshot), so this is the one actual deep
// copy `capture` makes -- `.to_vec()` off the `Arc<Vec<..>>` (via its
// `Deref<Target = [GpuFacetPlane]>`).
let (active_planes, tools) = finished.map_or_else(
|| (guard.active_planes.to_vec(), guard.active_tools.to_vec()),
|stone| (stone.planes.clone(), stone.tools.clone()),
);
let material = apply_material_overrides(
material,
&MaterialOverrides {
inclusion_sigma_s: guard.inclusion_sigma_s,
c_axis_override: guard.c_axis_override,
edge_rounding_radius: guard.edge_rounding_radius,
stone_width_mm: guard.stone_width_mm,
},
&active_planes,
&mut StoneWidthCache::new(),
);
// Frosted girdle: an empty `Vec` at the off position is
// `trace_spectral_ray_with_finish`'s documented equivalent of
// `trace_spectral_ray` (every facet reads `FacetFinish::default() == Polished`).
let facet_finishes = if guard.girdle_frosted {
girdle_facet_finishes(&active_planes)
} else {
Vec::new()
};
Ok(Self {
yaw: guard.yaw,
pitch: guard.pitch,
distance: guard.distance,
light_yaw: guard.light_yaw,
light_pitch: guard.light_pitch,
material,
lighting_preset: guard.lighting_preset,
max_bounces: guard.max_bounces,
exposure: guard.exposure,
backdrop: guard.backdrop.level(),
surface_glare: guard.surface_glare,
head_shadow_deg: guard.head_shadow_deg,
active_planes,
tools,
fluorescence: guard.active_fluorescence().unwrap_or_default(),
facet_finishes,
// `Arc::clone`, not a deep copy of the decoded panorama.
env_map: guard.env_map.clone(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use glam::Vec3;
/// A high-resolution export must resolve the design's real
/// effective material (RI override / unlisted custom material) exactly as the
/// live viewport, tilt sweep and hover preview do, rather than falling back to
/// a plain by-name lookup that cannot represent an override. Guards
/// `SceneSnapshot::capture` against regressing to a bare `resolve_material` call.
#[test]
fn capture_prefers_the_material_override_over_the_by_name_lookup() {
let override_dispersion = indicatrix::optics::dispersion::DispersionModel::Cauchy {
a: 1.62,
b: 0.0,
c: 0.0,
};
let mut overridden = GemMaterial::diamond();
overridden.name = "Custom RI 1.62".to_string();
overridden.dispersion = override_dispersion;
let with_override = SceneSnapshot::capture(&Mutex::new(RenderContext {
material_name: "Diamond".to_string(),
material_override: Some(overridden),
..Default::default()
}))
.expect("Diamond resolves");
assert_eq!(
with_override.material.dispersion, override_dispersion,
"the override's flattened dispersion (its RI) must reach the exported \
scene, not the by-name material's own dispersion curve"
);
let without_override = SceneSnapshot::capture(&Mutex::new(RenderContext {
material_name: "Diamond".to_string(),
material_override: None,
..Default::default()
}))
.expect("Diamond resolves");
assert_eq!(
without_override.material.dispersion,
GemMaterial::diamond().dispersion,
"with no override, the export keeps resolving by name exactly as before"
);
}
/// The inclusion slider is a property of what the user is looking at, so an
/// export must carry it. Guards `SceneSnapshot::capture`'s override against the
/// regression of "simplifying" it back into a bare `resolve_material` call.
#[test]
fn capture_carries_the_inclusion_setting_into_the_exported_scene() {
let off = SceneSnapshot::capture(&Mutex::new(RenderContext {
inclusion_sigma_s: 0.0,
..Default::default()
}))
.expect("default resolves");
assert_eq!(
off.material.scattering_sigma_s, 0.0,
"the off position must leave the material untouched"
);
let on = SceneSnapshot::capture(&Mutex::new(RenderContext {
inclusion_sigma_s: 1.25,
..Default::default()
}))
.expect("default resolves");
assert_eq!(
on.material.scattering_sigma_s, 1.25,
"a dialled-in inclusion amount must reach the exported scene"
);
assert_eq!(
on.material.scattering_g,
GemMaterial::DEFAULT_SCATTERING_G,
"anisotropy comes from the crate's default, matching the live path"
);
}
/// Crystal-axis override must reach the export, but must leave an isotropic
/// material's `c_axis` alone even when the override is on
/// (`RenderContext::default().material_name` is "Diamond", isotropic).
#[test]
fn capture_carries_the_c_axis_override_into_the_exported_scene() {
let off = SceneSnapshot::capture(&Mutex::new(RenderContext {
c_axis_override: None,
..Default::default()
}))
.expect("default resolves");
assert_eq!(
off.material.c_axis,
GemMaterial::diamond().c_axis,
"the off (\"as cut\") position must leave the material's own c_axis untouched"
);
let on = SceneSnapshot::capture(&Mutex::new(RenderContext {
material_name: "Sapphire".to_string(),
c_axis_override: Some(Vec3::X),
..Default::default()
}))
.expect("Sapphire resolves");
assert_eq!(
on.material.c_axis,
Vec3::X,
"a dialled-in override on an anisotropic material must reach the exported scene"
);
let isotropic_guarded = SceneSnapshot::capture(&Mutex::new(RenderContext {
material_name: "Diamond".to_string(),
c_axis_override: Some(Vec3::X),
..Default::default()
}))
.expect("Diamond resolves");
assert_eq!(
isotropic_guarded.material.c_axis,
GemMaterial::diamond().c_axis,
"an override dialled in for an isotropic material must be ignored, matching \
apply_material_overrides's own guard"
);
}
/// Edge-rounding's own seam guard, same shape as the inclusion test above.
#[test]
fn capture_carries_the_edge_rounding_setting_into_the_exported_scene() {
let off = SceneSnapshot::capture(&Mutex::new(RenderContext {
edge_rounding_radius: 0.0,
..Default::default()
}))
.expect("default resolves");
assert_eq!(
off.material.edge_rounding_radius, 0.0,
"the off position must leave the material untouched"
);
let on = SceneSnapshot::capture(&Mutex::new(RenderContext {
edge_rounding_radius: 0.02,
..Default::default()
}))
.expect("default resolves");
assert_eq!(
on.material.edge_rounding_radius, 0.02,
"a dialled-in edge-rounding radius must reach the exported scene"
);
}
/// The off position must leave `absorption_path_scale` at the base material's
/// default (`1.0`), and a dialled-in width must scale a per-model-unit material (the
/// default Diamond) by `width / 7 mm` and a per-millimetre one by the ratio to the
/// design's measured model-unit girdle width, matching
/// `apply_material_overrides`'s computation exactly.
#[test]
fn capture_carries_the_stone_width_setting_into_the_exported_scene() {
let off = SceneSnapshot::capture(&Mutex::new(RenderContext {
stone_width_mm: 0.0,
..Default::default()
}))
.expect("default resolves");
let face_up = indicatrix::render_setup::MODEL_UNIT_FACE_UP_PATH;
assert_eq!(
off.material.absorption_path_scale,
1.0 / face_up,
"the off position gives a per-model-unit material the face-up calibration scale only"
);
let default_ctx = RenderContext::default();
let model_width = indicatrix::geometry::stone_metrics::measure_solid(
&default_ctx
.active_planes
.iter()
.map(|p| {
(
glam::DVec3::new(
f64::from(p.normal[0]),
f64::from(p.normal[1]),
f64::from(p.normal[2]),
),
-f64::from(p.d),
)
})
.collect::<Vec<_>>(),
)
.expect("default active_planes must measure")
.width_axis;
let on = SceneSnapshot::capture(&Mutex::new(RenderContext {
stone_width_mm: 6.5,
..Default::default()
}))
.expect("default resolves");
let expected_scale = 6.5_f32 / 7.0 / face_up;
assert!(
(on.material.absorption_path_scale - expected_scale).abs() < 1e-4,
"a dialled-in stone width must reach the exported scene as the expected \
absorption_path_scale: got {}, expected {expected_scale}",
on.material.absorption_path_scale
);
// A per-millimetre (band) colour takes the design's model width, and 7 mm while no size
// is set.
let banded = indicatrix::optics::materials::GemMaterial::diamond()
.with_body_color_bands(&[[550.0, 60.0, 0.3]], 1.0);
for (width_mm, expected_mm) in [(0.0_f32, 7.0_f64), (6.5, 6.5)] {
let banded_on = SceneSnapshot::capture(&Mutex::new(RenderContext {
stone_width_mm: width_mm,
material_override: Some(banded.clone()),
..Default::default()
}))
.expect("the override resolves");
let expected = (expected_mm / model_width) as f32;
assert!(
(banded_on.material.absorption_path_scale - expected).abs() < 1e-4,
"{width_mm} mm: got {}, expected {expected}",
banded_on.material.absorption_path_scale
);
}
}
/// The viewport's surface glare reaches the export snapshot, and the default
/// (`1.0`) is what an untouched context captures.
#[test]
fn capture_carries_the_surface_glare_into_the_exported_scene() {
let default = SceneSnapshot::capture(&Mutex::new(RenderContext::default()))
.expect("default resolves");
assert_eq!(default.surface_glare.to_bits(), 1.0f32.to_bits());
let dimmed = SceneSnapshot::capture(&Mutex::new(RenderContext {
surface_glare: 0.25,
..Default::default()
}))
.expect("default resolves");
assert_eq!(dimmed.surface_glare.to_bits(), 0.25f32.to_bits());
}
/// The viewport's head-shadow radius reaches the export snapshot; the default is 16.
#[test]
fn capture_carries_the_head_shadow_into_the_exported_scene() {
let default = SceneSnapshot::capture(&Mutex::new(RenderContext::default()))
.expect("default resolves");
assert_eq!(default.head_shadow_deg.to_bits(), 16.0f32.to_bits());
let off = SceneSnapshot::capture(&Mutex::new(RenderContext {
head_shadow_deg: 0.0,
..Default::default()
}))
.expect("default resolves");
assert_eq!(off.head_shadow_deg.to_bits(), 0.0f32.to_bits());
}
/// The girdle-frosted toggle is captured as a resolved per-facet finish list, not
/// a bare `bool`, so `run_export`/`render_batch` need no further classification.
#[test]
fn capture_carries_the_girdle_frosted_setting_into_the_exported_scene() {
let off = SceneSnapshot::capture(&Mutex::new(RenderContext {
girdle_frosted: false,
..Default::default()
}))
.expect("default resolves");
assert!(
off.facet_finishes.is_empty(),
"the off position must carry no per-facet finish data"
);
let on = SceneSnapshot::capture(&Mutex::new(RenderContext {
girdle_frosted: true,
..Default::default()
}))
.expect("default resolves");
assert_eq!(
on.facet_finishes,
girdle_facet_finishes(&RenderContext::default().active_planes),
"the on position must carry the same classification the live viewport uses"
);
}
/// A finished stone handed to `capture_finished` replaces the context's planes and
/// tools -- and the derived frosted-girdle list follows it -- while an empty one (a
/// design that did not solve) leaves the context's own stone alone.
#[test]
fn capture_finished_draws_the_substitute_stone_and_ignores_an_empty_one() {
let ctx = Mutex::new(RenderContext {
girdle_frosted: true,
..Default::default()
});
let own = ctx.lock().unwrap().active_planes.to_vec();
assert!(own.len() > 4);
let finished = StoneGeometryBuf {
planes: own[..4].to_vec(),
tools: Vec::new(),
placements: Vec::new(),
};
let swapped = SceneSnapshot::capture_finished(&ctx, Some(&finished)).expect("resolves");
assert_eq!(swapped.active_planes, finished.planes);
assert_eq!(
swapped.facet_finishes,
girdle_facet_finishes(&finished.planes),
"the girdle classification describes the substitute stone"
);
let empty = StoneGeometryBuf {
planes: Vec::new(),
tools: Vec::new(),
placements: Vec::new(),
};
let kept = SceneSnapshot::capture_finished(&ctx, Some(&empty)).expect("resolves");
assert_eq!(kept.active_planes, own);
let plain = SceneSnapshot::capture_finished(&ctx, None).expect("resolves");
assert_eq!(plain.active_planes, own);
}
/// The Live Render toolbar's view-only colour must reach the export (and so the tilt
/// video and the remote workers, which all start from this capture), and must stay
/// out of it while the linked open design supplies the colour itself.
#[test]
fn capture_carries_the_view_only_colour_into_the_exported_scene() {
use crate::bridge::render_thread::PlanesOwner;
let yellow = [0.2f32, 0.4, 2.8];
let capture = |view_body_color, planes_owner, material_linked| {
SceneSnapshot::capture(&Mutex::new(RenderContext {
material_name: "Sapphire".to_string(),
view_body_color,
planes_owner,
material_linked,
..Default::default()
}))
.expect("Sapphire resolves")
};
let plain = capture(None, PlanesOwner::Builtin, false);
assert_eq!(
plain.material.absorption,
GemMaterial::sapphire().absorption
);
let tinted = capture(Some(yellow), PlanesOwner::Builtin, false);
assert_eq!(tinted.material.name, "Sapphire");
assert_eq!(
tinted.material.absorption,
GemMaterial::sapphire().with_body_color(yellow).absorption,
"the chosen colour must reach the exported scene"
);
assert_eq!(tinted.material.dispersion, plain.material.dispersion);
let design_driven = capture(Some(yellow), PlanesOwner::Editor { generation: 1 }, true);
assert_eq!(
design_driven.material.absorption, plain.material.absorption,
"while the linked open design drives the colour, the view setting stays out"
);
}
}