Skip to content

Commit 7e4ff5f

Browse files
committed
Merge slideshow-titles into slideshow-templates (origin/main: integration batch 26, storytold#975; no conflicts)
2 parents 6bfe223 + 857c15f commit 7e4ff5f

51 files changed

Lines changed: 1935 additions & 128 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/lightcraft-web/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! LightCraft in the browser: the same egui UI as the desktop app, compiled to WASM.
22
//!
3-
//! Build with `cargo xtask web` (→ `target/web/`), then serve that folder over HTTP (see
3+
//! Build with `cargo xtask web` (→ `target/web-site/`), then serve that folder over HTTP (see
44
//! `docs/web.md`). Differences from the desktop host:
55
//! - the library lives in browser storage (OPFS, or IndexedDB where OPFS can't be written from the
66
//! main thread): catalog journal, presets, view state and prefs are mirrored in memory and

‎apps/lightcraft/src/main.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ fn window_wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
9898
if let eframe::egui_wgpu::WgpuSetup::CreateNew(n) = &mut c.wgpu_setup {
9999
n.instance_descriptor.backends = lightcraft_engine::gpu::backend::window_backends();
100100
n.instance_descriptor.backend_options = lightcraft_engine::gpu::backend::backend_options();
101+
// no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250)
102+
n.instance_descriptor.flags = lightcraft_engine::gpu::backend::instance_flags_from_env(n.instance_descriptor.flags);
101103
}
102104
c
103105
}
@@ -1106,6 +1108,16 @@ mod tests {
11061108
}
11071109
}
11081110

1111+
/// Issue #250: the window's device is created without wgpu's indirect-call validation pipeline,
1112+
/// which Intel Macs' Metal compiler fails to build (the device was lost, the window never opened).
1113+
#[test]
1114+
fn window_has_no_indirect_call_validation_pipeline() {
1115+
let eframe::egui_wgpu::WgpuSetup::CreateNew(n) = window_wgpu_options().wgpu_setup else { panic!("expected CreateNew") };
1116+
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
1117+
assert!(!n.instance_descriptor.flags.contains(eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL));
1118+
}
1119+
}
1120+
11091121
/// Issue #234: Windows opens links with the URL protocol handler (the default browser), not
11101122
/// File Explorer, and passes the whole map link, `?`, `&` and `#` included, as one argument.
11111123
#[test]

‎crates/engine/src/camera_preview.rs‎

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,22 @@ fn to_prophoto() -> Mat3 {
833833
PROPHOTO.from_xyz().mul(&bradford(D65, D50)).mul(&REC2020.to_xyz())
834834
}
835835

836+
/// [`HueSat::apply`] restores the luminance in full only if the table kept at least this share of it. A colour
837+
/// the table darkens to [`NO_LUMINANCE_KEPT`] or less (only near-black noise, whose channels go negative) keeps
838+
/// its colour; in between the two are blended, so noisy shadows show no step.
839+
const MIN_LUMINANCE_KEPT: f32 = 0.25;
840+
const NO_LUMINANCE_KEPT: f32 = 0.15;
841+
842+
/// How much of the table's colour a pixel gets when the table kept `share` of its luminance: 0 up to
843+
/// [`NO_LUMINANCE_KEPT`], 1 from [`MIN_LUMINANCE_KEPT`], a smoothstep between.
844+
fn restore_weight(share: f32) -> f32 {
845+
if !share.is_finite() {
846+
return 0.0;
847+
}
848+
let t = ((share - NO_LUMINANCE_KEPT) / (MIN_LUMINANCE_KEPT - NO_LUMINANCE_KEPT)).clamp(0.0, 1.0);
849+
t * t * (3.0 - 2.0 * t)
850+
}
851+
836852
/// A fitted [`CameraLook::hue_sat`] table, ready to apply to linear Rec.2020 pixels. It changes
837853
/// hue and saturation only: luminance is restored, the camera tone curve owns it.
838854
pub(crate) struct HueSat<'a> {
@@ -852,7 +868,19 @@ impl<'a> HueSat<'a> {
852868
let mul = |m: &[[f32; 3]; 3], v: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2]) };
853869
let out = mul(&self.from, self.table.apply(mul(&self.to, rgb)));
854870
let (before, after) = (luminance_2020(rgb), luminance_2020(out));
855-
if before > 0.0 && after > 0.0 && out.iter().all(|v| v.is_finite()) { out.map(|v| v * before / after) } else { rgb }
871+
// restoring the luminance divides by the table's: near black, where noise makes some channels
872+
// negative, the table can bring it close to 0, and the gain would turn the pixel white (#820)
873+
if before <= 0.0 || after <= 0.0 || !out.iter().all(|v| v.is_finite()) {
874+
return rgb;
875+
}
876+
let w = restore_weight(after / before);
877+
if w >= 1.0 {
878+
return out.map(|v| v * before / after);
879+
}
880+
if w <= 0.0 {
881+
return rgb;
882+
}
883+
std::array::from_fn(|i| rgb[i] + (out[i] * before / after - rgb[i]) * w)
856884
}
857885
}
858886

