Merge #15396 into the merge queue batch

Photomerge: one History step and the reference's targeted layers (#14094)
This commit is contained in:
David Mann committed 2026-11-29 00:52:17 +01:00
commit 7a76a70a01
2 files changed
+242 -2

No files matched your search

+67 -2
View File
@@ -880,6 +880,9 @@ fn photomerge(s: &mut Session, p: &Value) -> Result<Value> {
// 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,6 +933,11 @@ fn photomerge(s: &mut Session, p: &Value) -> Result<Value> {
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);
// 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 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);
let mb_budget = budget / (1 << 20);
@@ -958,6 +966,7 @@ fn photomerge(s: &mut Session, p: &Value) -> Result<Value> {
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<Placement> = placements.iter().map(|p| (*p).clone()).collect();
@@ -965,6 +974,8 @@ fn photomerge(s: &mut Session, p: &Value) -> Result<Value> {
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 = 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.
@@ -975,6 +986,7 @@ fn photomerge(s: &mut Session, p: &Value) -> Result<Value> {
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,15 +1020,65 @@ fn photomerge(s: &mut Session, p: &Value) -> Result<Value> {
"photometric": info,
"ms": {"register": t_reg * 1000.0, "warp": (t_warp - t_reg) * 1000.0, "total": t0.ms()},
}),
unblended,
))
},
|s, (doc, mut info): (Document, Value)| {
info["document"] = json!(s.add_document(doc, None));
move |s, (doc, mut info, unblended): (Document, Value, Option<Document>)| {
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<Surface>) -> 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);
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 `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<Document>, blend: bool, fill: bool) -> usize {
let label = match (blend, fill) {
(true, true) => "Fill",
(true, false) => "Auto-Blend Layers",
(false, _) => "Move",
};
let all: Vec<photocraft_doc::LayerId> = 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) = unblended
&& st.snapshots().first().is_some_and(|snap| snap.id == 0)
&& let Some(first) = st.snapshots_mut().first_mut()
{
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 +1477,6 @@ mod tests;
#[cfg(test)]
mod photomerge_name_tests;
#[cfg(test)]
mod photomerge_history_tests;
@@ -0,0 +1,175 @@
//! 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). 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 = crate::session();
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() {
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);
d.layers.push(Layer::new("Background", LayerContent::Raster(surf)));
s.add_document(d, None);
}
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<String> {
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<String> {
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 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}");
}
}
#[test]
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();
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!(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();
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 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));
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::<Vec<_>>());
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 (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() {
// 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;
} else {
fails = mid;
}
}
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": fails})), ["Auto-Blend Layers"]);
assert_eq!(stack(&s), expect(&SOURCES, true));
assert_eq!(targeted(&s), SOURCES);
assert!(s.active().unwrap().snapshots().is_empty());
}