Integrate latest upstream after resolving CLI batch conflict

This commit is contained in:
mighty-programmer committed 2026-10-11 13:12:20 +03:00
commit bfa390956b
5 files changed
+324 -37

No files matched your search

+222 -28
View File
@@ -242,6 +242,8 @@ struct Solver<'a> {
valid_list: Vec<(i32, i32)>,
/// Target centres (patch overlaps the hole), row-major.
targets: Vec<bool>,
/// No pixel of the level is [`Px::Void`] (patches inside the grid need no per-pixel check).
no_void: bool,
adapt: Adapt,
/// Cancellation: checked per row band; a cancelled solve's output is discarded.
ctl: photocraft_raster::Interrupt<'a>,
@@ -275,6 +277,23 @@ impl Solver<'_> {
let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r);
let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32;
let mut sum = 0.0f32;
// The usual case: the whole target patch is image. The same sums in the same order as
// below, a row at a time.
if self.no_void && t.0 >= r && t.1 >= r && t.0 + r < w && t.1 + r < h {
let len = (2 * r + 1) as usize * ch;
for dy in -r..=r {
let ti = ((t.1 + dy) as usize * self.w + (t.0 - r) as usize) * ch;
let si = ((s.1 + dy) as usize * self.w + (s.0 - r) as usize) * ch;
for (a, b) in self.img[ti..ti + len].iter().zip(&self.img[si..si + len]) {
let d = a - b;
sum += d * d;
}
if sum > cutoff * full {
return f32::INFINITY;
}
}
return sum / full;
}
let mut n = 0usize;
for dy in -r..=r {
let ty = t.1 + dy;
@@ -505,6 +524,9 @@ impl Solver<'_> {
} else {
Vec::new()
};
// Each target's vote weight, computed once rather than for every pixel it covers.
let weight: Vec<f32> =
cost.iter().zip(&self.targets).map(|(c, t)| if *t && c.is_finite() { (-*c / (2.0 * sigma2)).exp().max(1e-8) } else { 0.0 }).collect();
let img = &*self.img;
let row = |y: usize| -> Vec<(usize, Vec<f32>)> {
let mut out = Vec::new();
@@ -533,7 +555,7 @@ impl Solver<'_> {
}
let s = nnf[ti];
let (sx, sy) = (s.0 - dx, s.1 - dy);
let wt = (-cost[ti] / (2.0 * sigma2)).exp().max(1e-8);
let wt = weight[ti];
let si = (sy as usize * w + sx as usize) * ch;
for c in 0..ch {
let v = if adapted {
@@ -572,9 +594,32 @@ impl Solver<'_> {
}
/// Fill the hole from its edge inwards, one ring at a time: each pixel takes the centre of the
/// source patch that best matches what is already known around it.
/// source patch that best matches what is already known around it (the first such patch in
/// `sources` order on ties).
///
/// The search is exhaustive, but most candidates are rejected early (#2771): the patch's known
/// offsets and pixels are gathered once per front pixel, the filled neighbours' sources (shifted
/// the same way, as in PatchMatch propagation; every 16th source where no neighbour is filled yet)
/// give an upper bound on the best error before the scan, and a candidate's sum of squares is
/// abandoned as soon as it can no longer win. The sum is accumulated in the same order as the
/// full one and only grows, so the chosen source, and the fill, are exactly those of the plain
/// scan.
fn onion_peel(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px], sources: &[(i32, i32)]) {
if ch == 0 {
return;
}
let mut known: Vec<bool> = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect();
// Which source each filled pixel copied (`NONE` until it has been filled), and each valid
// source's index by position, to seed a pixel's search from its filled neighbours.
const NONE: u32 = u32::MAX;
let mut picked = vec![NONE; w * h];
let mut source_at = vec![NONE; w * h];
for (k, &(sx, sy)) in sources.iter().enumerate() {
if let Some(slot) = source_at.get_mut(sy as usize * w + sx as usize) {
*slot = u32::try_from(k).unwrap_or(NONE);
}
}
let side = (2 * r + 1) as usize;
loop {
let front: Vec<usize> = (0..w * h)
.filter(|&i| {
@@ -593,42 +638,107 @@ fn onion_peel(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px],
if front.is_empty() {
break;
}
let best = |&i: &usize| -> Vec<f32> {
let (img_ro, known_ro, picked_ro) = (&*img, &known, &picked);
// The index of the best source for front pixel `i`, or `None` when no pixel around it is
// known (then pixel 0 is copied, as the plain scan did).
let best = |&i: &usize| -> Option<usize> {
let (x, y) = ((i % w) as i32, (i / w) as i32);
let mut best = (f32::INFINITY, (0i32, 0i32));
for &(sx, sy) in sources {
let (mut e, mut n) = (0.0f32, 0usize);
for dy in -r..=r {
for dx in -r..=r {
let (tx, ty) = (x + dx, y + dy);
if tx < 0 || ty < 0 || tx as usize >= w || ty as usize >= h || !known[ty as usize * w + tx as usize] {
continue;
}
let (ti, si) = ((ty as usize * w + tx as usize) * ch, ((sy + dy) as usize * w + (sx + dx) as usize) * ch);
for c in 0..ch {
let d = img[ti + c] - img[si + c];
e += d * d;
}
n += 1;
// The known pixels of the target patch: their offset (in pixels) and their samples, in
// the plain scan's order.
let mut offs: Vec<isize> = Vec::with_capacity(side * side);
let mut tv: Vec<f32> = Vec::with_capacity(side * side * ch);
for dy in -r..=r {
for dx in -r..=r {
let (tx, ty) = (x + dx, y + dy);
if tx < 0 || ty < 0 || tx as usize >= w || ty as usize >= h || !known_ro[ty as usize * w + tx as usize] {
continue;
}
}
if n > 0 && e / (n as f32) < best.0 {
best = (e / n as f32, (sx, sy));
let ti = (ty as usize * w + tx as usize) * ch;
offs.push(dy as isize * w as isize + dx as isize);
tv.extend_from_slice(&img_ro[ti..ti + ch]);
}
}
let si = (best.1.1 as usize * w + best.1.0 as usize) * ch;
img[si..si + ch].to_vec()
if offs.is_empty() {
return None;
}
let n = offs.len() as f32;
// Mean square difference against the source patch centred at `base`, abandoned
// (`None`) as soon as the mean so far exceeds `bound` or reaches `best` (the final
// mean can only be larger).
let ssd = |base: isize, bound: f32, best: f32| -> Option<f32> {
let mut e = 0.0f32;
for (j, (o, t)) in offs.iter().zip(tv.chunks_exact(ch)).enumerate() {
let si = (base + o) as usize * ch;
for (tc, sc) in t.iter().zip(&img_ro[si..si + ch]) {
let d = tc - sc;
e += d * d;
}
if j % 4 == 3 {
let m = e / n;
if m > bound || m >= best {
return None;
}
}
}
Some(e / n)
};
// An upper bound on the best mean (any candidate's mean is one): the best of the filled
// neighbours' sources, each shifted with its neighbour, or, at the hole's edge where no
// neighbour is filled yet, of every 16th source.
let mut bound = f32::INFINITY;
for dy in -1..=1i32 {
for dx in -1..=1i32 {
let (nx, ny) = (x + dx, y + dy);
if nx < 0 || ny < 0 || nx as usize >= w || ny as usize >= h {
continue;
}
let Some(&(sx, sy)) = sources.get(picked_ro[ny as usize * w + nx as usize] as usize) else { continue };
let (cx, cy) = (sx - dx, sy - dy);
if cx < 0 || cy < 0 || cx as usize >= w || cy as usize >= h || source_at[cy as usize * w + cx as usize] == NONE {
continue;
}
if let Some(e) = ssd(cy as isize * w as isize + cx as isize, f32::INFINITY, bound) {
bound = e;
}
}
}
if bound == f32::INFINITY {
for &(sx, sy) in sources.iter().step_by(16) {
if let Some(e) = ssd(sy as isize * w as isize + sx as isize, f32::INFINITY, bound) {
bound = e;
}
}
}
// The plain scan, in order, keeping the first strictly smaller mean: a candidate is
// abandoned once its mean exceeds the bound (the best is at most the bound) or reaches
// the best so far (a tie would not replace it).
let mut best = (f32::INFINITY, None);
for (k, &(sx, sy)) in sources.iter().enumerate() {
if let Some(e) = ssd(sy as isize * w as isize + sx as isize, bound, best.0)
&& e < best.0
{
best = (e, Some(k));
}
}
best.1
};
#[cfg(not(target_arch = "wasm32"))]
let vals: Vec<Vec<f32>> = {
let found: Vec<Option<usize>> = {
use rayon::prelude::*;
front.par_iter().map(best).collect()
};
#[cfg(target_arch = "wasm32")]
let vals: Vec<Vec<f32>> = front.iter().map(best).collect();
for (&i, v) in front.iter().zip(vals) {
img[i * ch..(i + 1) * ch].copy_from_slice(&v);
let found: Vec<Option<usize>> = front.iter().map(best).collect();
// Pixel 0 as it was before this ring (what a pixel with nothing known around it copies).
let first = img[..ch].to_vec();
for (&i, k) in front.iter().zip(found) {
match k.and_then(|k| sources.get(k)) {
// Sources are never hole pixels, so none of them changes during the ring.
Some(&(sx, sy)) => img.copy_within((sy as usize * w + sx as usize) * ch..(sy as usize * w + sx as usize + 1) * ch, i * ch),
None => img[i * ch..(i + 1) * ch].copy_from_slice(&first),
}
known[i] = true;
picked[i] = k.and_then(|k| u32::try_from(k).ok()).unwrap_or(NONE);
}
}
}
@@ -755,7 +865,8 @@ pub fn complete_masked(
prev = Some((lw, lh, limg, Vec::new()));
continue;
}
let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, px: &lpx, valid, valid_list, targets, adapt: p.adapt, ctl: *ctl };
let no_void = !lpx.contains(&Px::Void);
let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, px: &lpx, valid, valid_list, targets, no_void, adapt: p.adapt, ctl: *ctl };
// NNF init: the coarser level's matches scaled up where they land on a valid source,
// random otherwise.
let mut rng = Rng::new(p.seed ^ (li as u64) << 20);
@@ -1137,6 +1248,89 @@ mod tests {
assert_eq!(best_offset(w, h, ch, &img, &hole, 2, 0), None);
}
/// The exhaustive onion peel, as it was before the early-exit search (#2771).
fn onion_peel_plain(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px], sources: &[(i32, i32)]) {
let mut known: Vec<bool> = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect();
loop {
let front: Vec<usize> = (0..w * h)
.filter(|&i| {
let (x, y) = ((i % w) as i32, (i / w) as i32);
!known[i]
&& px[i] == Px::Hole
&& (-1..=1).any(|dy: i32| {
(-1..=1).any(|dx: i32| {
let (nx, ny) = (x + dx, y + dy);
nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize]
})
})
})
.collect();
if front.is_empty() {
return;
}
let vals: Vec<Vec<f32>> = front
.iter()
.map(|&i| {
let (x, y) = ((i % w) as i32, (i / w) as i32);
let mut best = (f32::INFINITY, (0i32, 0i32));
for &(sx, sy) in sources {
let (mut e, mut n) = (0.0f32, 0usize);
for dy in -r..=r {
for dx in -r..=r {
let (tx, ty) = (x + dx, y + dy);
if tx < 0 || ty < 0 || tx as usize >= w || ty as usize >= h || !known[ty as usize * w + tx as usize] {
continue;
}
let (ti, si) = ((ty as usize * w + tx as usize) * ch, ((sy + dy) as usize * w + (sx + dx) as usize) * ch);
for c in 0..ch {
let d = img[ti + c] - img[si + c];
e += d * d;
}
n += 1;
}
}
if n > 0 && e / (n as f32) < best.0 {
best = (e / n as f32, (sx, sy));
}
}
let si = (best.1.1 as usize * w + best.1.0 as usize) * ch;
img[si..si + ch].to_vec()
})
.collect();
for (&i, v) in front.iter().zip(vals) {
img[i * ch..(i + 1) * ch].copy_from_slice(&v);
known[i] = true;
}
}
}
#[test]
fn onion_peel_picks_exactly_what_the_plain_scan_picks() {
let (w, h, ch, r) = (48, 40, 3, 3);
// Noise over a gradient, with the left half repeating every 6 columns: many exact ties.
let mut img = texture(w, h);
for y in 0..h {
for x in 6..w / 2 {
for c in 0..ch {
img[(y * w + x) * ch + c] = img[(y * w + x % 6) * ch + c];
}
}
}
for hole in [disc(w, h, 20.0, 18.0, 7.5), disc(w, h, 34.0, 22.0, 5.0)] {
let px: Vec<Px> = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect();
let near = integral(w, h, &hole);
let sources: Vec<(i32, i32)> = (r..h as i32 - r)
.flat_map(|y| (r..w as i32 - r).map(move |x| (x, y)))
.filter(|&(x, y)| window_count(&near, w, h, x - r, y - r, x + r + 1, y + r + 1) == 0)
.collect();
let (mut fast, mut plain) = (img.clone(), img.clone());
onion_peel(w, h, ch, r, &mut fast, &px, &sources);
onion_peel_plain(w, h, ch, r, &mut plain, &px, &sources);
assert!(fast.iter().zip(&plain).all(|(a, b)| a.to_bits() == b.to_bits()));
assert_ne!(fast, img);
}
}
#[test]
fn synthesis_fills_hole_with_plausible_values() {
let (w, h, ch) = (64, 64, 3);
+29
View File
@@ -105,6 +105,35 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> {
Ok((action, from))
}
/// The actions that `steps` call through Play Action steps, followed transitively, in list order,
/// so a droplet can run without the Actions panel that made it (#2794). Index references in
/// `steps` and in the copies become names, which resolve without the rest of the list. A target
/// that doesn't resolve is left alone: it fails at playback, as it would have before.
pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec<Action> {
fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut Vec<(usize, usize)>) {
for (_, params) in steps.iter_mut().filter(|(id, _)| id == "actions.play") {
let Ok(i) = resolve(list, params, "actions.play") else { continue };
if let (Some(action), Some(obj)) = (list.get(i), params.as_object_mut()) {
obj.insert("action".into(), json!(action.name));
}
queue.push((i, depth));
}
}
let mut queue = Vec::new();
targets(list, steps, 1, &mut queue);
let mut found = std::collections::BTreeMap::new();
while let Some((i, depth)) = queue.pop() {
// Playback stops at 16 levels, so deeper calls never run.
if depth > 16 || found.contains_key(&i) {
continue;
}
let Some(mut action) = list.get(i).cloned() else { continue };
targets(list, &mut action.steps, depth + 1, &mut queue);
found.insert(i, action);
}
found.into_values().collect()
}
fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
+11 -3
View File
@@ -295,6 +295,9 @@ fn create_droplet(s: &mut Session, p: &Value) -> Result<Value> {
// The droplet's output folder replaces recorded saves, and view steps don't apply, as in batch.
steps.retain(|(id, _)| !crate::actions_cmds::shell_save_command(id) && !crate::actions_cmds::shell_view_command(id));
check_known(&steps, cmd)?;
// Play Action steps need their actions when the droplet runs on its own (#2794). Not under
// `actions`: the CLI reads that key as an action set.
let called = crate::actions_cmds::called_actions(&s.actions.list, &mut steps);
let path = if path.ends_with(".pcdroplet") || path.ends_with(".json") { path.to_string() } else { format!("{path}.pcdroplet") };
let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&path));
let steps_json: Vec<Value> = steps.iter().map(|(id, pr)| json!([id, pr])).collect();
@@ -304,12 +307,14 @@ fn create_droplet(s: &mut Session, p: &Value) -> Result<Value> {
options.insert(k.into(), v.clone());
}
}
let droplet = json!({"photocraftDroplet": 1, "name": name, "action": {"name": name, "steps": steps_json}, "options": options});
let mut droplet = json!({"photocraftDroplet": 1, "name": name, "action": {"name": name, "steps": steps_json}, "options": options});
if !called.is_empty() {
droplet["calledActions"] = json!(called);
}
let text = serde_json::to_string_pretty(&droplet).unwrap_or_default();
write_file(&path, text.as_bytes())?;
let shim = p.get("shim").and_then(Value::as_bool).unwrap_or(cfg!(unix));
let shim_path = if shim { Some(write_shim(&path)?) } else { None };
let _ = s;
Ok(json!({"path": path, "shim": shim_path, "steps": steps.len()}))
}
@@ -366,6 +371,9 @@ fn run_droplet(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(q) = opts.get("quality") {
bp["quality"] = q.clone();
}
if let Some(called) = v.get("calledActions") {
bp["calledActions"] = called.clone();
}
let r = s.execute("file.automate.batch", bp)?;
Ok(json!({"droplet": path, "output": output, "files": r["files"], "errors": r["errors"]}))
}
@@ -541,7 +549,7 @@ pub fn specs() -> Vec<CommandSpec> {
"file.automate.createDroplet",
"Create Droplet…",
&["File", "Automate"],
r##"{"path":str (.pcdroplet),"steps":[[id,params]…] (the action),"name":str?,"output":folder?,"format":"same|png|jpg|…"?,"quality":0..12?,"shim":bool=true on Unix (writes <name>.command calling `photocraft-cli droplet`)} → {path, shim}"##,
r##"{"path":str (.pcdroplet),"steps":[[id,params]…] (the action),"name":str?,"output":folder?,"format":"same|png|jpg|…"?,"quality":0..12?,"shim":bool=true on Unix (writes <name>.command calling `photocraft-cli droplet`)} → {path, shim} (the actions its Play Action steps call are saved in the droplet)"##,
native,
create_droplet
),
+49
View File
@@ -145,6 +145,55 @@ fn droplets_are_written_and_run() {
assert!(s.execute("file.automate.createDroplet", json!({"path": path, "steps": [["bogus", {}]]})).is_err());
}
#[test]
fn droplets_carry_the_actions_their_play_steps_call() {
use crate::actions_cmds::Action;
let dir = tmp("droplet-called");
let inputs = images(&dir, 2, 40, 20);
let mut s = Session::new();
let act = |name: &str, steps: Value| -> Action { serde_json::from_value(json!({"name": name, "steps": steps})).unwrap() };
s.actions.list = vec![
act("Unrelated", json!([["image.imageRotation.180", {}]])),
act("Rotate", json!([["image.imageRotation.90cw", {}]])),
// Calls Rotate by index (as the panel records it) and itself (caught at run time).
act("Outer", json!([["actions.play", {"action": 1}]])),
act("Loop", json!([["actions.play", {"action": "Loop"}]])),
];
let make = |s: &mut Session, name: &str, steps: Value| {
let path = format!("{dir}/{name}");
let out = format!("{dir}/out-{name}");
s.execute("file.automate.createDroplet", json!({"path": path, "steps": steps, "format": "png", "output": out, "shim": false})).unwrap()["path"]
.as_str()
.unwrap()
.to_string()
};
let dp = make(&mut s, "Outer", json!([["actions.play", {"action": "Outer"}]]));
let looping = make(&mut s, "Loop", json!([["actions.play", {"action": "Loop"}]]));
let v: Value = serde_json::from_slice(&std::fs::read(&dp).unwrap()).unwrap();
assert!(v.get("actions").is_none(), "the CLI reads `actions` as an action set");
let names: Vec<&str> = v["calledActions"].as_array().unwrap().iter().map(|a| a["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Rotate", "Outer"], "only the called actions, transitively");
// A fresh session, as `photocraft-cli droplet` and the droplet shim use.
let mut fresh = Session::new();
let r = fresh.execute("file.automate.runDroplet", json!({"droplet": dp, "input": [dir.clone()]})).unwrap();
assert_eq!(r["files"].as_array().unwrap().len(), inputs.len(), "{r}");
let out = photocraft_codecs::decode(&std::fs::read(format!("{dir}/out-Outer/img0.png")).unwrap()).unwrap();
assert_eq!(out.dimensions(), (20, 40));
let r = fresh.execute("file.automate.runDroplet", json!({"droplet": looping, "input": [dir.clone()]})).unwrap();
assert_eq!(r["errors"].as_array().unwrap().len(), inputs.len(), "a self-call fails instead of looping: {r}");
// Droplets written before `calledActions` still run.
let old = format!("{dir}/old.pcdroplet");
std::fs::write(
&old,
json!({"photocraftDroplet": 1, "action": {"steps": [["image.imageRotation.90cw", {}]]}, "options": {"output": format!("{dir}/out-old")}}).to_string(),
)
.unwrap();
let r = fresh.execute("file.automate.runDroplet", json!({"droplet": old, "input": [dir.clone()]})).unwrap();
assert_eq!(r["files"].as_array().unwrap().len(), inputs.len(), "{r}");
}
#[test]
fn batch_and_droplets_skip_recorded_view_steps() {
let dir = tmp("view-steps");
+13 -6
View File
@@ -893,12 +893,19 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {
let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string();
// Steps that call another action play it from the caller's actions; the playback stack comes
// along so an action that batches itself is caught as a recursive call.
let actions = crate::actions_cmds::ActionState {
list: s.actions.list.clone(),
playing: s.actions.playing,
playback_stack: s.actions.playback_stack.clone(),
..Default::default()
let list = match p.get("calledActions") {
None | Some(Value::Null) => s.actions.list.clone(),
// A droplet brings the actions it calls (#2794) and runs with those alone.
Some(v) => {
let list: Vec<crate::actions_cmds::Action> =
serde_json::from_value(v.clone()).map_err(|e| EngineError::BadParams { cmd: cmd.into(), msg: format!("\"calledActions\": {e}") })?;
if list.len() > 4096 {
return Err(EngineError::BadParams { cmd: cmd.into(), msg: "\"calledActions\" holds more than 4096 actions".into() });
}
list
}
};
let actions = crate::actions_cmds::ActionState { list, playing: s.actions.playing, playback_stack: s.actions.playback_stack.clone(), ..Default::default() };
let r = process_files(&inputs, &output, &format, SaveOpts::from_params(p), "", &|scratch| {
scratch.actions = actions.clone();
// Reuse a host-granted backend (and its resident model) across inputs. A default or
@@ -1458,7 +1465,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
&["File", "Automate"],
None,
r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"tiffLayers":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"tiffLayers":bool=false,"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
native,
batch
),