@@ -1439,6 +1467,61 @@ mod tests {
14391467
assert!(fit_hue_sat(&[], &Mat3::IDENTITY).is_none(), "too few samples");
14401468
}
14411469

1470+
#[test]
1471+
fn hue_sat_never_turns_near_black_noise_white() {
1472+
// a saturating table, as fitted to high-ISO Sony files; near-black noise with mixed-sign channels
1473+
let table = HsvTable { hue_divisions: 4, sat_divisions: 2, val_divisions: 1, data: vec![[10.0, 1.5, 1.0]; 8], srgb_value: false };
1474+
let hue_sat = HueSat::new(&table).unwrap();
1475+
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
1476+
let mut next = || {
1477+
seed ^= seed << 13;
1478+
seed ^= seed >> 7;
1479+
seed ^= seed << 17;
1480+
(seed >> 11) as f32 / (1u64 << 53) as f32 * 2.0 - 1.0
1481+
};
1482+
let mut worst = 0.0f32;
1483+
for _ in 0..200_000 {
1484+
let rgb = [0.002 + 0.004 * next(), 0.002 + 0.004 * next(), 0.002 + 0.004 * next()];
1485+
if luminance_2020(rgb) <= 0.0 {
1486+
continue;
1487+
}
1488+
let out = hue_sat.apply(rgb);
1489+
let scale = rgb.iter().fold(0.0f32, |m, v| m.max(v.abs()));
1490+
worst = worst.max(out.iter().fold(0.0f32, |m, v| m.max(v.abs())) / scale);
1491+
}
1492+
assert!(worst < 20.0, "a near-black pixel came out {worst}× its largest channel");
1493+
}
1494+
1495+
#[test]
1496+
fn hue_sat_restore_weight_blends_smoothly_between_the_thresholds() {
1497+
assert_eq!(restore_weight(0.0), 0.0);
1498+
assert_eq!(restore_weight(NO_LUMINANCE_KEPT), 0.0);
1499+
assert_eq!(restore_weight(MIN_LUMINANCE_KEPT), 1.0);
1500+
assert_eq!(restore_weight(1.0), 1.0);
1501+
assert_eq!(restore_weight(f32::NAN), 0.0);
1502+
// monotonic and without a step: neighbouring shares 0.001 apart differ by little
1503+
let mut last = 0.0f32;
1504+
for i in 0..=400 {
1505+
let w = restore_weight(i as f32 * 0.001);
1506+
assert!(w >= last && w - last < 0.02, "step at {}: {last} → {w}", i as f32 * 0.001);
1507+
last = w;
1508+
}
1509+
}
1510+
1511+
#[test]
1512+
fn hue_sat_keeps_colours_the_table_leaves_bright_exactly_as_before() {
1513+
// the blend only touches colours whose luminance the table cut below MIN_LUMINANCE_KEPT
1514+
let table = HsvTable { hue_divisions: 4, sat_divisions: 2, val_divisions: 1, data: vec![[10.0, 1.5, 1.0]; 8], srgb_value: false };
1515+
let hue_sat = HueSat::new(&table).unwrap();
1516+
let mul = |m: &[[f32; 3]; 3], v: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2]) };
1517+
for rgb in [[0.4, 0.2, 0.1], [0.05, 0.3, 0.2], [0.18, 0.18, 0.18], [0.6, 0.1, 0.5]] {
1518+
let out = mul(&hue_sat.from, table.apply(mul(&hue_sat.to, rgb)));
1519+
let (before, after) = (luminance_2020(rgb), luminance_2020(out));
1520+
assert!(after >= MIN_LUMINANCE_KEPT * before);
1521+
assert_eq!(hue_sat.apply(rgb), out.map(|v| v * before / after));
1522+
}
1523+
}
1524+
14421525
fn raw_of(format: RawFormat, make: &str, model: &str, color: lightcraft_raw::ColorData) -> RawImage {
14431526
let area = lightcraft_raw::Rect::new(0, 0, 2, 2);
14441527
RawImage {

‎crates/engine/src/cmd/develop.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,10 +239,14 @@ pub fn specs() -> Vec<CommandSpec> {
239239
let fresh = match look {
240240
Some(l) => (*l).clone(),
241241
None => {
242+
// the photo's built-in defaults (raws: capture sharpening and colour noise
243+
// reduction, embedded lens corrections), as at import, with the white balance
244+
// of its current as-shot reference
242245
let info = s.source_info(id);
246+
let defaults = s.catalog.photo(id).map(|p| p.camera_defaults()).unwrap_or_default();
243247
DevelopSettings {
244248
wb: lightcraft_develop::WhiteBalance { mode: WbMode::AsShot, temp: info.as_shot_temp, tint: info.as_shot_tint },
245-
..Default::default()
249+
..defaults
246250
}
247251
}
248252
};

‎crates/engine/src/cmd/query.rs‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ fn photo_arg(s: &Session, p: &Value, c: &str) -> crate::Result<PhotoId> {
5959
}
6060
}
6161

62+
// Catalog queries also run in the 32-bit web build. A narrowing cast wraps
63+
// an out-of-range offset to zero, returning the first page instead of no photos.
64+
fn pagination_usize(value: u64) -> usize {
65+
usize::try_from(value).unwrap_or(usize::MAX)
66+
}
67+
6268
pub fn specs() -> Vec<CommandSpec> {
6369
vec![
6470
cmd!(query "catalog.query", "Query Photos", [], None, "{filter?: Filter, sort?: Sort, offset?, limit?} — omit filter to list the current view", always, |s, p| {
@@ -69,8 +75,8 @@ pub fn specs() -> Vec<CommandSpec> {
6975
} else {
7076
s.visible_cloned()
7177
};
72-
let off = p.get("offset").and_then(Value::as_u64).unwrap_or(0) as usize;
73-
let lim = p.get("limit").and_then(Value::as_u64).unwrap_or(200) as usize;
78+
let off = pagination_usize(p.get("offset").and_then(Value::as_u64).unwrap_or(0));
79+
let lim = pagination_usize(p.get("limit").and_then(Value::as_u64).unwrap_or(200));
7480
let items: Vec<Value> = ids.iter().skip(off).take(lim).filter_map(|id| s.catalog.photo(*id)).map(|p| photo_summary(p)).collect();
7581
Ok(json!({"total": ids.len(), "photos": items}))
7682
}),
@@ -237,3 +243,17 @@ pub fn specs() -> Vec<CommandSpec> {
237243
}),
238244
]
239245
}
246+
247+
#[cfg(test)]
248+
mod pagination_tests {
249+
use super::*;
250+
251+
#[test]
252+
fn offsets_and_limits_saturate_instead_of_wrapping_on_wasm() {
253+
assert_eq!(pagination_usize(0), 0);
254+
assert_eq!(pagination_usize(200), 200);
255+
assert_eq!(pagination_usize(u64::MAX), usize::MAX);
256+
#[cfg(target_pointer_width = "32")]
257+
assert_eq!(pagination_usize(u64::from(u32::MAX) + 1), usize::MAX);
258+
}
259+
}

‎crates/engine/src/media.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ impl SettingsHashes {
6262
}
6363

6464
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
65-
pub const RENDER_CACHE_VERSION: u64 = 42;
65+
pub const RENDER_CACHE_VERSION: u64 = 50;
6666

6767
/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
6868
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];

