From 4524c480a00ffd4fe9f315c20a453a78ed2ee36a Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:47:26 +0100 Subject: [PATCH 1/7] Photomerge: one History step and the reference's targeted layers (#14094) The result opened with only its opening state in History and the top layer targeted. It now opens as the reference application leaves it: the first snapshot plus one state, "Auto-Blend Layers" with Blend Images Together on (the snapshot holds the aligned layers without their seam masks, and every source layer is targeted), "Move" with it off (only the bottom layer is targeted), or "Fill" with the fill option. --- crates/engine/src/cmd/photo_cmds.rs | 45 ++++++- .../photo_cmds/photomerge_history_tests.rs | 121 ++++++++++++++++++ 2 files changed, 164 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs diff --git a/crates/engine/src/cmd/photo_cmds.rs b/crates/engine/src/cmd/photo_cmds.rs index c10d0bf5a64..d7814dd1e5c 100644 --- a/crates/engine/src/cmd/photo_cmds.rs +++ b/crates/engine/src/cmd/photo_cmds.rs @@ -1010,13 +1010,51 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { }), )) }, - |s, (doc, mut info): (Document, Value)| { - info["document"] = json!(s.add_document(doc, None)); + move |s, (doc, mut info): (Document, Value)| { + info["document"] = json!(open_photomerge_result(s, doc, blend, fill)); Ok(info) }, ) } +/// Opens a Photomerge result with the History and the targeted layers Photoshop leaves (#14094). +/// The History panel holds the first snapshot and one state named after the merge's last step: +/// "Fill" with the fill option, else "Auto-Blend Layers" with Blend Images Together on and "Move" +/// with it off. The Auto-Blend snapshot holds the aligned layers without their seam masks, so +/// going back to it leaves them unblended. Blend on targets every source layer, Blend off only +/// the bottom one (the last source); the fill result keeps today's target, its top layer. +fn open_photomerge_result(s: &mut Session, doc: Document, blend: bool, fill: bool) -> usize { + let label = match (blend, fill) { + (true, true) => "Fill", + (true, false) => "Auto-Blend Layers", + (false, _) => "Move", + }; + let unblended = (blend && !fill).then(|| { + let mut d = doc.clone(); + for l in &mut d.layers { + l.mask = None; + } + d + }); + let all: Vec = doc.layers.iter().map(|l| l.id).collect(); + let bottom = doc.layers.first().map(|l| l.id); + let idx = s.add_document(doc, None); + if let Some(st) = s.active_mut() { + st.history.set_current_label(label); + // The first snapshot (History Options › Automatically Create First Snapshot) is the + // document before the step; without it the state before the step is not kept. + if let (Some(d), Some(first)) = (unblended, st.snapshots.first_mut().filter(|snap| snap.id == 0)) { + first.doc = std::sync::Arc::new(d); + } + } + match (blend, fill) { + (true, false) => crate::layer_multi_cmds::reselect(s, all, None), + (false, _) => crate::layer_multi_cmds::reselect(s, bottom.into_iter().collect(), bottom), + (true, true) => {} + } + idx +} + /// Fills the transparent areas of a composite (inside its bounding rectangle) with /// content-aware fill, at a reduced scale for large panoramas. fn content_aware_fill(comp: &Surface, canvas: Rect) -> Surface { @@ -1415,3 +1453,6 @@ mod tests; #[cfg(test)] mod photomerge_name_tests; + +#[cfg(test)] +mod photomerge_history_tests; diff --git a/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs b/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs new file mode 100644 index 00000000000..eae44b2764c --- /dev/null +++ b/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs @@ -0,0 +1,121 @@ +//! A Photomerge result opens with the History and targeted layers Photoshop leaves (#14094): the +//! first snapshot plus one state, "Auto-Blend Layers" (Blend Images Together on, every source +//! layer targeted), "Move" (Blend off, only the bottom layer targeted) or "Fill" (the fill option). + +use super::*; + +/// One colour per 5x5 block of a 700x300 scene, hashed from the block, over a horizontal ramp. +fn scene_pixel(x: usize, y: usize) -> [f32; 4] { + let h = ((x / 5) as u64 * 73_856_093 ^ (y / 5) as u64 * 19_349_663).wrapping_mul(0x9E37_79B9_7F4A_7C15); + let c = |shift: u32| ((h >> shift) & 0xff) as f32 / 255.0; + [0.5 * c(8) + 0.5 * x as f32 / 700.0, c(24), c(40), 1.0] +} + +/// A session with t1.tif, t2.tif and t3.tif open: 300x300 tiles of the scene cut at x 0, 200 +/// and 400, so neighbours overlap by 100 px (the issue's measured set). +fn tiles() -> Session { + let mut s = Session::new(); + for (k, x0) in [0usize, 200, 400].into_iter().enumerate() { + let mut d = Document::new(format!("t{}.tif", k + 1), Size::new(300, 300), ColorMode::Rgb, SampleType::U8); + let fmt = d.pixel_format(); + let mut data = vec![0.0f32; 300 * 300 * fmt.channels()]; + for (i, o) in data.chunks_exact_mut(fmt.channels()).enumerate() { + photocraft_raster::from_rgba_into(&fmt, scene_pixel(x0 + i % 300, i / 300), o); + } + let mut surf = Surface::new(fmt); + surf.write_region(Rect::new(0, 0, 300, 300), &data); + d.layers.push(Layer::new("Background", LayerContent::Raster(surf))); + s.add_document(d, None); + } + s +} + +/// Merges the open tiles and returns the result's History rows (the first snapshot excluded). +fn merge(s: &mut Session, params: Value) -> Vec { + let mut p = json!({"useOpenDocuments": true}); + p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone()); + let r = s.execute("file.automate.photomerge", p).unwrap(); + assert_eq!(r["placed"].as_array().map(Vec::len), Some(3), "{r}"); + assert_eq!(r["document"], json!(3), "the result is a new, fourth document"); + s.active().unwrap().history.entries() +} + +/// The targeted layers' names, top of the Layers panel first. +fn targeted(s: &Session) -> Vec { + let st = s.active().unwrap(); + st.selected_layers().iter().rev().map(|id| st.doc.layer(*id).unwrap().name.clone()).collect() +} + +/// The layer names from the top of the Layers panel down, with whether each has a mask. +fn stack(s: &Session) -> Vec<(String, bool)> { + s.active().unwrap().doc.layers.iter().rev().map(|l| (l.name.clone(), l.mask.is_some())).collect() +} + +/// `names` from the top down, each with (`masked`) or without a mask. +fn expect(names: &[&str], masked: bool) -> Vec<(String, bool)> { + names.iter().map(|n| (n.to_string(), masked)).collect() +} + +const SOURCES: [&str; 3] = ["t1.tif", "t2.tif", "t3.tif"]; + +#[test] +fn blend_on_is_one_auto_blend_layers_step_targeting_every_source() { + for layout in ["reposition", "collage", "perspective"] { + let mut s = tiles(); + assert_eq!(merge(&mut s, json!({"layout": layout})), ["Auto-Blend Layers"], "{layout}"); + assert_eq!(stack(&s), expect(&SOURCES, true), "{layout}"); + assert_eq!(targeted(&s), SOURCES, "{layout}: every source layer is targeted"); + let st = s.active().unwrap(); + assert_eq!(st.active_layer, st.doc.top_layer(), "{layout}: the top layer stays the key layer"); + let inspect = s.execute("document.inspect", json!({})).unwrap(); + assert_eq!(inspect["selectedLayers"].as_array().map(Vec::len), Some(3), "{layout}: {inspect}"); + // The first snapshot stays, named after the document. + assert_eq!(st.snapshots.len(), 1, "{layout}"); + assert_eq!(st.snapshots[0].name, st.doc.name, "{layout}"); + } +} + +#[test] +fn going_back_before_auto_blend_leaves_the_aligned_layers_without_masks() { + let mut s = tiles(); + merge(&mut s, json!({"layout": "reposition"})); + let blended: Document = (*s.active().unwrap().doc).clone(); + s.execute("history.selectSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(stack(&s), expect(&SOURCES, false)); + let st = s.active().unwrap(); + for (now, then) in st.doc.layers.iter().zip(&blended.layers) { + let (a, b) = (now.surface().unwrap(), then.surface().unwrap()); + let area = Rect::new(0, 0, blended.size.width as i32, blended.size.height as i32); + assert_eq!(a.read_region(area), b.read_region(area), "{}: the aligned pixels are kept", now.name); + } + assert_eq!(st.doc.size, blended.size); + // Selecting the snapshot is a state of its own; undoing it brings the masks back. + assert_eq!(st.history.entries(), ["Auto-Blend Layers".to_string(), st.doc.name.clone()]); + s.execute("history.undo", json!({})).unwrap(); + assert_eq!(stack(&s), expect(&SOURCES, true)); + assert_eq!(targeted(&s), SOURCES, "the Auto-Blend Layers state targets every source"); +} + +#[test] +fn blend_off_is_one_move_step_targeting_only_the_bottom_layer() { + let mut s = tiles(); + assert_eq!(merge(&mut s, json!({"layout": "reposition", "blend": false})), ["Move"]); + assert_eq!(stack(&s), expect(&SOURCES, false)); + assert_eq!(targeted(&s), ["t3.tif"], "only the last source, the bottom layer"); + let st = s.active().unwrap(); + assert_eq!(st.active_layer, st.doc.layers.first().map(|l| l.id)); + let inspect = s.execute("document.inspect", json!({})).unwrap(); + assert_eq!(inspect["selectedLayers"], json!([st.doc.layers[0].id.0]), "{inspect}"); + assert_eq!(inspect["activeLayer"], json!(st.doc.layers[0].id.0), "{inspect}"); +} + +#[test] +fn fill_is_one_fill_step_without_auto_blend_layers() { + let mut s = tiles(); + assert_eq!(merge(&mut s, json!({"layout": "reposition", "contentAwareFill": true})), ["Fill"]); + // Not measured: the target after the fill keeps today's, the top (filled) layer. + let st = s.active().unwrap(); + assert_eq!(st.selected_layers(), st.doc.top_layer().into_iter().collect::>()); + assert_eq!(stack(&s).len(), 4); + assert!(stack(&s)[1..].iter().all(|(_, masked)| *masked), "the sources keep their seam masks"); +} From 58131df9eee4b4d96eb5e26b548cf42163f9dc16 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:54:20 +0100 Subject: [PATCH 2/7] Photomerge history tests: inspect before borrowing the session; parenthesize the hash --- .../engine/src/cmd/photo_cmds/photomerge_history_tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs b/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs index eae44b2764c..2466aee682c 100644 --- a/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs +++ b/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs @@ -6,7 +6,7 @@ use super::*; /// One colour per 5x5 block of a 700x300 scene, hashed from the block, over a horizontal ramp. fn scene_pixel(x: usize, y: usize) -> [f32; 4] { - let h = ((x / 5) as u64 * 73_856_093 ^ (y / 5) as u64 * 19_349_663).wrapping_mul(0x9E37_79B9_7F4A_7C15); + let h = (((x / 5) as u64 * 73_856_093) ^ ((y / 5) as u64 * 19_349_663)).wrapping_mul(0x9E37_79B9_7F4A_7C15); let c = |shift: u32| ((h >> shift) & 0xff) as f32 / 255.0; [0.5 * c(8) + 0.5 * x as f32 / 700.0, c(24), c(40), 1.0] } @@ -65,10 +65,10 @@ fn blend_on_is_one_auto_blend_layers_step_targeting_every_source() { assert_eq!(merge(&mut s, json!({"layout": layout})), ["Auto-Blend Layers"], "{layout}"); assert_eq!(stack(&s), expect(&SOURCES, true), "{layout}"); assert_eq!(targeted(&s), SOURCES, "{layout}: every source layer is targeted"); - let st = s.active().unwrap(); - assert_eq!(st.active_layer, st.doc.top_layer(), "{layout}: the top layer stays the key layer"); let inspect = s.execute("document.inspect", json!({})).unwrap(); assert_eq!(inspect["selectedLayers"].as_array().map(Vec::len), Some(3), "{layout}: {inspect}"); + let st = s.active().unwrap(); + assert_eq!(st.active_layer, st.doc.top_layer(), "{layout}: the top layer stays the key layer"); // The first snapshot stays, named after the document. assert_eq!(st.snapshots.len(), 1, "{layout}"); assert_eq!(st.snapshots[0].name, st.doc.name, "{layout}"); @@ -102,9 +102,9 @@ fn blend_off_is_one_move_step_targeting_only_the_bottom_layer() { assert_eq!(merge(&mut s, json!({"layout": "reposition", "blend": false})), ["Move"]); assert_eq!(stack(&s), expect(&SOURCES, false)); assert_eq!(targeted(&s), ["t3.tif"], "only the last source, the bottom layer"); + let inspect = s.execute("document.inspect", json!({})).unwrap(); let st = s.active().unwrap(); assert_eq!(st.active_layer, st.doc.layers.first().map(|l| l.id)); - let inspect = s.execute("document.inspect", json!({})).unwrap(); assert_eq!(inspect["selectedLayers"], json!([st.doc.layers[0].id.0]), "{inspect}"); assert_eq!(inspect["activeLayer"], json!(st.doc.layers[0].id.0), "{inspect}"); } From 2c23818c1c31fc690b93f707665f40e4a67270a3 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 06:52:10 +0100 Subject: [PATCH 3/7] Photomerge: the Auto-Blend snapshot holds the aligned pixels from before the blend Removing the masks from the blended layers kept their gain-compensated and seam-blended pixels. Keep the warped surfaces through the blend instead (sharing their tiles), charge them against the memory budget, and build the snapshot's layers from them. --- crates/engine/src/cmd/photo_cmds.rs | 42 +++++++++++++------ .../photo_cmds/photomerge_history_tests.rs | 35 +++++++++++----- 2 files changed, 54 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/photo_cmds.rs b/crates/engine/src/cmd/photo_cmds.rs index d7814dd1e5c..3917dd8608d 100644 --- a/crates/engine/src/cmd/photo_cmds.rs +++ b/crates/engine/src/cmd/photo_cmds.rs @@ -930,6 +930,11 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { let warped_sizes: Vec<(usize, usize)> = extents.iter().map(|&(w, h)| ((w.ceil() + 1.0).max(0.0).min(cw) as usize, (h.ceil() + 1.0).max(0.0).min(ch) as usize)).collect(); let (est_needed, fixed_during_bands) = estimate_photomerge_memory(&sizes, &warped_sizes, cw as usize, ch as usize, cc, bpp, blend, fill); + // Auto-Blend Layers' first snapshot keeps the aligned layers (#14094): their warped + // pixels stay alive through the blend instead of being freed as it reads them. + let kept = + if blend && !fill { warped_sizes.iter().map(|&(w, h)| w.saturating_mul(h)).fold(0usize, usize::saturating_add).saturating_mul(bpp) } else { 0 }; + let (est_needed, fixed_during_bands) = (est_needed.saturating_add(kept), fixed_during_bands.saturating_add(kept)); if est_needed > budget { let mb_est = est_needed / (1 << 20); let mb_budget = budget / (1 << 20); @@ -958,6 +963,7 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { let mut doc = Document::new(doc_name, Size::new(cw as u32, ch as u32), fmt.mode, fmt.sample); doc.icc_profile = icc; let mut info = json!({}); + let mut unblended = None; let ref_pos = placed.iter().position(|&i| i == al.reference).unwrap_or(0); if blend { let pls: Vec = placements.iter().map(|p| (*p).clone()).collect(); @@ -965,6 +971,8 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { let geo = vignette.then_some((pls.as_slice(), sizes.as_slice(), offset)); let remaining_band_budget = budget.saturating_sub(fixed_during_bands); let check_cancel = || ctx.check(); + // Shares the tiles: the cost is the `kept` bytes charged above. + let aligned = (!fill).then(|| warped.clone()); let opt = BlendOptions { seamless: true, gains: true, geometry: geo, budget: Some(remaining_band_budget) }; let b = seam_blend(warped, canvas, &order, opt, Some(&check_cancel))?; // `children[0]` is the bottom layer, and the first source goes on top. @@ -975,6 +983,7 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { l.mask = Some(m); doc.layers.push(l); } + unblended = aligned.map(|aligned| unblended_layers(&doc, aligned)); info = json!({"gains": b.gains, "vignette": b.vignette}); ctx.check()?; if fill { @@ -1008,34 +1017,41 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { "photometric": info, "ms": {"register": t_reg * 1000.0, "warp": (t_warp - t_reg) * 1000.0, "total": t0.ms()}, }), + unblended, )) }, - move |s, (doc, mut info): (Document, Value)| { - info["document"] = json!(open_photomerge_result(s, doc, blend, fill)); + move |s, (doc, mut info, unblended): (Document, Value, Option)| { + info["document"] = json!(open_photomerge_result(s, doc, unblended, blend, fill)); Ok(info) }, ) } +/// The blended Photomerge `doc` as it was before Auto-Blend Layers: the same layers (names, ids, +/// order) holding the `aligned` pixels, in source order, without seam masks. +fn unblended_layers(doc: &Document, aligned: Vec) -> Document { + let mut d = doc.clone(); + // `children[0]` is the bottom layer, the last source. + for (l, px) in d.layers.iter_mut().zip(aligned.into_iter().rev()) { + l.content = LayerContent::Raster(px); + l.mask = None; + } + d +} + /// Opens a Photomerge result with the History and the targeted layers Photoshop leaves (#14094). /// The History panel holds the first snapshot and one state named after the merge's last step: /// "Fill" with the fill option, else "Auto-Blend Layers" with Blend Images Together on and "Move" -/// with it off. The Auto-Blend snapshot holds the aligned layers without their seam masks, so -/// going back to it leaves them unblended. Blend on targets every source layer, Blend off only -/// the bottom one (the last source); the fill result keeps today's target, its top layer. -fn open_photomerge_result(s: &mut Session, doc: Document, blend: bool, fill: bool) -> usize { +/// with it off. The Auto-Blend snapshot holds `unblended`, the aligned layers before blending +/// ([`unblended_layers`]), so going back to it undoes the blend. Blend on targets every source +/// layer, Blend off only the bottom one (the last source); the fill result keeps today's target, +/// its top layer. +fn open_photomerge_result(s: &mut Session, doc: Document, unblended: Option, blend: bool, fill: bool) -> usize { let label = match (blend, fill) { (true, true) => "Fill", (true, false) => "Auto-Blend Layers", (false, _) => "Move", }; - let unblended = (blend && !fill).then(|| { - let mut d = doc.clone(); - for l in &mut d.layers { - l.mask = None; - } - d - }); let all: Vec = doc.layers.iter().map(|l| l.id).collect(); let bottom = doc.layers.first().map(|l| l.id); let idx = s.add_document(doc, None); diff --git a/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs b/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs index 2466aee682c..1709236165b 100644 --- a/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs +++ b/crates/engine/src/cmd/photo_cmds/photomerge_history_tests.rs @@ -12,15 +12,18 @@ fn scene_pixel(x: usize, y: usize) -> [f32; 4] { } /// A session with t1.tif, t2.tif and t3.tif open: 300x300 tiles of the scene cut at x 0, 200 -/// and 400, so neighbours overlap by 100 px (the issue's measured set). -fn tiles() -> Session { +/// and 400, so neighbours overlap by 100 px (the issue's measured set). t2.tif's colours are +/// scaled by `t2_exposure`, which Auto-Blend Layers' gain compensation then evens out. +fn exposed_tiles(t2_exposure: f32) -> Session { let mut s = Session::new(); for (k, x0) in [0usize, 200, 400].into_iter().enumerate() { let mut d = Document::new(format!("t{}.tif", k + 1), Size::new(300, 300), ColorMode::Rgb, SampleType::U8); let fmt = d.pixel_format(); let mut data = vec![0.0f32; 300 * 300 * fmt.channels()]; for (i, o) in data.chunks_exact_mut(fmt.channels()).enumerate() { - photocraft_raster::from_rgba_into(&fmt, scene_pixel(x0 + i % 300, i / 300), o); + let [r, g, b, a] = scene_pixel(x0 + i % 300, i / 300); + let e = if k == 1 { t2_exposure } else { 1.0 }; + photocraft_raster::from_rgba_into(&fmt, [r * e, g * e, b * e, a], o); } let mut surf = Surface::new(fmt); surf.write_region(Rect::new(0, 0, 300, 300), &data); @@ -30,6 +33,11 @@ fn tiles() -> Session { s } +/// [`exposed_tiles`] with the three tiles exposed alike. +fn tiles() -> Session { + exposed_tiles(1.0) +} + /// Merges the open tiles and returns the result's History rows (the first snapshot excluded). fn merge(s: &mut Session, params: Value) -> Vec { let mut p = json!({"useOpenDocuments": true}); @@ -76,19 +84,26 @@ fn blend_on_is_one_auto_blend_layers_step_targeting_every_source() { } #[test] -fn going_back_before_auto_blend_leaves_the_aligned_layers_without_masks() { - let mut s = tiles(); +fn going_back_before_auto_blend_restores_the_aligned_layers_without_masks() { + // t2.tif darker, so blending changes its pixels, not only its mask. + let mut s = exposed_tiles(0.7); merge(&mut s, json!({"layout": "reposition"})); let blended: Document = (*s.active().unwrap().doc).clone(); + // The aligned layers before blending: what the same merge gives with Blend off. + let mut unblended = exposed_tiles(0.7); + merge(&mut unblended, json!({"layout": "reposition", "blend": false})); + let aligned: Document = (*unblended.active().unwrap().doc).clone(); s.execute("history.selectSnapshot", json!({"snapshot": 0})).unwrap(); assert_eq!(stack(&s), expect(&SOURCES, false)); let st = s.active().unwrap(); - for (now, then) in st.doc.layers.iter().zip(&blended.layers) { - let (a, b) = (now.surface().unwrap(), then.surface().unwrap()); - let area = Rect::new(0, 0, blended.size.width as i32, blended.size.height as i32); - assert_eq!(a.read_region(area), b.read_region(area), "{}: the aligned pixels are kept", now.name); + assert_eq!(st.doc.size, aligned.size); + let area = Rect::new(0, 0, aligned.size.width as i32, aligned.size.height as i32); + let pixels = |l: &Layer| l.surface().unwrap().read_region(area); + for ((now, before), after) in st.doc.layers.iter().zip(&aligned.layers).zip(&blended.layers) { + assert_eq!(now.id, after.id, "{}: the snapshot keeps the result's layers", now.name); + assert!(pixels(now) == pixels(before), "{}: the snapshot holds the aligned, unblended pixels", now.name); } - assert_eq!(st.doc.size, blended.size); + assert!(pixels(&blended.layers[1]) != pixels(&aligned.layers[1]), "the blend changed t2.tif's pixels"); // Selecting the snapshot is a state of its own; undoing it brings the masks back. assert_eq!(st.history.entries(), ["Auto-Blend Layers".to_string(), st.doc.name.clone()]); s.execute("history.undo", json!({})).unwrap(); From 424cc8c5473b89c1adea97d84d228311622fcc90 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:51:05 +0100 Subject: [PATCH 4/7] Photomerge: assert one aligned surface per layer in the pre-blend snapshot --- crates/engine-core/src/cmd/photo_cmds.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index 3917dd8608d..f9dcd2ff363 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -1031,6 +1031,8 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { /// order) holding the `aligned` pixels, in source order, without seam masks. fn unblended_layers(doc: &Document, aligned: Vec) -> Document { let mut d = doc.clone(); + // One aligned surface per layer: a mismatch would leave layers blended in the snapshot. + debug_assert_eq!(d.layers.len(), aligned.len(), "one aligned surface per Photomerge layer"); // `children[0]` is the bottom layer, the last source. for (l, px) in d.layers.iter_mut().zip(aligned.into_iter().rev()) { l.content = LayerContent::Raster(px); From b2006754bc6749d70cb2ec6c0132f6a0b93d3523 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:58:32 +0100 Subject: [PATCH 5/7] Photomerge: reach the snapshots through DocState's accessors on main --- crates/engine-core/src/cmd/photo_cmds.rs | 5 ++++- .../src/cmd/photo_cmds/photomerge_history_tests.rs | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index f9dcd2ff363..41f10529b53 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -1061,7 +1061,10 @@ fn open_photomerge_result(s: &mut Session, doc: Document, unblended: Option Date: Mon, 23 Nov 2026 18:12:22 +0100 Subject: [PATCH 6/7] Photomerge: keep the aligned layers through the blend only when a first snapshot will hold them With History Options > Automatically Create First Snapshot off, the result has no snapshot for the aligned layers, so the warped surfaces are no longer cloned before the blend and their bytes are no longer added to the memory estimate or taken off the band budget. --- crates/engine-core/src/cmd/photo_cmds.rs | 11 +++--- .../photo_cmds/photomerge_history_tests.rs | 34 +++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index 41f10529b53..a5971b9ef60 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -880,6 +880,9 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { // Resolved before loading: the sources are flattened and retained one at a time, so the // budget has to bound them before the first surface is allocated, not after they all exist. let budget = photomerge_memory_budget(p); + // Auto-Blend Layers' first snapshot keeps the aligned layers (#14094). Without a first + // snapshot (History Options) nothing would hold them, so they are not kept through the blend. + let keep_aligned = blend && !fill && s.prefs().history_options.automatically_create_first_snapshot; let (mut srcs, fmt, icc) = load_sources(s, p, cmd, Some(budget))?; if srcs.len() < 2 { return Err(bad(cmd, "Photomerge needs two or more images")); @@ -930,10 +933,10 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { let warped_sizes: Vec<(usize, usize)> = extents.iter().map(|&(w, h)| ((w.ceil() + 1.0).max(0.0).min(cw) as usize, (h.ceil() + 1.0).max(0.0).min(ch) as usize)).collect(); let (est_needed, fixed_during_bands) = estimate_photomerge_memory(&sizes, &warped_sizes, cw as usize, ch as usize, cc, bpp, blend, fill); - // Auto-Blend Layers' first snapshot keeps the aligned layers (#14094): their warped - // pixels stay alive through the blend instead of being freed as it reads them. + // The aligned layers kept for the first snapshot: their warped pixels stay alive + // through the blend instead of being freed as it reads them. let kept = - if blend && !fill { warped_sizes.iter().map(|&(w, h)| w.saturating_mul(h)).fold(0usize, usize::saturating_add).saturating_mul(bpp) } else { 0 }; + if keep_aligned { warped_sizes.iter().map(|&(w, h)| w.saturating_mul(h)).fold(0usize, usize::saturating_add).saturating_mul(bpp) } else { 0 }; let (est_needed, fixed_during_bands) = (est_needed.saturating_add(kept), fixed_during_bands.saturating_add(kept)); if est_needed > budget { let mb_est = est_needed / (1 << 20); @@ -972,7 +975,7 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { let remaining_band_budget = budget.saturating_sub(fixed_during_bands); let check_cancel = || ctx.check(); // Shares the tiles: the cost is the `kept` bytes charged above. - let aligned = (!fill).then(|| warped.clone()); + let aligned = keep_aligned.then(|| warped.clone()); let opt = BlendOptions { seamless: true, gains: true, geometry: geo, budget: Some(remaining_band_budget) }; let b = seam_blend(warped, canvas, &order, opt, Some(&check_cancel))?; // `children[0]` is the bottom layer, and the first source goes on top. diff --git a/crates/engine-core/src/cmd/photo_cmds/photomerge_history_tests.rs b/crates/engine-core/src/cmd/photo_cmds/photomerge_history_tests.rs index 3d661a40fc6..5123c251a9c 100644 --- a/crates/engine-core/src/cmd/photo_cmds/photomerge_history_tests.rs +++ b/crates/engine-core/src/cmd/photo_cmds/photomerge_history_tests.rs @@ -134,3 +134,37 @@ fn fill_is_one_fill_step_without_auto_blend_layers() { assert_eq!(stack(&s).len(), 4); assert!(stack(&s)[1..].iter().all(|(_, masked)| *masked), "the sources keep their seam masks"); } + +/// Whether the open tiles merge (Blend on, no fill) within `budget` bytes of working memory. +fn merges_within(budget: u64, first_snapshot: bool) -> bool { + let mut s = tiles(); + s.edit_prefs(|p| p.history_options.automatically_create_first_snapshot = first_snapshot); + s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition", "memoryBudget": budget})).is_ok() +} + +/// With History Options › Automatically Create First Snapshot off there is no snapshot to hold +/// the aligned layers, so they are not kept through the blend and their bytes are not charged: +/// the merge fits a budget one byte below the least one it needs with the snapshot on. +#[test] +fn without_a_first_snapshot_the_aligned_layers_are_not_charged() { + // The least budget the merge passes with while it keeps the aligned layers. + let (mut fails, mut passes) = (0u64, 1u64 << 30); + assert!(!merges_within(fails, true) && merges_within(passes, true)); + while passes - fails > 1 { + let mid = fails + (passes - fails) / 2; + if merges_within(mid, true) { + passes = mid; + } else { + fails = mid; + } + } + assert!(!merges_within(passes - 1, true), "one byte less is refused while the aligned layers are kept"); + assert!(merges_within(passes - 1, false), "nothing is kept without a first snapshot, so nothing more is charged"); + // The result is the same merge: one state, every source masked and targeted, no snapshot. + let mut s = tiles(); + s.edit_prefs(|p| p.history_options.automatically_create_first_snapshot = false); + assert_eq!(merge(&mut s, json!({"layout": "reposition", "memoryBudget": passes - 1})), ["Auto-Blend Layers"]); + assert_eq!(stack(&s), expect(&SOURCES, true)); + assert_eq!(targeted(&s), SOURCES); + assert!(s.active().unwrap().snapshots().is_empty()); +} From 333503ee231730570e2e520bf308a33599908b7f Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:31:56 +0100 Subject: [PATCH 7/7] Photomerge: the first-snapshot budget test searches to 64 KiB, not to the byte The aligned layers are about 1 MB for the test tiles, so a budget within 64 KiB below the least passing one tells the two cases apart with a third of the merges. --- .../photo_cmds/photomerge_history_tests.rs | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/crates/engine-core/src/cmd/photo_cmds/photomerge_history_tests.rs b/crates/engine-core/src/cmd/photo_cmds/photomerge_history_tests.rs index 5123c251a9c..06da794ec37 100644 --- a/crates/engine-core/src/cmd/photo_cmds/photomerge_history_tests.rs +++ b/crates/engine-core/src/cmd/photo_cmds/photomerge_history_tests.rs @@ -143,14 +143,19 @@ fn merges_within(budget: u64, first_snapshot: bool) -> bool { } /// With History Options › Automatically Create First Snapshot off there is no snapshot to hold -/// the aligned layers, so they are not kept through the blend and their bytes are not charged: -/// the merge fits a budget one byte below the least one it needs with the snapshot on. +/// the aligned layers, so they are not kept through the blend and their bytes (about 1 MB for +/// these tiles) are not charged: the merge fits a budget that is too small by less than 64 KiB +/// while they are kept. #[test] fn without_a_first_snapshot_the_aligned_layers_are_not_charged() { - // The least budget the merge passes with while it keeps the aligned layers. - let (mut fails, mut passes) = (0u64, 1u64 << 30); - assert!(!merges_within(fails, true) && merges_within(passes, true)); - while passes - fails > 1 { + // A budget the merge is refused with while it keeps the aligned layers, at most 64 KiB + // below one it passes with. + let (mut fails, mut passes) = (0u64, 1u64 << 20); + while !merges_within(passes, true) { + (fails, passes) = (passes, passes * 2); + assert!(passes <= 1 << 30, "the merge needs more than 1 GiB"); + } + while passes - fails > 64 << 10 { let mid = fails + (passes - fails) / 2; if merges_within(mid, true) { passes = mid; @@ -158,12 +163,12 @@ fn without_a_first_snapshot_the_aligned_layers_are_not_charged() { fails = mid; } } - assert!(!merges_within(passes - 1, true), "one byte less is refused while the aligned layers are kept"); - assert!(merges_within(passes - 1, false), "nothing is kept without a first snapshot, so nothing more is charged"); + assert!(!merges_within(fails, true), "refused while the aligned layers are kept"); + assert!(merges_within(fails, false), "nothing is kept without a first snapshot, so nothing more is charged"); // The result is the same merge: one state, every source masked and targeted, no snapshot. let mut s = tiles(); s.edit_prefs(|p| p.history_options.automatically_create_first_snapshot = false); - assert_eq!(merge(&mut s, json!({"layout": "reposition", "memoryBudget": passes - 1})), ["Auto-Blend Layers"]); + assert_eq!(merge(&mut s, json!({"layout": "reposition", "memoryBudget": fails})), ["Auto-Blend Layers"]); assert_eq!(stack(&s), expect(&SOURCES, true)); assert_eq!(targeted(&s), SOURCES); assert!(s.active().unwrap().snapshots().is_empty());