‎crates/engine/src/tests.rs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,33 @@ fn changing_one_wb_control_resolves_as_shot_without_stale_tint() {
3737
}
3838
}
3939

40+
/// Reset Edits on a raw goes back to its import defaults, capture sharpening and colour noise
41+
/// reduction included (#763: reset left both at 0 while import sets 40 / 25); a rendered file
42+
/// keeps none.
43+
#[test]
44+
fn reset_edits_restores_a_raws_import_defaults() {
45+
use lightcraft_catalog::{Photo, PhotoId, Source};
46+
use lightcraft_develop::DevelopSettings;
47+
let mut s = demo();
48+
for (id, format, raw) in [(200u64, "NEF", true), (201, "JPG", false)] {
49+
let name = format!("p{id}.{format}");
50+
let mut p = Photo::new(PhotoId(id), Source::File { path: name.clone() }, &name, format, 16, 16, "");
51+
if raw {
52+
p.as_shot_wb = Some((5200.0, 4.0));
53+
p.develop = std::sync::Arc::new(DevelopSettings::for_raw(5200.0, 4.0));
54+
}
55+
s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(p) }).unwrap();
56+
}
57+
for (id, want) in [(200, (40.0, 25.0)), (201, (0.0, 0.0))] {
58+
s.execute("library.select", &json!({"ids": [id], "active": id})).unwrap();
59+
s.execute("develop.set", &json!({"control": "detail.sharpenAmount", "value": 90})).unwrap();
60+
s.execute("develop.set", &json!({"control": "detail.nrColor", "value": 70})).unwrap();
61+
s.execute("develop.reset", &json!({})).unwrap();
62+
let d = active_dev(&s);
63+
assert_eq!((d.detail.sharpen_amount, d.detail.nr_color), want, "photo {id}");
64+
}
65+
}
66+
4067
#[test]
4168
fn demo_library_loads() {
4269
let mut s = demo();

‎crates/engine/src/tests_sync.rs‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ impl Scratch {
3232
Scratch(dir)
3333
}
3434
fn path(&self, rel: &str) -> String {
35-
self.0.join(rel).to_string_lossy().to_string()
35+
// Fixtures use `/`; rebuild components so expected paths match the native separators
36+
// returned by directory scans, including for files that have already been removed.
37+
self.0.join(rel).components().collect::<PathBuf>().to_string_lossy().into_owned()
3638
}
3739
}
3840

@@ -103,6 +105,68 @@ fn an_unchanged_folder_has_no_changes() {
103105
assert!(paths(&r, "new").is_empty() && paths(&r, "missing").is_empty() && paths(&r, "metadata").is_empty(), "{r}");
104106
}
105107

108+
#[cfg(windows)]
109+
#[test]
110+
fn importing_and_synchronizing_with_different_windows_separators_keeps_photo_identity() {
111+
for forward_import in [true, false] {
112+
for import_folder in [true, false] {
113+
let dir = Scratch::new(&format!("separators-{forward_import}-{import_folder}"));
114+
let folder = dir.path("trip");
115+
let a = dir.path("trip/a.png");
116+
let b = dir.path("trip/day1/b.png");
117+
write_png(&a, 1);
118+
write_png(&b, 2);
119+
let spelling = |path: &str, forward: bool| if forward { path.replace('\\', "/") } else { path.to_string() };
120+
let import_path = spelling(&folder, forward_import);
121+
let sync_path = spelling(&folder, !forward_import);
122+
assert_ne!(import_path, sync_path, "exercise distinct Windows path spellings");
123+
let inputs = if import_folder { vec![import_path.clone()] } else { vec![spelling(&a, forward_import), spelling(&b, forward_import)] };
124+
let mut s = Session::new().with_fs();
125+
let imported = s.execute("library.import", &json!({"paths": inputs})).unwrap();
126+
assert_eq!(imported["imported"].as_array().unwrap().len(), 2, "{imported}");
127+
let before = s.execute("catalog.query", &json!({})).unwrap();
128+
let photos = before["photos"].as_array().unwrap();
129+
let a_id = photos.iter().find(|p| p["fileName"] == "a.png").unwrap()["id"].clone();
130+
let b_id = photos.iter().find(|p| p["fileName"] == "b.png").unwrap()["id"].clone();
131+
132+
let duplicate = s.execute("library.import", &json!({"paths": [sync_path]})).unwrap();
133+
assert!(duplicate["imported"].as_array().unwrap().is_empty(), "{duplicate}");
134+
assert_eq!(duplicate["duplicates"].as_array().unwrap().len(), 2, "{duplicate}");
135+
assert_eq!(s.execute("catalog.query", &json!({})).unwrap(), before, "reimport preserves the photos and their ids");
136+
137+
std::fs::remove_file(&b).unwrap();
138+
let c = dir.path("trip/day2/c.png");
139+
write_png(&c, 3);
140+
let changes = scan(&mut s, &sync_path);
141+
assert_eq!(changes["new"].as_array().unwrap().len(), 1, "{changes}");
142+
assert_eq!(Path::new(changes["new"][0]["path"].as_str().unwrap()), Path::new(&c));
143+
assert_eq!(changes["missing"].as_array().unwrap().len(), 1, "{changes}");
144+
assert_eq!(changes["missing"][0]["id"], b_id, "the missing photo keeps its id");
145+
assert!(changes["moved"].as_array().unwrap().is_empty(), "{changes}");
146+
147+
// Switching spelling again must consume the confirmed scan of this same folder.
148+
let synced = s.execute("folder.synchronize", &json!({"path": import_path, "scanned": true, "removeMissing": true})).unwrap();
149+
assert_eq!(
150+
(synced["imported"].as_u64(), synced["removed"].as_u64(), synced["relinked"].as_u64()),
151+
(Some(1), Some(1), Some(0)),
152+
"{synced}"
153+
);
154+
assert!(synced["failed"].as_array().unwrap().is_empty(), "{synced}");
155+
let after = s.execute("catalog.query", &json!({})).unwrap();
156+
let photos = after["photos"].as_array().unwrap();
157+
assert_eq!(photos.len(), 2, "{after}");
158+
assert!(photos.iter().any(|p| p["id"] == a_id && p["fileName"] == "a.png"), "{after}");
159+
assert!(photos.iter().any(|p| p["fileName"] == "c.png" && p["id"] != a_id && p["id"] != b_id), "{after}");
160+
for path in [&import_path, &sync_path] {
161+
let changes = scan(&mut s, path);
162+
for kind in ["new", "missing", "moved", "metadata"] {
163+
assert!(changes[kind].as_array().unwrap().is_empty(), "{path}: {changes}");
164+
}
165+
}
166+
}
167+
}
168+
}
169+
106170
#[test]
107171
fn files_added_to_the_folder_or_a_folder_inside_it_are_new() {
108172
let dir = Scratch::new("new");

‎crates/gpu/src/backend.rs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,25 @@ pub fn backend_options() -> wgpu::BackendOptions {
145145
o
146146
}
147147

148+
/// wgpu's instance flags for every instance LightCraft creates, from `flags` (wgpu's defaults with its
149+
/// environment variables applied) without `VALIDATION_INDIRECT_CALL`, unless
150+
/// `WGPU_VALIDATION_INDIRECT_CALL` asks for it (any value but `0`). That validation builds an internal
151+
/// compute pipeline when each device is created; Intel Macs' Metal compiler fails on it ("Compiler
152+
/// encountered an internal error"), the device is lost and the window never opens (#250). It only
153+
/// guards indirect draws and dispatches, which neither LightCraft nor egui issue.
154+
pub fn instance_flags(flags: wgpu::InstanceFlags, env: Option<&str>) -> wgpu::InstanceFlags {
155+
if env.is_some_and(|v| v != "0") {
156+
flags | wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL
157+
} else {
158+
flags - wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL
159+
}
160+
}
161+
162+
/// [`instance_flags`] with `WGPU_VALIDATION_INDIRECT_CALL` read from the environment.
163+
pub fn instance_flags_from_env(flags: wgpu::InstanceFlags) -> wgpu::InstanceFlags {
164+
instance_flags(flags, std::env::var("WGPU_VALIDATION_INDIRECT_CALL").ok().as_deref())
165+
}
166+
148167
/// `LIGHTCRAFT_GPU_BACKEND=off`.
149168
pub(crate) fn env_off() -> bool {
150169
env_choice() == BackendChoice::Off
@@ -195,6 +214,17 @@ pub fn read_init_marker(path: &std::path::Path) -> Option<String> {
195214
#[cfg(test)]
196215
#[allow(clippy::unwrap_used)]
197216
mod tests {
217+
218+
/// #250: the indirect-call validation pipeline is off unless asked for; other flags are kept.
219+
#[test]
220+
fn indirect_call_validation_is_off_unless_asked_for() {
221+
use wgpu::InstanceFlags as F;
222+
let base = F::VALIDATION_INDIRECT_CALL | F::DEBUG;
223+
assert_eq!(instance_flags(base, None), F::DEBUG);
224+
assert_eq!(instance_flags(base, Some("0")), F::DEBUG);
225+
assert_eq!(instance_flags(F::empty(), Some("1")), F::VALIDATION_INDIRECT_CALL);
226+
assert_eq!(instance_flags(F::empty(), None), F::empty());
227+
}
198228
use super::*;
199229

200230
#[test]

‎crates/gpu/src/ctx.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,8 @@ impl Gpu {
284284
desc.backends = backends;
285285
// DX12 shaders compile with FXC (issue #471)
286286
desc.backend_options = crate::backend::backend_options();
287+
// no indirect-call validation pipeline: Intel Metal fails to compile it (#250)
288+
desc.flags = crate::backend::instance_flags_from_env(desc.flags);
287289
let instance = wgpu::Instance::new(desc);
288290
let adapter = pollster::block_on(
289291
instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }),

0 commit comments

Comments
 (0)