diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3a9404d3..6223cded 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2200,10 +2200,25 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u /// One flattened tile of one channel: (channel, tile, premultiplied value + coverage data). pub type FlatTile = (Channel, (u32, u32), Vec); +/// One tile of a layer's mask (with its geometry mask and mask with height), u16 per texel. +pub type MaskTile = ((u32, u32), Vec); + /// Flatten one paint or fill layer: its content (with content effects) times its mask, as /// premultiplied (value, coverage) tiles per enabled channel, ready to become a plain paint /// layer. Groups are not supported (None). pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> { + flatten(inputs, id, tiles, false).map(|(content, _)| content) +} + +/// [`flatten_layer`] with the mask kept apart: the content tiles hold the content alone +/// (premultiplied by its own coverage), and the mask tiles the layer's mask as it shapes the +/// content (geometry mask and mask with height included), over the same tiles. For an image +/// editor's layer mask. Groups are not supported (None). +pub fn flatten_layer_masked_apart(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<(Vec, Vec)> { + flatten(inputs, id, tiles, true) +} + +fn flatten(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], apart: bool) -> Option<(Vec, Vec)> { let set = inputs.project.texture_set(inputs.ts).ok()?; if inputs.project.content_layer(id)?.is_group() { return None; @@ -2219,11 +2234,12 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti let visible_inputs = Inputs { project: &solo, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; let fields = neighbourhood_fields(&visible_inputs, &channels, tiles); - let out: Vec> = tiles + let out: Vec<(Vec, Option)> = tiles .par_iter() .map(|&(tx, ty)| { let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); - let Some(n) = nodes.first() else { return Vec::new() }; + let Some(n) = nodes.first() else { return (Vec::new(), None) }; + let mut mask = apart.then(|| vec![0u16; TILE_AREA]); let full = anchor_plan(&visible_inputs, id, &channels, tx, ty, Some(&fields)); let mut buffers: Vec<(Channel, Vec, bool)> = n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect(); @@ -2241,6 +2257,11 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti tex.anchors_below(&full, id); } let m = tex.node_mask(n); + if let Some(slot) = mask.as_mut().and_then(|t| t.get_mut(o)) { + *slot = to_u16(m); + } + // Kept apart, the mask leaves the content's own coverage alone. + let m = if apart { 1.0 } else { m }; for (c, (ch, buffer, any)) in n.chans.iter().zip(buffers.iter_mut()) { let Some((v, cov)) = tex.content(&n.content, c) else { continue }; let a = (cov * m).clamp(0.0, 1.0); @@ -2260,11 +2281,18 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti } } - buffers.into_iter().filter(|(_, _, any)| *any).map(|(ch, buffer, _)| (ch, (tx, ty), buffer)).collect() + let content = buffers.into_iter().filter(|(_, _, any)| *any).map(|(ch, buffer, _)| (ch, (tx, ty), buffer)).collect(); + (content, mask.map(|m| ((tx, ty), m))) }) .collect(); - Some(out.into_iter().flatten().collect()) + let mut content = Vec::new(); + let mut masks = Vec::new(); + for (c, m) in out { + content.extend(c); + masks.extend(m); + } + Some((content, masks)) } #[cfg(test)] diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index fe57e611..f30651fd 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -20,6 +20,6 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_at, mask_image, pad_tiles, + flatten_layer_masked_apart, mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 346ff0cf..6657d316 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -39,6 +39,7 @@ pub mod orb_preview; pub mod painting; pub mod path_tool; pub mod photocraft_cmds; +pub mod photocraft_psd; mod polygon_fill; mod polygon_fill_drag; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/photocraft_cmds.rs b/crates/engine/src/photocraft_cmds.rs index 99dc988c..0c7f5438 100644 --- a/crates/engine/src/photocraft_cmds.rs +++ b/crates/engine/src/photocraft_cmds.rs @@ -1,12 +1,18 @@ -//! PhotoCraft hand-off: a texture set's layer stack as layered OpenRaster documents (one per -//! channel) opened in PhotoCraft, and PhotoCraft's saves shown live. +//! PhotoCraft hand-off: a texture set's layer stack opened in PhotoCraft, and PhotoCraft's +//! saves shown live. //! -//! Every layer is rendered alone (content with its fill sources, generators, filters and -//! content effects, times its mask: [`Session::flatten`]) into a layer of the same name, so the -//! mask becomes the layer's transparency; folders become groups. Each sent file is remembered -//! as a [`Link`]: when PhotoCraft saves it, its merged image becomes the image source of a -//! `PhotoCraft: ` fill at the top of the set, which leaves the layers below untouched. -//! The apps share the file format and the command line, not code. +//! By default every texture set goes as one layered PSD holding all its channels, each layer +//! a group with its real mask (see [`crate::photocraft_psd`]). The `ora` format instead writes +//! one OpenRaster document per channel, where every layer is rendered alone (content with its +//! fill sources, generators, filters and content effects, times its mask: +//! [`Session::flatten`]) so the mask becomes the layer's transparency; folders become groups. +//! +//! Each sent file is remembered as a [`Link`]: when PhotoCraft saves it, every channel it holds +//! becomes the image source of a `PhotoCraft: ` fill at the top of the set (one undo +//! step), which leaves the layers below untouched. The apps share the file format and the +//! command line, not code. + +use std::collections::BTreeMap; use serde_json::{Value, json}; use texturecraft_core::{BlendMode, Channel, ChannelKind, LayerId, LayerKind}; @@ -29,11 +35,13 @@ pub fn specs() -> Vec { "Send layers to PhotoCraft...", ["File"], None, - "{dir, ts?: index|\"all\" (default: the active set), channels?: [channel ids] (default: the set's channels), open?: true} → {files, warnings} — writes __.ora per set and channel (every layer rendered with its mask as transparency, folders as groups) and opens them in PhotoCraft; saves made there show live (see photocraft.links)", + "{dir, ts?: index|\"all\" (default: the active set), channels?: [channel ids] (default: the set's channels), format?: \"psd\"|\"ora\" (default psd), open?: true} → {files, warnings} — psd: writes _.psd per set, every layer a group with its editable mask and one layer per channel inside, a layer comp per channel; ora: writes __.ora per set and channel, every layer rendered with its mask as transparency. Opens them in PhotoCraft; saves made there show live (see photocraft.links)", always, send ), - cmd!("photocraft.links", "List PhotoCraft links", [], None, "{} → [{path, ts, channel, layer?}]", always, |s, _| Ok(links_json(s))), + cmd!("photocraft.links", "List PhotoCraft links", [], None, "{} → [{path, ts, format, channels, layers: {channel: layer id}}]", always, |s, _| Ok( + links_json(s) + )), cmd!( "photocraft.sync", "Update from PhotoCraft", @@ -47,16 +55,36 @@ pub fn specs() -> Vec { ] } +/// How a texture set is sent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Format { + /// One layered PSD per texture set with every channel. + Psd, + /// One OpenRaster document per texture set and channel. + Ora, +} + +impl Format { + pub fn id(self) -> &'static str { + match self { + Format::Psd => "psd", + Format::Ora => "ora", + } + } +} + /// A file sent to PhotoCraft, watched for its saves. #[derive(Clone, Debug, PartialEq)] pub struct Link { pub path: std::path::PathBuf, pub ts: usize, - pub channel: Channel, + pub format: Format, + /// The channels the file holds (one for OpenRaster). + pub channels: Vec, /// The file's modification time when it was last read or written. pub modified: Option, - /// The `PhotoCraft: ` fill showing the file's merged image, once there is one. - pub layer: Option, + /// The `PhotoCraft: ` fills showing what the file holds, once there are some. + pub layers: BTreeMap, } /// The session's PhotoCraft links (not saved with the project). @@ -73,7 +101,13 @@ pub(crate) fn links_json(s: &Session) -> Value { s.photocraft .links .iter() - .map(|l| json!({"path": l.path.display().to_string(), "ts": l.ts, "channel": l.channel.id(), "layer": l.layer.map(|id| id.0)})) + .map(|l| json!({ + "path": l.path.display().to_string(), + "ts": l.ts, + "format": l.format.id(), + "channels": l.channels.iter().map(|c| c.id()).collect::>(), + "layers": l.layers.iter().map(|(c, id)| (c.id().to_string(), json!(id.0))).collect::>(), + })) .collect::>() ) } @@ -129,7 +163,7 @@ fn texel(c: Channel, px: &[u16]) -> Option<[u16; 4]> { } /// The canvas-sized image of channel `c` in flattened tiles. -fn flat_image(c: Channel, (w, h): (u32, u32), tiles: &[texturecraft_compose::eval::FlatTile]) -> Rgba16 { +pub(crate) fn flat_image(c: Channel, (w, h): (u32, u32), tiles: &[texturecraft_compose::eval::FlatTile]) -> Rgba16 { let mut img = Rgba16::transparent(w, h); let stride = c.components() + 1; for (_, (tx, ty), buf) in tiles.iter().filter(|(ch, _, _)| *ch == c) { @@ -148,8 +182,19 @@ fn flat_image(c: Channel, (w, h): (u32, u32), tiles: &[texturecraft_compose::eva img } +/// Channel value `v` as an opaque hand-off pixel (sRGB colour, signed values around 0.5). +pub(crate) fn encode_value(c: Channel, v: [f32; 3]) -> [u16; 4] { + let rgb = match c.kind() { + ChannelKind::Color => v.map(|v| linear_to_srgb(v.clamp(0.0, 1.0))), + ChannelKind::NormalMap => v, + ChannelKind::Scalar => [v[0]; 3], + ChannelKind::Signed => [v[0] * 0.5 + 0.5; 3], + }; + [to_u16(rgb[0]), to_u16(rgb[1]), to_u16(rgb[2]), 65535] +} + /// The set's composite of channel `c`: opaque where the mesh covers the texture. -fn merged_image(s: &Session, ts: usize, c: Channel) -> Result { +pub(crate) fn merged_image(s: &Session, ts: usize, c: Channel) -> Result { let cache = s.caches.get(ts).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?; let (w, h) = cache.size; let coverage = cache.gbuf.coverage_mask(); @@ -160,15 +205,8 @@ fn merged_image(s: &Session, ts: usize, c: Channel) -> Result { if !coverage.get(i).copied().unwrap_or(false) { continue; } - let v = cache.composite.value(c, x, y); - let rgb = match c.kind() { - ChannelKind::Color => v.map(|v| linear_to_srgb(v.clamp(0.0, 1.0))), - ChannelKind::NormalMap => v, - ChannelKind::Scalar => [v[0]; 3], - ChannelKind::Signed => [v[0] * 0.5 + 0.5; 3], - }; if let Some(dst) = img.data.get_mut(i * 4..i * 4 + 4) { - dst.copy_from_slice(&[to_u16(rgb[0]), to_u16(rgb[1]), to_u16(rgb[2]), 65535]); + dst.copy_from_slice(&encode_value(c, cache.composite.value(c, x, y))); } } } @@ -289,10 +327,19 @@ fn send(s: &mut Session, p: &Value) -> Result { let dir = std::path::PathBuf::from(dir); let sets = sets_param(s, p)?; let open = p.get("open").and_then(Value::as_bool).unwrap_or(true); - let mut jobs = Vec::new(); + let format = match p.get("format") { + None | Some(Value::Null) => Format::Psd, + Some(v) if v.as_str() == Some("psd") => Format::Psd, + Some(v) if v.as_str() == Some("ora") => Format::Ora, + Some(v) => return Err(bad(SEND, format!("unknown format {v}: use \"psd\" or \"ora\""))), + }; + let mut jobs: Vec<(usize, Vec)> = Vec::new(); for &ts in &sets { - for c in channels_param(s, ts, p)? { - jobs.push((ts, c)); + let channels = channels_param(s, ts, p)?; + match format { + Format::Psd if !channels.is_empty() => jobs.push((ts, channels)), + Format::Psd => {} + Format::Ora => jobs.extend(channels.into_iter().map(|c| (ts, vec![c]))), } } if jobs.is_empty() { @@ -302,21 +349,34 @@ fn send(s: &mut Session, p: &Value) -> Result { let mesh = std::path::Path::new(s.doc.project.mesh.trim_start_matches("builtin:")).file_stem().and_then(|n| n.to_str()).unwrap_or("Untitled").to_string(); let mut files = Vec::new(); let mut warnings = Vec::new(); - for (ts, c) in jobs { + for (ts, channels) in jobs { let set_name = s.doc.project.texture_set(ts).map(|t| t.name.clone()).unwrap_or_default(); - let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh}_{set_name}_{}", c.id())); - let path = dir.join(format!("{stem}.{}", ora::ORA_EXT)); + let (stem, ext) = match (format, channels.first()) { + (Format::Ora, Some(c)) => (format!("{mesh}_{set_name}_{}", c.id()), ora::ORA_EXT), + _ => (format!("{mesh}_{set_name}"), texturecraft_formats::psd::PSD_EXT), + }; + let path = dir.join(format!("{}.{ext}", texturecraft_formats::export::sanitize_file_stem(&stem))); if files.contains(&path) { warnings.push(format!("texture set \"{set_name}\" sends as {} like an earlier set, so it was skipped; rename one of them", path.display())); continue; } - let (bytes, w) = s.photocraft_document(ts, c)?; - warnings.extend(w.into_iter().map(|w| format!("{set_name} {}: {w}", c.label()))); + let (bytes, w) = match (format, channels.first()) { + (Format::Ora, Some(&c)) => { + let (bytes, w) = s.photocraft_document(ts, c)?; + (bytes, w.into_iter().map(|w| format!("{set_name} {}: {w}", c.label())).collect::>()) + } + _ => { + let (bytes, w) = s.photocraft_psd(ts, &channels)?; + (bytes, w.into_iter().map(|w| format!("{set_name}: {w}")).collect()) + } + }; + warnings.extend(w); texturecraft_formats::write_atomic(&path, &bytes).map_err(|e| bad(SEND, format!("cannot write {}: {e}", path.display())))?; let modified = std::fs::metadata(&path).and_then(|m| m.modified()).ok(); - let layer = s.photocraft.links.iter().find(|l| l.path == path).and_then(|l| l.layer); + // Sending again keeps the fills an earlier save made. + let layers = s.photocraft.links.iter().find(|l| l.path == path && l.ts == ts).map(|l| l.layers.clone()).unwrap_or_default(); s.photocraft.links.retain(|l| l.path != path); - s.photocraft.links.push(Link { path: path.clone(), ts, channel: c, modified, layer }); + s.photocraft.links.push(Link { path: path.clone(), ts, format, channels, modified, layers }); files.push(path); } s.log.push(format!("Sent {} documents to {}", files.len(), dir.display())); @@ -387,9 +447,9 @@ impl Session { l.modified = Some(modified); } match self.show_photocraft_file(&link) { - Ok(layer) => { + Ok(layers) => { if let Some(l) = self.photocraft.links.get_mut(i) { - l.layer = Some(layer); + l.layers = layers; } self.log.push(format!("Updated {} from PhotoCraft", link.path.display())); updated.push(link.path.clone()); @@ -400,10 +460,10 @@ impl Session { updated } - /// Put the merged image of `link`'s file into its `PhotoCraft: ` fill (created at the - /// top of the set when missing), as one undo step. + /// Put every channel `link`'s file holds into its `PhotoCraft: ` fill (created at + /// the top of the set when missing), as one undo step. #[cfg(not(target_arch = "wasm32"))] - fn show_photocraft_file(&mut self, link: &Link) -> Result { + fn show_photocraft_file(&mut self, link: &Link) -> Result> { use std::io::Read; let io = |e: std::io::Error| EngineError::Other(e.to_string()); let file = std::fs::File::open(&link.path).map_err(io)?; @@ -412,17 +472,66 @@ impl Session { if bytes.len() as u64 > MAX_LINKED_BYTES { return Err(EngineError::Other(format!("larger than {} MB", MAX_LINKED_BYTES >> 20))); } - let png = ora::read_merged(&bytes).map_err(|e| EngineError::Other(e.to_string()))?; - self.show_photocraft_image(link.ts, link.channel, link.layer, &png) + let err = |e: texturecraft_formats::FormatError| EngineError::Other(e.to_string()); + let images = match link.format { + Format::Ora => { + let c = link.channels.first().copied().ok_or_else(|| EngineError::Other("the link holds no channel".into()))?; + vec![(c, ora::read_merged(&bytes).map_err(err)?)] + } + Format::Psd => { + let doc = texturecraft_formats::psd::read_psd(&bytes).map_err(err)?; + let cache = self.caches.get(link.ts).ok_or_else(|| EngineError::Other(format!("no texture set {}", link.ts)))?; + if (doc.width, doc.height) != cache.size { + return Err(EngineError::Other(format!( + "the document is {}×{} but the texture set is {}×{}; resize it back to bring it in", + doc.width, doc.height, cache.size.0, cache.size.1 + ))); + } + let coverage = cache.gbuf.coverage_mask(); + let mut notes = Vec::new(); + let mut images = Vec::new(); + for &c in &link.channels { + let img = crate::photocraft_psd::composite(&doc, c, &coverage, &mut notes); + images.push((c, ora::png16(&img).map_err(err)?)); + } + self.log.extend(notes.into_iter().map(|n| format!("PhotoCraft: {}: {n}", link.path.display()))); + images + } + }; + self.show_photocraft_images(link.ts, &images, &link.layers) } /// Show `png` as channel `c` of texture set `ts` through the fill `layer` (when it is still a /// fill of that set) or a new `PhotoCraft: ` fill at the top. The previous image /// resource is removed when nothing else uses it. pub fn show_photocraft_image(&mut self, ts: usize, c: Channel, layer: Option, png: &[u8]) -> Result { + let layers: BTreeMap = layer.map(|id| (c, id)).into_iter().collect(); + self.show_photocraft_images(ts, &[(c, png.to_vec())], &layers)?.get(&c).copied().ok_or_else(|| EngineError::Other("no layer was made".into())) + } + + /// [`Session::show_photocraft_image`] for several channels in one undo step. + pub fn show_photocraft_images( + &mut self, + ts: usize, + images: &[(Channel, Vec)], + layers: &BTreeMap, + ) -> Result> { let (w, h) = self.caches.get(ts).map(|c| c.size).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?; let set_name = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?.name.clone(); self.edit(UPDATE, |s| { + let mut out = BTreeMap::new(); + for (c, png) in images { + let id = s.put_photocraft_image(ts, &set_name, (w, h), *c, layers.get(c).copied(), png)?; + out.insert(*c, id); + } + Ok(out) + }) + } + + /// The body of [`Session::show_photocraft_images`] for one channel, inside its edit. + fn put_photocraft_image(&mut self, ts: usize, set_name: &str, (w, h): (u32, u32), c: Channel, layer: Option, png: &[u8]) -> Result { + let s = self; + { let resource = texturecraft_formats::export::sanitize_file_stem(&format!("photocraft_{set_name}_{}", c.id())); let name = s.add_image_resource(&format!("{resource}.png"), png.to_vec(), u64::from(w) * u64::from(h) * 4)?; let source = texturecraft_core::Source::image(name); @@ -452,7 +561,7 @@ impl Session { } }; Ok(id) - }) + } } /// Drop image resource `name` when no fill source uses it any more. @@ -474,6 +583,7 @@ mod tests { use super::*; use crate::execute; use std::io::Read; + use texturecraft_formats::psd; use texturecraft_geom::primitives; /// A fresh folder under the system temp dir, removed when dropped. @@ -528,7 +638,9 @@ mod tests { execute(&mut s, "layer.rename", &json!({"layer": fill.0, "name": "Red"})).unwrap(); execute(&mut s, "mask.add.black", &Value::Null).unwrap(); execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(); - let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor", "roughness"], "open": false})).unwrap(); + let r = + execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor", "roughness"], "format": "ora", "open": false})) + .unwrap(); let files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); assert_eq!(files.len(), 2, "{r}"); let base = std::path::PathBuf::from(files.iter().find(|f| f.ends_with("_baseColor.ora")).unwrap()); @@ -552,7 +664,7 @@ mod tests { let dir = tempdir("srgb"); let mut s = session(); execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap(); - let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor"], "open": false})).unwrap(); + let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor"], "format": "ora", "open": false})).unwrap(); let path = std::path::PathBuf::from(r["files"][0].as_str().unwrap()); let xml = stack_xml(&path); let src = xml.split("src=\"").nth(1).unwrap().split('"').next().unwrap().to_string(); @@ -565,7 +677,7 @@ mod tests { execute(&mut s, "mask.add.black", &Value::Null).unwrap(); execute(&mut s, "effect.add.generator", &json!({"generator": "position"})).unwrap(); s.update(); - let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor"], "open": false})).unwrap(); + let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor"], "format": "ora", "open": false})).unwrap(); let path = std::path::PathBuf::from(r["files"][0].as_str().unwrap()); let xml = stack_xml(&path); let src = xml.split("src=\"").nth(1).unwrap().split('"').next().unwrap().to_string(); @@ -588,7 +700,7 @@ mod tests { fn a_save_in_photocraft_shows_live_and_undoes() { let dir = tempdir("live"); let mut s = session(); - let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor"], "open": false})).unwrap(); + let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor"], "format": "ora", "open": false})).unwrap(); let path = std::path::PathBuf::from(r["files"][0].as_str().unwrap()); // Nothing changed since the send. assert!(s.sync_photocraft().is_empty()); @@ -605,12 +717,12 @@ mod tests { s.update(); let v = s.caches[0].composite.value(Channel::BaseColor, w / 2, h / 2); assert!(v[1] > 0.9 && v[0] < 0.1, "{v:?}"); - let layer = s.photocraft.links[0].layer.unwrap(); + let layer = s.photocraft.links[0].layers[&Channel::BaseColor]; assert!(s.doc.project.layer(layer).unwrap().name.starts_with("PhotoCraft")); // A second save reuses the layer and its old image resource goes. std::fs::File::options().write(true).open(&path).unwrap().set_modified(later + std::time::Duration::from_secs(5)).unwrap(); assert_eq!(s.sync_photocraft().len(), 1); - assert_eq!(s.photocraft.links[0].layer, Some(layer)); + assert_eq!(s.photocraft.links[0].layers.get(&Channel::BaseColor), Some(&layer)); assert_eq!(s.doc.resources.keys().filter(|k| k.contains("photocraft")).count(), 1, "{:?}", s.doc.resources.keys().collect::>()); // A broken file is logged, not fatal. std::fs::write(&path, b"broken").unwrap(); @@ -627,6 +739,179 @@ mod tests { assert!(s.photocraft.links.is_empty()); } + fn read_psd(path: &std::path::Path) -> psd::ReadDocument { + psd::read_psd(&std::fs::read(path).unwrap()).unwrap() + } + + fn find<'a>(layers: &'a [psd::ReadLayer], name: &str) -> Option<&'a psd::ReadLayer> { + layers.iter().find_map(|l| { + if l.name == name { + return Some(l); + } + match &l.kind { + psd::ReadKind::Group(children) => find(children, name), + psd::ReadKind::Pixels { .. } => None, + } + }) + } + + fn children(l: &psd::ReadLayer) -> &[psd::ReadLayer] { + match &l.kind { + psd::ReadKind::Group(c) => c, + psd::ReadKind::Pixels { .. } => panic!("{} is not a group", l.name), + } + } + + fn pixel(l: &psd::ReadLayer, x: i32, y: i32) -> [u16; 4] { + let psd::ReadKind::Pixels { x: x0, y: y0, image } = &l.kind else { panic!("{} is a group", l.name) }; + let i = ((y - y0) as usize * image.width as usize + (x - x0) as usize) * 4; + image.data[i..i + 4].try_into().unwrap() + } + + #[test] + fn sends_one_psd_per_set_with_a_group_per_layer_its_mask_and_a_layer_per_channel() { + let dir = tempdir("psd"); + let mut s = session(); + // A dab in a corner of the paint layer: its other tiles hold no paint. + execute(&mut s, "tool.strokeUv", &json!({"points": [[0.1, 0.1], [0.12, 0.1]]})).unwrap(); + execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(); + let fill = s.selected_layer().unwrap(); + execute(&mut s, "layer.rename", &json!({"layer": fill.0, "name": "Red"})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(); + let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor", "roughness"], "open": false})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 1, "{r}"); + let path = std::path::PathBuf::from(files[0].as_str().unwrap()); + assert_eq!(path.extension().unwrap(), "psd"); + let doc = read_psd(&path); + let (w, h) = s.caches[0].size; + assert_eq!((doc.width, doc.height), (w, h)); + // Top-first: the folder holding "Red", then the project's first paint layer. + assert_eq!(doc.layers.len(), 2, "{:?}", doc.layers.iter().map(|l| &l.name).collect::>()); + assert!(find(children(&doc.layers[0]), "Red").is_some()); + assert_eq!(doc.layers[1].name, "Layer 1"); + // A paint layer without a mask hides nothing, so its group has no mask (also where it + // holds no paint). + assert!(doc.layers[1].mask.is_none()); + let red = find(&doc.layers, "Red").unwrap(); + assert_eq!(&red.blend, b"pass"); + // The black mask is the group's own mask; the content inside stays whole. + let (cx, cy) = (w as i32 / 2, h as i32 / 2); + assert_eq!(red.mask.as_ref().map(|m| m.at(cx, cy)), Some(0)); + let inside = children(red); + assert_eq!(inside.iter().map(|l| l.name.as_str()).collect::>(), ["Base color", "Roughness"]); + assert!(inside[0].visible && !inside[1].visible, "the first comp shows only Base color"); + assert_eq!(pixel(&inside[0], cx, cy), [65535, 0, 0, 65535]); + let rough = pixel(&inside[1], cx, cy); + assert!((rough[0] as f32 / 65535.0 - 0.2).abs() < 1e-3 && rough[3] == 65535, "{rough:?}"); + // One link holds both channels. + assert_eq!(s.photocraft.links.len(), 1); + assert_eq!(links_json(&s)[0]["channels"], json!(["baseColor", "roughness"])); + assert_eq!(links_json(&s)[0]["format"], "psd"); + } + + #[test] + fn a_psd_sent_back_unchanged_rebuilds_every_channel() { + let dir = tempdir("psd_same"); + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.6, 0.9], "roughness": 0.7, "metallic": 1.0})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.generator", &json!({"generator": "position"})).unwrap(); + execute(&mut s, "layer.add.fill", &json!({"roughness": 0.1})).unwrap(); + let top = s.selected_layer().unwrap(); + execute(&mut s, "layer.blend", &json!({"layer": top.0, "channel": "roughness", "mode": "multiply", "opacity": 0.5})).unwrap(); + s.update(); + let channels = [Channel::BaseColor, Channel::Roughness, Channel::Metallic]; + let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor", "roughness", "metallic"], "open": false})) + .unwrap(); + let doc = read_psd(std::path::Path::new(r["files"][0].as_str().unwrap())); + let coverage = s.caches[0].gbuf.coverage_mask(); + let (w, h) = s.caches[0].size; + let mut notes = Vec::new(); + for c in channels { + let img = crate::photocraft_psd::composite(&doc, c, &coverage, &mut notes); + let mut worst = 0i32; + for (x, y) in [(3, 5), (w / 4, h / 3), (w / 2, h / 2), (w - 7, h - 9), (w / 3, h - 20)] { + let i = (y as usize * w as usize + x as usize) * 4; + let want = encode_value(c, s.caches[0].composite.value(c, x, y)); + for k in 0..4 { + worst = worst.max((img.data[i + k] as i32 - want[k] as i32).abs()); + } + } + assert!(worst < 300, "{c:?} differs by {worst}"); + } + assert!(notes.is_empty(), "{notes:?}"); + } + + #[test] + fn a_psd_save_brings_every_channel_back_in_one_step_through_its_group_mask() { + let dir = tempdir("psd_live"); + let mut s = session(); + let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor", "roughness"], "open": false})).unwrap(); + let path = std::path::PathBuf::from(r["files"][0].as_str().unwrap()); + assert!(s.sync_photocraft().is_empty()); + // PhotoCraft saves: one group whose mask shows only the right half, holding a green + // base colour, a roughness of 0.8 (hidden, as a comp would leave it) and a stray layer. + let (w, h) = s.caches[0].size; + let solid = |px: [u16; 4]| { + let mut img = Rgba16::transparent(w, h); + for p in img.data.as_chunks_mut::<4>().0 { + *p = px; + } + psd::encode_pixels(&img).unwrap() + }; + let mut mask = psd::Mask16 { width: w, height: h, data: vec![0; (w * h) as usize] }; + for (i, v) in mask.data.iter_mut().enumerate() { + if i as u32 % w >= w / 2 { + *v = 65535; + } + } + let layer = |name: &str, visible: bool, px: [u16; 4]| psd::Layer { + name: name.into(), + visible, + opacity: 1.0, + blend: *b"norm", + mask: None, + comps: Vec::new(), + kind: psd::Kind::Pixels(solid(px)), + }; + let r8 = (0.8f32 * 65535.0) as u16; + let group = psd::Layer { + name: "Paint".into(), + visible: true, + opacity: 1.0, + blend: *b"pass", + mask: Some(psd::encode_mask(&mask).unwrap()), + comps: Vec::new(), + kind: psd::Kind::Group(vec![ + layer("Notes", true, [65535, 65535, 65535, 65535]), + layer("Base color", true, [0, 65535, 0, 65535]), + layer("Roughness", false, [r8, r8, r8, 65535]), + ]), + }; + let doc = psd::Document { layers: vec![group], merged: Rgba16::transparent(w, h), comps: vec!["Base color".into(), "Roughness".into()] }; + std::fs::write(&path, psd::write_psd(&doc).unwrap()).unwrap(); + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(5); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap(); + let undo_before = s.undo.len(); + assert_eq!(s.sync_photocraft(), vec![path.clone()]); + assert_eq!(s.undo.len(), undo_before + 1, "both channels are one undo step"); + s.update(); + let comp = &s.caches[0].composite; + let (right, left) = ((w * 3 / 4, h / 2), (w / 4, h / 2)); + let base = comp.value(Channel::BaseColor, right.0, right.1); + assert!(base[1] > 0.9 && base[0] < 0.1, "{base:?}"); + assert!((comp.value(Channel::Roughness, right.0, right.1)[0] - 0.8).abs() < 1e-2); + // Where the group mask hides the paint, the channels keep their defaults. + let d = Channel::Roughness.default_value()[0]; + assert!((comp.value(Channel::Roughness, left.0, left.1)[0] - d).abs() < 1e-2); + assert_eq!(s.photocraft.links[0].layers.len(), 2); + assert!(s.log.iter().any(|l| l.contains("\"Notes\"")), "{:?}", s.log); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.walk(0).iter().all(|(id, _)| !s.doc.project.layer(*id).unwrap().name.starts_with("PhotoCraft"))); + } + #[test] fn bad_params_are_errors() { let mut s = session(); @@ -638,6 +923,7 @@ mod tests { assert!(execute(&mut s, SEND, &json!({"dir": d, "channels": ["nope"], "open": false})).is_err()); assert!(execute(&mut s, SEND, &json!({"dir": d, "channels": "baseColor", "open": false})).is_err()); assert!(execute(&mut s, SEND, &json!({"dir": d, "channels": ["coatNormal"], "open": false})).is_err()); + assert!(execute(&mut s, SEND, &json!({"dir": d, "format": "tiff", "open": false})).is_err()); assert!(s.show_photocraft_image(0, Channel::BaseColor, None, b"not a png").is_err()); assert!(s.doc.project.walk(0).iter().all(|(id, _)| !s.doc.project.layer(*id).unwrap().name.starts_with("PhotoCraft"))); } diff --git a/crates/engine/src/photocraft_psd.rs b/crates/engine/src/photocraft_psd.rs new file mode 100644 index 00000000..ba77323b --- /dev/null +++ b/crates/engine/src/photocraft_psd.rs @@ -0,0 +1,379 @@ +//! The PhotoCraft hand-off as one layered PSD per texture set. +//! +//! The stack keeps its shape: every folder is a group and every layer a pass-through group +//! named after it, carrying the layer's mask as an editable group mask; inside it, one pixel +//! layer per channel (`Base color`, `Roughness`, ...) holds the layer's content for that +//! channel with the channel's blend mode and opacity. One layer comp per channel shows only +//! that channel's layers, so the whole material is one document and a mask edited once +//! shapes every channel. +//! +//! When PhotoCraft saves the file, [`composite`] rebuilds each channel from the saved layers: +//! a pixel layer counts for the channel it is named after, through every group mask, opacity +//! and visibility above it, blended with TextureCraft's own blend math. + +use texturecraft_core::{BlendMode, Channel, ChannelKind, LayerId, LayerKind, blend1, blend3, mix3}; +use texturecraft_formats::ora::Rgba16; +use texturecraft_formats::psd::{self, EncodedMask, Kind, Mask16, ReadDocument, ReadKind, ReadLayer}; +use texturecraft_texel::{TILE, TILE_AREA, from_u16, srgb_to_linear}; + +use crate::photocraft_cmds::{encode_value, flat_image, merged_image}; +use crate::{EngineError, Result, Session}; + +/// The PSD blend mode key for `mode`, with a warning when it is only close or missing. +pub(crate) fn psd_key(mode: BlendMode) -> ([u8; 4], Option<&'static str>) { + use BlendMode as B; + match mode { + B::Normal => (*b"norm", None), + B::Passthrough => (*b"pass", None), + B::Multiply => (*b"mul ", None), + B::Screen => (*b"scrn", None), + B::Overlay => (*b"over", None), + B::Darken => (*b"dark", None), + B::Lighten => (*b"lite", None), + B::ColorDodge => (*b"div ", None), + B::ColorBurn => (*b"idiv", None), + B::HardLight => (*b"hLit", None), + B::SoftLight => (*b"sLit", None), + B::Difference => (*b"diff", None), + B::Exclusion => (*b"smud", None), + B::LinearDodge => (*b"lddg", None), + B::LinearBurn => (*b"lbrn", None), + B::VividLight => (*b"vLit", None), + B::LinearLight => (*b"lLit", None), + B::PinLight => (*b"pLit", None), + B::Subtract => (*b"fsub", None), + B::Divide => (*b"fdiv", None), + B::Saturation => (*b"sat ", None), + B::Color => (*b"colr", None), + B::Value => (*b"lum ", Some("Value is sent as Luminosity")), + _ => (*b"norm", Some("this blend mode has no PSD equivalent; it is sent as Normal")), + } +} + +/// The blend mode a PSD key stands for (unknown keys blend as Normal). +fn mode_of(key: &[u8; 4]) -> BlendMode { + use BlendMode as B; + match key { + b"mul " => B::Multiply, + b"scrn" => B::Screen, + b"over" => B::Overlay, + b"dark" => B::Darken, + b"lite" => B::Lighten, + b"div " => B::ColorDodge, + b"idiv" => B::ColorBurn, + b"hLit" => B::HardLight, + b"sLit" => B::SoftLight, + b"diff" => B::Difference, + b"smud" => B::Exclusion, + b"lddg" => B::LinearDodge, + b"lbrn" => B::LinearBurn, + b"vLit" => B::VividLight, + b"lLit" => B::LinearLight, + b"pLit" => B::PinLight, + b"fsub" => B::Subtract, + b"fdiv" => B::Divide, + b"sat " => B::Saturation, + b"colr" => B::Color, + b"lum " => B::Value, + _ => B::Normal, + } +} + +/// Builds the PSD tree of one texture set. +struct Tree<'s> { + s: &'s Session, + ts: usize, + size: (u32, u32), + channels: Vec, + covered: Vec<(u32, u32)>, + warnings: Vec, +} + +impl Tree<'_> { + fn warn(&mut self, layer: &str, msg: &str) { + let line = format!("\"{layer}\": {msg}"); + if !self.warnings.contains(&line) { + self.warnings.push(line); + } + } + + /// `ids` (bottom → top) as PSD layers top-first. + fn nodes(&mut self, ids: &[LayerId], depth: usize) -> Result> { + if depth > psd::MAX_DEPTH { + return Err(EngineError::Other(format!("folders are nested more than {} deep", psd::MAX_DEPTH))); + } + let mut out = Vec::new(); + for &id in ids.iter().rev() { + let layer = self.s.doc.project.layer(id).map_err(|e| EngineError::Other(e.to_string()))?.clone(); + let enabled: Vec<(Channel, texturecraft_core::ChannelBlend)> = + self.channels.iter().filter_map(|c| layer.blend(*c).filter(|b| b.mode != BlendMode::Disable).map(|b| (*c, b))).collect(); + if enabled.is_empty() { + continue; + } + let node = match &layer.kind { + LayerKind::Group { children, .. } => { + // A folder has one blend mode and opacity in the PSD; TextureCraft has one per channel. + let first = enabled.first().map(|(_, b)| *b).unwrap_or_default(); + let uniform = enabled.iter().all(|(_, b)| b.mode == first.mode && (b.opacity - first.opacity).abs() < 1e-4); + let (blend, opacity) = if uniform { + let (key, note) = psd_key(first.mode); + if let Some(note) = note { + self.warn(&layer.name, note); + } + (key, first.opacity) + } else { + self.warn(&layer.name, "the folder blends its channels differently; it is sent as a pass-through group at 100%"); + (*b"pass", 1.0) + }; + let children = self.nodes(children, depth + 1)?; + psd::Layer { + name: layer.name.clone(), + visible: layer.visible, + opacity, + blend, + mask: self.mask(id, &[])?, + comps: Vec::new(), + kind: Kind::Group(children), + } + } + _ => { + let (content, masks) = self.s.flatten_apart(self.ts, id).unwrap_or_default(); + let mask = self.mask(id, &masks)?; + let mut children = Vec::new(); + for (c, b) in &enabled { + let (key, note) = psd_key(b.mode); + if let Some(note) = note { + self.warn(&format!("{} › {}", layer.name, c.label()), note); + } + let image = psd::encode_pixels(&flat_image(*c, self.size, &content)).map_err(|e| EngineError::Other(e.to_string()))?; + let comps: Vec = self.channels.iter().map(|x| x == c).collect(); + let first_comp = self.channels.first() == Some(c); + children.push(psd::Layer { + name: c.label().to_string(), + visible: first_comp, + opacity: b.opacity, + blend: key, + mask: None, + comps, + kind: Kind::Pixels(image), + }); + } + psd::Layer { + name: layer.name.clone(), + visible: layer.visible, + opacity: 1.0, + blend: *b"pass", + mask, + comps: Vec::new(), + kind: Kind::Group(children), + } + } + }; + out.push(node); + } + Ok(out) + } + + /// The mask of layer or folder `id` over the covered texels, when it hides any of them. + /// `tiles` are the mask tiles flattening gave (a layer); the texels they leave out, such as + /// tiles where a paint layer is empty, are evaluated on their own. + fn mask(&self, id: LayerId, tiles: &[texturecraft_compose::eval::MaskTile]) -> Result> { + let (w, h) = self.size; + let index = |x: u32, y: u32| (x < w && y < h).then(|| y as usize * w as usize + x as usize); + let mut data: Vec> = vec![None; w as usize * h as usize]; + for ((tx, ty), values) in tiles { + for (o, v) in values.iter().enumerate().take(TILE_AREA) { + if let Some(d) = index(tx * TILE + o as u32 % TILE, ty * TILE + o as u32 / TILE).and_then(|i| data.get_mut(i)) { + *d = Some(*v); + } + } + } + let missing: Vec<(u32, u32)> = + self.covered.iter().copied().filter(|&(x, y)| index(x, y).and_then(|i| data.get(i)).is_some_and(Option::is_none)).collect(); + if !missing.is_empty() { + let values = self.s.with_inputs(self.ts, |inp| texturecraft_compose::mask_at(inp, id, &missing)).unwrap_or_default(); + for (&(x, y), v) in missing.iter().zip(values) { + if let Some(d) = index(x, y).and_then(|i| data.get_mut(i)) { + *d = Some(texturecraft_texel::to_u16(v)); + } + } + } + let hides = self.covered.iter().any(|&(x, y)| index(x, y).and_then(|i| data.get(i).copied().flatten()).is_some_and(|v| v < 65535)); + if !hides { + return Ok(None); + } + let m = Mask16 { width: w, height: h, data: data.into_iter().map(|v| v.unwrap_or(0)).collect() }; + psd::encode_mask(&m).map(Some).map_err(|e| EngineError::Other(e.to_string())) + } +} + +impl Session { + /// Layer `id` of texture set `ts` alone, its content and its mask apart (see + /// [`texturecraft_compose::flatten_layer_masked_apart`]). + pub(crate) fn flatten_apart( + &self, + ts: usize, + id: LayerId, + ) -> Option<(Vec, Vec)> { + let tiles: Vec<(u32, u32)> = self.caches.get(ts)?.covered_tiles.iter().copied().collect(); + self.with_inputs(ts, |inp| texturecraft_compose::flatten_layer_masked_apart(inp, id, &tiles)) + } + + /// Texture set `ts` as one layered PSD of `channels` (see the module docs), plus what it + /// couldn't keep. + pub fn photocraft_psd(&mut self, ts: usize, channels: &[Channel]) -> Result<(Vec, Vec)> { + self.update(); + let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?; + let channels: Vec = channels.iter().copied().filter(|c| set.channel_list().contains(c)).collect(); + let Some(&first) = channels.first() else { + return Err(EngineError::Other(format!("texture set \"{}\" has none of the channels asked for", set.name))); + }; + let stack = set.stack.clone(); + let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?; + let size = cache.size; + let covered: Vec<(u32, u32)> = cache + .gbuf + .coverage_mask() + .iter() + .enumerate() + .filter(|(_, c)| **c) + .map(|(i, _)| ((i % size.0 as usize) as u32, (i / size.0 as usize) as u32)) + .collect(); + let mut tree = Tree { s: self, ts, size, channels: channels.clone(), covered, warnings: Vec::new() }; + let layers = tree.nodes(&stack, 1)?; + let mut warnings = tree.warnings; + if channels.iter().any(|c| c.kind() == ChannelKind::NormalMap) { + warnings.push("normal channels: PhotoCraft blends normal layers as colours, not as normals".into()); + } + let doc = psd::Document { layers, merged: merged_image(self, ts, first)?, comps: channels.iter().map(|c| c.label().to_string()).collect() }; + let bytes = psd::write_psd(&doc).map_err(|e| EngineError::Other(e.to_string()))?; + Ok((bytes, warnings)) + } +} + +/// A channel value from a saved pixel (straight, 0..65535). +fn decode(c: Channel, px: &[u16]) -> [f32; 3] { + let v = |k: usize| px.get(k).map_or(0.0, |v| from_u16(*v)); + match c.kind() { + ChannelKind::Color => [0, 1, 2].map(|k| srgb_to_linear(v(k))), + ChannelKind::NormalMap => [v(0), v(1), v(2)], + ChannelKind::Scalar => [v(0); 3], + ChannelKind::Signed => [v(0) * 2.0 - 1.0; 3], + } +} + +/// Channel `c` of a saved document, `w`×`h`: the channel's default value with every layer named +/// after `c` blended over it (see the module docs). Encoded as the hand-off writes channels; +/// opaque where `coverage` is set. +pub(crate) fn composite(doc: &ReadDocument, c: Channel, coverage: &[bool], notes: &mut Vec) -> Rgba16 { + let (w, h) = (doc.width as usize, doc.height as usize); + let mut acc = vec![c.default_value(); w * h]; + walk(&doc.layers, c, &mut acc, (w, h), None, 0, notes); + let mut img = Rgba16::transparent(doc.width, doc.height); + for (i, v) in acc.iter().enumerate() { + if coverage.get(i).copied().unwrap_or(false) + && let Some(dst) = img.data.get_mut(i * 4..i * 4 + 4) + { + dst.copy_from_slice(&encode_value(c, *v)); + } + } + img +} + +fn is_channel_name(name: &str) -> bool { + Channel::ALL.iter().any(|c| c.label() == name.trim()) +} + +/// Blend `nodes` (top-first) into `acc`, each weighted by `weight` (the masks, opacities and +/// visibility of the groups above; None: 1). +fn walk(nodes: &[ReadLayer], c: Channel, acc: &mut [[f32; 3]], (w, h): (usize, usize), weight: Option<&[f32]>, depth: usize, notes: &mut Vec) { + if depth > psd::MAX_DEPTH { + return; + } + for node in nodes.iter().rev() { + match &node.kind { + ReadKind::Group(children) => { + if !node.visible || node.opacity <= 0.0 { + continue; + } + let mut wgt: Vec = weight.map_or_else(|| vec![1.0; w * h], <[f32]>::to_vec); + for (i, v) in wgt.iter_mut().enumerate() { + let m = node.mask.as_ref().map_or(1.0, |m| from_u16(m.at((i % w) as i32, (i / w) as i32))); + *v *= m * node.opacity; + } + walk(children, c, acc, (w, h), Some(&wgt), depth + 1, notes); + } + ReadKind::Pixels { x, y, image } => { + // Channel layers are shown one comp at a time, so their own visibility is ignored. + if node.name.trim() != c.label() { + if node.visible && !is_channel_name(&node.name) { + let note = format!("\"{}\" is not named after a channel (such as \"{}\"), so it isn't brought back", node.name, c.label()); + if !notes.contains(¬e) { + notes.push(note); + } + } + continue; + } + let mode = mode_of(&node.blend); + let (iw, ih) = (image.width as usize, image.height as usize); + for ly in 0..ih { + let cy = i64::from(*y) + ly as i64; + if cy < 0 || cy >= h as i64 { + continue; + } + for lx in 0..iw { + let cx = i64::from(*x) + lx as i64; + if cx < 0 || cx >= w as i64 { + continue; + } + let i = cy as usize * w + cx as usize; + let Some(px) = image.data.get((ly * iw + lx) * 4..(ly * iw + lx) * 4 + 4) else { continue }; + let mask = node.mask.as_ref().map_or(1.0, |m| from_u16(m.at(cx as i32, cy as i32))); + let a = from_u16(px[3]) * node.opacity * mask * weight.and_then(|wg| wg.get(i)).copied().unwrap_or(1.0); + if a <= 0.0 { + continue; + } + let Some(dst) = acc.get_mut(i) else { continue }; + let v = decode(c, px); + let blended = if c.components() == 3 { blend3(mode, *dst, v) } else { [blend1(mode, dst[0], v[0]); 3] }; + *dst = mix3(*dst, blended, a.min(1.0)); + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::execute; + use serde_json::Value; + use texturecraft_geom::primitives; + + fn tree(s: &Session) -> Tree<'_> { + let size = s.caches[0].size; + let covered = s.caches[0] + .gbuf + .coverage_mask() + .iter() + .enumerate() + .filter(|(_, c)| **c) + .map(|(i, _)| ((i % size.0 as usize) as u32, (i / size.0 as usize) as u32)) + .collect(); + Tree { s, ts: 0, size, channels: vec![Channel::BaseColor], covered, warnings: Vec::new() } + } + + #[test] + fn texels_flattening_leaves_out_are_masked_as_the_layer_is() { + let mut s = Session::new_project("t", primitives::plane(2.0, 2), "builtin:plane", None, 128).unwrap(); + s.update(); + let paint = s.selected_layer().unwrap(); + // No mask tiles at all (an empty paint layer flattens to nothing): no mask either. + assert!(tree(&s).mask(paint, &[]).unwrap().is_none()); + // A black mask hides every texel, tiles or not. + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + s.update(); + assert!(tree(&s).mask(paint, &[]).unwrap().is_some()); + } +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 1c1a7d74..6033ff71 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -17,6 +17,8 @@ //! MaterialCraft graph inputs. //! - [`ora`]: layered OpenRaster (`.ora`) documents for an image editor, and their merged image //! read back. +//! - [`psd`]: layered 16-bit PSD documents (groups, layer masks, layer comps) for an image +//! editor, and their layers read back. //! - [`presets`]: the built-in export presets and JSON (de)serialization of user presets. //! - [`project_file`]: the `.tcraft` project zip (project JSON, sparse lossless pixel tiles, //! baked maps, the original mesh and a thumbnail). @@ -40,6 +42,7 @@ pub mod mesh_import; pub mod ora; pub mod presets; pub mod project_file; +pub mod psd; pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps, diff --git a/crates/formats/src/ora.rs b/crates/formats/src/ora.rs index a9890984..66de1004 100644 --- a/crates/formats/src/ora.rs +++ b/crates/formats/src/ora.rs @@ -191,7 +191,8 @@ fn escape(s: &str) -> String { out } -fn png16(img: &Rgba16) -> Result> { +/// `img` as a 16-bit RGBA PNG. +pub fn png16(img: &Rgba16) -> Result> { use image::ImageEncoder; let bytes: Vec = img.data.iter().flat_map(|v| v.to_ne_bytes()).collect(); let mut out = Cursor::new(Vec::new()); diff --git a/crates/formats/src/psd.rs b/crates/formats/src/psd.rs new file mode 100644 index 00000000..a1c07af7 --- /dev/null +++ b/crates/formats/src/psd.rs @@ -0,0 +1,1125 @@ +//! Layered PSD documents (16-bit RGB, version 1) for an image editor, and the layers read back +//! after the editor saved them. +//! +//! Written from the public PSD file format specification: a header, empty colour mode data, +//! image resources (the layer comp list, resource 1065), the layer and mask section (layer +//! records bottom to top, groups as `lsct` section dividers, layer masks as channel −2, +//! Unicode names in `luni`, layer ids in `lyid`, per-layer comp visibility in `shmd`/`cmls`), +//! and the merged image. Layer channels are written with ZIP-with-prediction compression; the +//! reader also takes raw, RLE and plain ZIP, 8 and 16 bits, which is what editors save. +//! +//! Every read is bounded: canvas size, layer count, nesting and decoded bytes are capped, and +//! malformed input is an error, never a panic. + +use std::io::{Read, Write}; + +use crate::ora::Rgba16; +use crate::{FormatError, Result}; + +/// File extension. +pub const PSD_EXT: &str = "psd"; +/// Largest canvas side written or read. +pub const MAX_SIDE: u32 = 16384; +/// Most layer records (groups count twice) read. +const MAX_RECORDS: usize = 8192; +/// Deepest group nesting written or read. +pub const MAX_DEPTH: usize = 64; +/// Most decoded channel bytes read from one file. +const MAX_DECODED: u64 = 6 << 30; +/// Image resource id of the layer comp list. +const LAYER_COMPS: u16 = 1065; + +fn invalid(msg: impl Into) -> FormatError { + FormatError::Invalid(msg.into()) +} + +fn malformed(msg: impl Into) -> FormatError { + FormatError::Malformed { kind: "PSD", msg: msg.into() } +} + +// ------------------------------------------------------------------------------------------ +// Model + +/// A rectangle as the format stores it: top, left, bottom, right. +type Rect = (i32, i32, i32, i32); + +/// A grayscale layer mask the size of the canvas (0 hides, 65535 shows). +#[derive(Clone, Debug, PartialEq)] +pub struct Mask16 { + pub width: u32, + pub height: u32, + pub data: Vec, +} + +/// One layer or group of a document to write, children top-first. +#[derive(Clone, Debug, PartialEq)] +pub struct Layer { + pub name: String, + pub visible: bool, + /// 0..1. + pub opacity: f32, + /// A PSD blend mode key (`norm`, `mul `, `pass` for a pass-through group, ...). + pub blend: [u8; 4], + pub mask: Option, + /// Visibility in each of the document's layer comps (missing entries: `visible`). + pub comps: Vec, + pub kind: Kind, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Kind { + /// Pixels, compressed as soon as they are made ([`encode_pixels`]), so a document of many + /// large layers never holds them all uncompressed. + Pixels(EncodedPixels), + Group(Vec), +} + +/// A layer's channels, cropped to its pixels and compressed. +#[derive(Clone, Debug, PartialEq)] +pub struct EncodedPixels { + canvas: (u32, u32), + rect: (i32, i32, i32, i32), + data: Vec<(i16, Vec)>, +} + +/// A layer mask, cropped to where it is not 0 and compressed. +#[derive(Clone, Debug, PartialEq)] +pub struct EncodedMask { + canvas: (u32, u32), + rect: (i32, i32, i32, i32), + data: Vec, +} + +/// A document to write: layers top-first, the merged image, layer comp names. +#[derive(Clone, Debug, PartialEq)] +pub struct Document { + pub layers: Vec, + pub merged: Rgba16, + pub comps: Vec, +} + +// ------------------------------------------------------------------------------------------ +// Writing + +trait Put { + fn u8(&mut self, v: u8); + fn u16(&mut self, v: u16); + fn i16(&mut self, v: i16); + fn u32(&mut self, v: u32); + fn i32(&mut self, v: i32); + fn bytes(&mut self, v: &[u8]); +} + +impl Put for Vec { + fn u8(&mut self, v: u8) { + self.push(v); + } + fn u16(&mut self, v: u16) { + self.extend_from_slice(&v.to_be_bytes()); + } + fn i16(&mut self, v: i16) { + self.extend_from_slice(&v.to_be_bytes()); + } + fn u32(&mut self, v: u32) { + self.extend_from_slice(&v.to_be_bytes()); + } + fn i32(&mut self, v: i32) { + self.extend_from_slice(&v.to_be_bytes()); + } + fn bytes(&mut self, v: &[u8]) { + self.extend_from_slice(v); + } +} + +fn len32(n: usize) -> Result { + u32::try_from(n).map_err(|_| invalid("the document is larger than a PSD can hold (4 GB sections); use smaller texture sets")) +} + +/// Action descriptor values (the subset layer comps need). +enum Value { + Long(i32), + Bool(bool), + Text(String), + List(Vec), + Object(&'static str, Vec<(&'static str, Value)>), +} + +/// A descriptor key or class id: four-character ids as length 0 plus the id, others with their length. +fn put_id(out: &mut Vec, id: &str) { + if id.len() == 4 { + out.u32(0); + } else { + out.u32(id.len() as u32); + } + out.bytes(id.as_bytes()); +} + +fn put_unicode(out: &mut Vec, s: &str, nul: bool) { + let mut units: Vec = s.encode_utf16().collect(); + if nul { + units.push(0); + } + out.u32(units.len() as u32); + for u in units { + out.u16(u); + } +} + +fn put_object(out: &mut Vec, class: &str, items: &[(&'static str, Value)]) { + put_unicode(out, "", true); + put_id(out, class); + out.u32(items.len() as u32); + for (k, v) in items { + put_id(out, k); + put_value(out, v); + } +} + +fn put_value(out: &mut Vec, v: &Value) { + match v { + Value::Long(i) => { + out.bytes(b"long"); + out.i32(*i); + } + Value::Bool(b) => { + out.bytes(b"bool"); + out.u8(u8::from(*b)); + } + Value::Text(t) => { + out.bytes(b"TEXT"); + put_unicode(out, t, true); + } + Value::List(items) => { + out.bytes(b"VlLs"); + out.u32(items.len() as u32); + for i in items { + put_value(out, i); + } + } + Value::Object(class, items) => { + out.bytes(b"Objc"); + put_object(out, class, items); + } + } +} + +fn versioned(class: &str, items: &[(&'static str, Value)]) -> Vec { + let mut out = Vec::new(); + out.u32(16); + put_object(&mut out, class, items); + out +} + +/// Additional layer information: signature, key, length, data padded to even. +fn tagged(out: &mut Vec, key: &[u8; 4], data: &[u8]) -> Result<()> { + out.bytes(b"8BIM"); + out.bytes(key); + let padded = data.len() + data.len() % 2; + out.u32(len32(padded)?); + out.bytes(data); + if data.len() % 2 == 1 { + out.u8(0); + } + Ok(()) +} + +/// One plane of `w`×`h` 16-bit samples, ZIP with prediction (row deltas, big-endian, zlib). +fn zip_predicted(plane: &[u16], w: usize) -> Result> { + let mut bytes = Vec::with_capacity(plane.len() * 2); + for row in plane.chunks(w.max(1)) { + let mut prev = 0u16; + for &v in row { + bytes.extend_from_slice(&v.wrapping_sub(prev).to_be_bytes()); + prev = v; + } + } + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(6)); + z.write_all(&bytes)?; + Ok(z.finish()?) +} + +/// A layer's channels for its record: rectangle, (channel id, compression code + data), mask. +struct Channels { + rect: (i32, i32, i32, i32), + data: Vec<(i16, Vec)>, + mask: Option<(Rect, Vec)>, +} + +/// A channel with nothing in it: just the raw compression code. +fn empty_channel() -> Vec { + vec![0, 0] +} + +fn coded(plane: &[u16], w: usize) -> Result> { + let mut out = Vec::new(); + out.u16(3); + out.bytes(&zip_predicted(plane, w)?); + Ok(out) +} + +/// The smallest rectangle (top, left, bottom, right) holding a sample for which `keep` is true. +fn bounds(w: usize, n: usize, keep: impl Fn(usize) -> bool) -> Option<(i32, i32, i32, i32)> { + let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); + for i in (0..n).filter(|i| keep(*i)) { + let (x, y) = (i % w.max(1), i / w.max(1)); + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x); + y1 = y1.max(y); + } + (x0 != usize::MAX).then(|| (y0 as i32, x0 as i32, y1 as i32 + 1, x1 as i32 + 1)) +} + +fn crop_plane(src: &[u16], stride: usize, comps: usize, comp: usize, (t, l, b, r): (i32, i32, i32, i32)) -> Vec { + let mut out = Vec::with_capacity(((b - t) * (r - l)).max(0) as usize); + for y in t..b { + for x in l..r { + out.push(src.get((y as usize * stride + x as usize) * comps + comp).copied().unwrap_or(0)); + } + } + out +} + +fn check_size(what: &str, (w, h): (u32, u32), len: usize, comps: usize) -> Result<()> { + if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE || len != w as usize * h as usize * comps { + return Err(invalid(format!("{what}: {w}×{h} with {len} samples is not a size a PSD is written at"))); + } + Ok(()) +} + +/// Compress a layer's straight-alpha pixels, cropped to where they have alpha. +pub fn encode_pixels(img: &Rgba16) -> Result { + check_size("layer", (img.width, img.height), img.data.len(), 4)?; + let w = img.width as usize; + let rect = bounds(w, w * img.height as usize, |i| img.data.get(i * 4 + 3).copied().unwrap_or(0) > 0); + let mut data = Vec::new(); + match rect { + Some(rect) => { + let rw = (rect.3 - rect.1) as usize; + for (id, comp) in [(-1i16, 3usize), (0, 0), (1, 1), (2, 2)] { + data.push((id, coded(&crop_plane(&img.data, w, 4, comp, rect), rw)?)); + } + } + None => data.extend([-1i16, 0, 1, 2].map(|id| (id, empty_channel()))), + } + Ok(EncodedPixels { canvas: (img.width, img.height), rect: rect.unwrap_or((0, 0, 0, 0)), data }) +} + +/// Compress a mask over the rectangle where it is not 0 (outside it reads the default, 0). +pub fn encode_mask(m: &Mask16) -> Result { + check_size("layer mask", (m.width, m.height), m.data.len(), 1)?; + let w = m.width as usize; + // An all-hidden mask still needs a rectangle to say so: one texel. + let rect = bounds(w, m.data.len(), |i| m.data.get(i).copied().unwrap_or(0) > 0).unwrap_or((0, 0, 1, 1)); + let rw = (rect.3 - rect.1) as usize; + Ok(EncodedMask { canvas: (m.width, m.height), rect, data: coded(&crop_plane(&m.data, w, 1, 0, rect), rw)? }) +} + +fn mask_channel(m: Option<&EncodedMask>, canvas: (u32, u32)) -> Result)>> { + match m { + Some(m) if m.canvas != canvas => Err(invalid("a layer mask is not the canvas size")), + Some(m) => Ok(Some((m.rect, m.data.clone()))), + None => Ok(None), + } +} + +/// Layer records and channel data, bottom to top. +struct Records { + records: Vec, + channels: Vec, + count: usize, + next_id: u32, +} + +impl Records { + fn layer(&mut self, l: &Layer, section: Option, ch: Channels, comps: usize) -> Result<()> { + self.count += 1; + self.next_id += 1; + let id = self.next_id; + let r = &mut self.records; + let (t, left, b, right) = ch.rect; + r.i32(t); + r.i32(left); + r.i32(b); + r.i32(right); + let mut chans = ch.data; + if let Some((_, data)) = &ch.mask { + chans.push((-2, data.clone())); + } + r.u16(chans.len() as u16); + for (cid, data) in &chans { + r.i16(*cid); + r.u32(len32(data.len())?); + } + r.bytes(b"8BIM"); + r.bytes(&l.blend); + r.u8((l.opacity.clamp(0.0, 1.0) * 255.0).round() as u8); + r.u8(0); // clipping: base + // Flags: bit 1 hides the layer; bit 3 says bit 4 is meaningful (not set: pixel data matters). + r.u8(if l.visible { 0 } else { 2 } | 8); + r.u8(0); + + let mut extra = Vec::new(); + match &ch.mask { + Some(((mt, ml, mb, mr), _)) => { + extra.u32(20); + extra.i32(*mt); + extra.i32(*ml); + extra.i32(*mb); + extra.i32(*mr); + extra.u8(0); // default colour: hidden outside the rectangle + extra.u8(0); // flags: position relative to layer, enabled + extra.u16(0); + } + None => extra.u32(0), + } + extra.u32(0); // blending ranges + // Pascal name, padded to a multiple of 4 (ASCII; the full name is in `luni`). + let ascii: Vec = l.name.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect(); + extra.u8(ascii.len() as u8); + extra.bytes(&ascii); + extra.bytes(&[0; 3][..(4 - (ascii.len() + 1) % 4) % 4]); + let mut luni = Vec::new(); + put_unicode(&mut luni, &l.name, false); + tagged(&mut extra, b"luni", &luni)?; + tagged(&mut extra, b"lyid", &id.to_be_bytes())?; + if let Some(kind) = section { + let mut s = Vec::new(); + s.u32(kind); + if kind != 3 { + s.bytes(b"8BIM"); + s.bytes(&l.blend); + } + tagged(&mut extra, b"lsct", &s)?; + } + if comps > 0 && section != Some(3) { + tagged(&mut extra, b"shmd", &cmls(l, id, comps)?)?; + } + r.u32(len32(extra.len())?); + r.bytes(&extra); + for (_, data) in chans { + self.channels.bytes(&data); + } + Ok(()) + } + + fn nodes(&mut self, nodes: &[Layer], canvas: (u32, u32), comps: usize, depth: usize) -> Result<()> { + if depth > MAX_DEPTH { + return Err(invalid(format!("groups are nested more than {MAX_DEPTH} deep"))); + } + for l in nodes.iter().rev() { + match &l.kind { + Kind::Pixels(px) => { + if px.canvas != canvas { + return Err(invalid(format!("layer \"{}\" is not the canvas size", l.name))); + } + let ch = Channels { rect: px.rect, data: px.data.clone(), mask: mask_channel(l.mask.as_ref(), canvas)? }; + self.layer(l, None, ch, comps)?; + } + Kind::Group(children) => { + let end = Layer { + name: "".into(), + visible: true, + opacity: 1.0, + blend: *b"norm", + mask: None, + comps: Vec::new(), + kind: Kind::Group(Vec::new()), + }; + self.layer(&end, Some(3), empty(), comps)?; + self.nodes(children, canvas, comps, depth + 1)?; + self.layer(l, Some(1), Channels { mask: mask_channel(l.mask.as_ref(), canvas)?, ..empty() }, comps)?; + } + } + } + Ok(()) + } +} + +fn empty() -> Channels { + Channels { rect: (0, 0, 0, 0), data: [-1i16, 0, 1, 2].map(|id| (id, empty_channel())).to_vec(), mask: None } +} + +/// The `shmd` block holding a layer's visibility in each comp (`cmls`). +fn cmls(l: &Layer, id: u32, comps: usize) -> Result> { + let visible_in = |i: usize| l.comps.get(i).copied().unwrap_or(l.visible); + let mut settings: Vec = (0..comps) + .map(|i| Value::Object("null", vec![("enab", Value::Bool(visible_in(i))), ("compList", Value::List(vec![Value::Long(i as i32 + 1)]))])) + .collect(); + // Comp 0 is the last document state: the layer as saved. + settings.push(Value::Object("null", vec![("enab", Value::Bool(l.visible)), ("compList", Value::List(vec![Value::Long(0)]))])); + let data = versioned("null", &[("LyrI", Value::Long(id as i32)), ("layerSettings", Value::List(settings))]); + let mut out = Vec::new(); + out.u32(1); + out.bytes(b"8BIM"); + out.bytes(b"cmls"); + out.u8(1); + out.bytes(&[0, 0, 0]); + out.u32(len32(data.len())?); + out.bytes(&data); + Ok(out) +} + +fn comps_resource(names: &[String]) -> Vec { + let list = names + .iter() + .enumerate() + .map(|(i, n)| Value::Object("Comp", vec![("Nm ", Value::Text(n.clone())), ("compID", Value::Long(i as i32 + 1)), ("capturedInfo", Value::Long(1))])) + .collect(); + versioned("CompList", &[("list", Value::List(list)), ("lastAppliedComp", Value::Long(1))]) +} + +/// Write `doc` as a 16-bit RGB PSD. Every layer and mask must be the merged image's size. +pub fn write_psd(doc: &Document) -> Result> { + let m = &doc.merged; + if m.width == 0 || m.height == 0 || m.width > MAX_SIDE || m.height > MAX_SIDE || m.data.len() != m.width as usize * m.height as usize * 4 { + return Err(invalid(format!("{}×{} is not a size a PSD is written at (at most {MAX_SIDE} a side)", m.width, m.height))); + } + let canvas = (m.width, m.height); + let mut out = Vec::new(); + out.bytes(b"8BPS"); + out.u16(1); + out.bytes(&[0; 6]); + out.u16(4); // RGB + the merged transparency + out.u32(m.height); + out.u32(m.width); + out.u16(16); + out.u16(3); // RGB + out.u32(0); // colour mode data + + let mut resources = Vec::new(); + if !doc.comps.is_empty() { + let data = comps_resource(&doc.comps); + resources.bytes(b"8BIM"); + resources.u16(LAYER_COMPS); + resources.bytes(&[0, 0]); // empty Pascal name, padded + resources.u32(len32(data.len())?); + resources.bytes(&data); + if data.len() % 2 == 1 { + resources.u8(0); + } + } + out.u32(len32(resources.len())?); + out.bytes(&resources); + + let mut recs = Records { records: Vec::new(), channels: Vec::new(), count: 0, next_id: 0 }; + recs.nodes(&doc.layers, canvas, doc.comps.len(), 1)?; + if recs.count > MAX_RECORDS { + return Err(invalid(format!("{} layers and groups; a document holds at most {MAX_RECORDS}", recs.count))); + } + let mut info = Vec::new(); + // Negative: the merged image's first alpha channel is its transparency. + info.i16(-(recs.count as i16)); + info.bytes(&recs.records); + info.bytes(&recs.channels); + if info.len() % 2 == 1 { + info.u8(0); + } + let mut section = Vec::new(); + section.u32(len32(info.len())?); + section.bytes(&info); + section.u32(0); // global layer mask info + out.u32(len32(section.len())?); + out.bytes(§ion); + + // The merged image, planar R, G, B, A, uncompressed: readers only show it as a preview. + out.u16(0); + for comp in [0usize, 1, 2, 3] { + for px in m.data.as_chunks::<4>().0 { + out.u16(px[comp]); + } + } + Ok(out) +} + +// ------------------------------------------------------------------------------------------ +// Reading + +/// A layer or group read back, children top-first. +#[derive(Clone, Debug, PartialEq)] +pub struct ReadLayer { + pub name: String, + pub visible: bool, + pub opacity: f32, + pub blend: [u8; 4], + /// The layer mask, when enabled. + pub mask: Option, + pub kind: ReadKind, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ReadKind { + /// Straight-alpha pixels of the layer's rectangle, whose top-left corner is at `(x, y)` on the + /// canvas (possibly off it). + Pixels { + x: i32, + y: i32, + image: Rgba16, + }, + Group(Vec), +} + +/// A layer mask over its rectangle; outside it, the mask is `default` (0 or 65535). +#[derive(Clone, Debug, PartialEq)] +pub struct ReadMask { + pub x: i32, + pub y: i32, + pub width: u32, + pub height: u32, + pub data: Vec, + pub default: u16, +} + +impl ReadMask { + /// The mask at canvas texel (`x`, `y`), 0..65535. + pub fn at(&self, x: i32, y: i32) -> u16 { + let (mx, my) = (i64::from(x) - i64::from(self.x), i64::from(y) - i64::from(self.y)); + if mx < 0 || my < 0 || mx >= i64::from(self.width) || my >= i64::from(self.height) { + return self.default; + } + self.data.get(my as usize * self.width as usize + mx as usize).copied().unwrap_or(self.default) + } +} + +/// A document read back. +#[derive(Clone, Debug, PartialEq)] +pub struct ReadDocument { + pub width: u32, + pub height: u32, + pub layers: Vec, +} + +struct Reader<'a> { + b: &'a [u8], + p: usize, +} + +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let end = self.p.checked_add(n).filter(|e| *e <= self.b.len()).ok_or_else(|| malformed("truncated file"))?; + let s = self.b.get(self.p..end).ok_or_else(|| malformed("truncated file"))?; + self.p = end; + Ok(s) + } + fn u8(&mut self) -> Result { + Ok(self.take(1)?.first().copied().unwrap_or(0)) + } + fn u16(&mut self) -> Result { + let s = self.take(2)?; + Ok(u16::from_be_bytes([s[0], s[1]])) + } + fn i16(&mut self) -> Result { + Ok(self.u16()? as i16) + } + fn u32(&mut self) -> Result { + let s = self.take(4)?; + Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]])) + } + fn i32(&mut self) -> Result { + Ok(self.u32()? as i32) + } + fn skip(&mut self, n: usize) -> Result<()> { + self.take(n).map(drop) + } +} + +struct Record { + name: String, + rect: (i32, i32, i32, i32), + channels: Vec<(i16, usize)>, + blend: [u8; 4], + opacity: u8, + visible: bool, + mask: Option<(Rect, u8, bool)>, + section: Option, +} + +fn rect_size((t, l, b, r): (i32, i32, i32, i32)) -> Result<(usize, usize)> { + let w = i64::from(r) - i64::from(l); + let h = i64::from(b) - i64::from(t); + if w < 0 || h < 0 || w > i64::from(MAX_SIDE) * 2 || h > i64::from(MAX_SIDE) * 2 { + return Err(malformed("a layer rectangle is out of range")); + } + Ok((w as usize, h as usize)) +} + +fn read_record(r: &mut Reader) -> Result { + let rect = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); + let n = r.u16()? as usize; + if n > 56 { + return Err(malformed(format!("a layer has {n} channels"))); + } + let mut channels = Vec::with_capacity(n); + for _ in 0..n { + let id = r.i16()?; + let len = r.u32()? as usize; + channels.push((id, len)); + } + if r.take(4)? != b"8BIM" { + return Err(malformed("bad blend mode signature")); + } + let mut blend = [0u8; 4]; + blend.copy_from_slice(r.take(4)?); + let opacity = r.u8()?; + let _clipping = r.u8()?; + let flags = r.u8()?; + let _ = r.u8()?; + let extra_len = r.u32()? as usize; + let extra = r.take(extra_len)?; + let mut e = Reader { b: extra, p: 0 }; + let mask_len = e.u32()? as usize; + let mask = if mask_len >= 18 { + let m = e.take(mask_len)?; + let mut mr = Reader { b: m, p: 0 }; + let mrect = (mr.i32()?, mr.i32()?, mr.i32()?, mr.i32()?); + let default = mr.u8()?; + let mflags = mr.u8()?; + // Bit 1 disables the mask. + Some((mrect, default, mflags & 2 == 0)) + } else { + e.skip(mask_len)?; + None + }; + let ranges = e.u32()? as usize; + e.skip(ranges)?; + let name_len = e.u8()? as usize; + let mut name: String = e.take(name_len)?.iter().map(|b| *b as char).collect(); + let pad = (4 - (name_len + 1) % 4) % 4; + e.skip(pad.min(e.b.len().saturating_sub(e.p)))?; + let mut section = None; + while e.b.len().saturating_sub(e.p) >= 12 { + let sig = e.take(4)?; + if sig != b"8BIM" && sig != b"8B64" { + break; + } + let mut key = [0u8; 4]; + key.copy_from_slice(e.take(4)?); + let len = e.u32()? as usize; + let data = e.take(len.min(e.b.len().saturating_sub(e.p)))?; + match &key { + b"luni" => { + let mut d = Reader { b: data, p: 0 }; + let units = d.u32()? as usize; + let raw = d.take(units.saturating_mul(2).min(data.len().saturating_sub(4)))?; + let units: Vec = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).take_while(|u| *u != 0).collect(); + name = String::from_utf16_lossy(&units); + } + b"lsct" | b"lsdk" => { + let mut d = Reader { b: data, p: 0 }; + section = Some(d.u32()?); + if data.len() >= 12 { + blend.copy_from_slice(data.get(8..12).unwrap_or(b"norm")); + } + } + _ => {} + } + } + Ok(Record { name, rect, channels, blend, opacity, visible: flags & 2 == 0, mask, section }) +} + +/// Decode one channel of `w`×`h` samples at `depth` bits into 16-bit samples. +fn decode_channel(data: &[u8], w: usize, h: usize, depth: u16, budget: &mut u64) -> Result> { + let n = w.checked_mul(h).ok_or_else(|| malformed("channel too large"))?; + if n == 0 { + return Ok(Vec::new()); + } + let bps = usize::from(depth / 8); + let need = (n * bps) as u64; + *budget = budget.checked_sub(need).ok_or_else(|| FormatError::TooLarge("the document's layers are too large to read back".into()))?; + let mut r = Reader { b: data, p: 0 }; + let code = r.u16()?; + let rest = data.get(2..).unwrap_or(&[]); + let row = w * bps; + let bytes: Vec = match code { + 0 => rest.get(..n * bps).ok_or_else(|| malformed("raw channel truncated"))?.to_vec(), + 1 => { + let mut counts = Vec::with_capacity(h); + for _ in 0..h { + counts.push(r.u16()? as usize); + } + let mut out = Vec::with_capacity(n * bps); + for c in counts { + let src = r.take(c)?; + unpack_bits(src, row, &mut out)?; + } + out + } + 2 | 3 => { + let mut out = Vec::with_capacity(n * bps); + flate2::read::ZlibDecoder::new(rest).take(need + 1).read_to_end(&mut out).map_err(|e| malformed(format!("ZIP channel: {e}")))?; + if out.len() as u64 != need { + return Err(malformed("ZIP channel has the wrong size")); + } + if code == 3 { + unpredict(&mut out, row, bps)?; + } + out + } + c => return Err(malformed(format!("unknown compression {c}"))), + }; + Ok(match bps { + 1 => bytes.iter().map(|b| u16::from(*b) * 257).collect(), + _ => bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(), + }) +} + +fn unpack_bits(src: &[u8], row: usize, out: &mut Vec) -> Result<()> { + let start = out.len(); + let mut i = 0; + while i < src.len() && out.len() - start < row { + let n = src[i] as i8; + i += 1; + if n >= 0 { + let k = n as usize + 1; + out.extend_from_slice(src.get(i..i + k).ok_or_else(|| malformed("RLE run truncated"))?); + i += k; + } else if n != -128 { + let v = *src.get(i).ok_or_else(|| malformed("RLE run truncated"))?; + out.extend(std::iter::repeat_n(v, (1 - n as isize) as usize)); + i += 1; + } + } + if out.len() - start != row { + return Err(malformed("RLE row has the wrong length")); + } + Ok(()) +} + +fn unpredict(bytes: &mut [u8], row: usize, bps: usize) -> Result<()> { + for r in bytes.chunks_mut(row.max(1)) { + match bps { + 1 => { + for i in 1..r.len() { + r[i] = r[i].wrapping_add(r[i - 1]); + } + } + 2 => { + let mut prev = 0u16; + for c in r.as_chunks_mut::<2>().0 { + let v = u16::from_be_bytes(*c).wrapping_add(prev); + c.copy_from_slice(&v.to_be_bytes()); + prev = v; + } + } + _ => return Err(FormatError::Unsupported("32-bit PSD layers".into())), + } + } + Ok(()) +} + +/// Read the layers of a PSD (version 1, 8 or 16-bit RGB). Groups come back nested. +pub fn read_psd(bytes: &[u8]) -> Result { + let mut r = Reader { b: bytes, p: 0 }; + if r.take(4)? != b"8BPS" { + return Err(malformed("not a PSD file")); + } + match r.u16()? { + 1 => {} + 2 => return Err(FormatError::Unsupported("large documents (PSB); save as PSD".into())), + v => return Err(malformed(format!("version {v}"))), + } + r.skip(6)?; + let _channels = r.u16()?; + let height = r.u32()?; + let width = r.u32()?; + let depth = r.u16()?; + let mode = r.u16()?; + if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE { + return Err(FormatError::TooLarge(format!("{width}×{height}"))); + } + if depth != 8 && depth != 16 { + return Err(FormatError::Unsupported(format!("{depth}-bit documents; save as 8 or 16-bit"))); + } + if mode != 3 { + return Err(FormatError::Unsupported("documents that are not RGB; convert to RGB first".into())); + } + let n = r.u32()? as usize; + r.skip(n)?; + let n = r.u32()? as usize; + r.skip(n)?; + let section_len = r.u32()? as usize; + let section = r.take(section_len)?; + let mut s = Reader { b: section, p: 0 }; + let info_len = s.u32()? as usize; + let info = if info_len > 0 { s.take(info_len)? } else { &[][..] }; + let info = if info.is_empty() { find_lr16(section, s.p)? } else { info }; + let mut budget = MAX_DECODED; + let mut flat: Vec<(Record, Option, Option)> = Vec::new(); + if !info.is_empty() { + let mut ir = Reader { b: info, p: 0 }; + let count = ir.i16()?.unsigned_abs() as usize; + if count > MAX_RECORDS { + return Err(FormatError::TooLarge(format!("{count} layers"))); + } + let mut records = Vec::with_capacity(count); + for _ in 0..count { + records.push(read_record(&mut ir)?); + } + for rec in records { + let (rw, rh) = rect_size(rec.rect)?; + let mut planes: [Option>; 4] = [None, None, None, None]; + let mut mask_plane = None; + for &(id, len) in &rec.channels { + let data = ir.take(len)?; + match id { + -1..=2 => { + let idx = if id == -1 { 3 } else { id as usize }; + if let Some(slot) = planes.get_mut(idx) { + *slot = Some(decode_channel(data, rw, rh, depth, &mut budget)?); + } + } + -2 => { + if let Some((mrect, _, _)) = rec.mask { + let (mw, mh) = rect_size(mrect)?; + mask_plane = Some(decode_channel(data, mw, mh, depth, &mut budget)?); + } + } + _ => {} + } + } + let pixels = (rec.section.is_none() || rec.section == Some(0)).then(|| ReadKind::Pixels { + x: rec.rect.1, + y: rec.rect.0, + image: interleave(&planes, (rw, rh)), + }); + let mask = match rec.mask { + Some((mrect, default, true)) => { + let (mw, mh) = rect_size(mrect)?; + let data = mask_plane.filter(|p| p.len() == mw * mh).unwrap_or_default(); + let (mw, mh) = if data.is_empty() { (0, 0) } else { (mw as u32, mh as u32) }; + Some(ReadMask { x: mrect.1, y: mrect.0, width: mw, height: mh, data, default: u16::from(default) * 257 }) + } + _ => None, + }; + flat.push((rec, pixels, mask)); + } + } + let mut it = flat.into_iter().rev().peekable(); + let layers = nest(&mut it, 0)?; + Ok(ReadDocument { width, height, layers }) +} + +/// The `Lr16` block after the (empty) layer info, where some writers put 16-bit layers. +fn find_lr16(section: &[u8], mut p: usize) -> Result<&[u8]> { + // Skip the global layer mask info. + let mut r = Reader { b: section, p }; + if let Ok(n) = r.u32() { + p = r.p + n as usize; + } + let mut r = Reader { b: section, p }; + while section.len().saturating_sub(r.p) >= 12 { + let sig = r.take(4)?; + if sig != b"8BIM" && sig != b"8B64" { + break; + } + let key = r.take(4)?; + let len = r.u32()? as usize; + let data = r.take(len)?; + if key == b"Lr16" { + return Ok(data); + } + if !len.is_multiple_of(4) { + r.skip((4 - len % 4).min(section.len().saturating_sub(r.p)))?; + } + } + Ok(&[]) +} + +/// Planes of a `rw`×`rh` rectangle as straight RGBA (a missing alpha plane is opaque). +fn interleave(planes: &[Option>; 4], (rw, rh): (usize, usize)) -> Rgba16 { + let n = rw * rh; + let mut data = Vec::with_capacity(n * 4); + for i in 0..n { + for (k, plane) in planes.iter().enumerate() { + data.push(match plane { + Some(p) => p.get(i).copied().unwrap_or(0), + None if k == 3 => 65535, + None => 0, + }); + } + } + Rgba16 { width: rw as u32, height: rh as u32, data } +} + +/// Records top-first into a tree: a folder record opens a group that its divider closes. +fn nest(it: &mut std::iter::Peekable, Option)>>, depth: usize) -> Result> { + if depth > MAX_DEPTH { + return Err(malformed(format!("groups nested more than {MAX_DEPTH} deep"))); + } + let mut out = Vec::new(); + while let Some((rec, pixels, mask)) = it.next() { + let base = |kind| ReadLayer { + name: rec.name.clone(), + visible: rec.visible, + opacity: f32::from(rec.opacity) / 255.0, + blend: rec.blend, + mask: mask.clone(), + kind, + }; + match rec.section { + Some(3) => return Ok(out), + Some(1) | Some(2) => { + let children = nest(it, depth + 1)?; + out.push(base(ReadKind::Group(children))); + } + _ => out.push(base(pixels.unwrap_or(ReadKind::Pixels { x: 0, y: 0, image: Rgba16 { width: 0, height: 0, data: Vec::new() } }))), + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn solid(w: u32, h: u32, rect: (u32, u32, u32, u32), px: [u16; 4]) -> Rgba16 { + let mut img = Rgba16::transparent(w, h); + for y in rect.1..rect.1 + rect.3 { + for x in rect.0..rect.0 + rect.2 { + let i = ((y * w + x) * 4) as usize; + img.data[i..i + 4].copy_from_slice(&px); + } + } + img + } + + fn px(img: Rgba16) -> Kind { + Kind::Pixels(encode_pixels(&img).unwrap()) + } + + fn layer(name: &str, kind: Kind) -> Layer { + Layer { name: name.into(), visible: true, opacity: 1.0, blend: *b"norm", mask: None, comps: Vec::new(), kind } + } + + #[test] + fn groups_masks_names_and_blends_round_trip() { + let (w, h) = (16, 8); + let mut mask = Mask16 { width: w, height: h, data: vec![0; (w * h) as usize] }; + for x in 0..8 { + mask.data[(2 * w + x) as usize] = 40000; + } + let base = + Layer { opacity: 0.5, blend: *b"mul ", comps: vec![true, false], ..layer("Base color", px(solid(w, h, (1, 1, 4, 3), [100, 200, 300, 65535]))) }; + let rough = Layer { visible: false, comps: vec![false, true], ..layer("Roughness", px(solid(w, h, (0, 0, 16, 8), [5, 5, 5, 65535]))) }; + let group = Layer { blend: *b"pass", mask: Some(encode_mask(&mask).unwrap()), ..layer("Dirt ✓", Kind::Group(vec![base, rough])) }; + let doc = Document { + layers: vec![group, layer("Layer 1", px(Rgba16::transparent(w, h)))], + merged: solid(w, h, (0, 0, 16, 8), [1, 2, 3, 65535]), + comps: vec!["Base color".into(), "Roughness".into()], + }; + let bytes = write_psd(&doc).unwrap(); + let back = read_psd(&bytes).unwrap(); + assert_eq!((back.width, back.height), (w, h)); + assert_eq!(back.layers.len(), 2); + let g = &back.layers[0]; + assert_eq!(g.name, "Dirt ✓"); + assert_eq!(&g.blend, b"pass"); + let m = g.mask.as_ref().unwrap(); + for y in 0..h as i32 { + for x in 0..w as i32 { + assert_eq!(m.at(x, y), mask.data[(y * w as i32 + x) as usize], "mask at {x},{y}"); + } + } + let ReadKind::Group(children) = &g.kind else { panic!("{g:?}") }; + assert_eq!(children.iter().map(|c| c.name.as_str()).collect::>(), ["Base color", "Roughness"]); + assert_eq!(&children[0].blend, b"mul "); + assert!((children[0].opacity - 0.5).abs() < 0.01); + assert!(!children[1].visible); + let ReadKind::Pixels { x, y, image } = &children[0].kind else { panic!() }; + assert_eq!((*x, *y, image.width, image.height), (1, 1, 4, 3), "cropped to the layer's pixels"); + assert_eq!(&image.data[..4], &[100, 200, 300, 65535]); + // The comp list is in the resources. + assert!(bytes.windows(8).any(|x| x == b"CompList")); + assert!(bytes.windows(4).any(|x| x == b"cmls")); + } + + #[test] + fn rle_and_8_bit_layers_read() { + // A hand-made 8-bit 2×1 document with one RLE layer. + let mut f = Vec::new(); + f.bytes(b"8BPS"); + f.u16(1); + f.bytes(&[0; 6]); + f.u16(3); + f.u32(1); + f.u32(2); + f.u16(8); + f.u16(3); + f.u32(0); + f.u32(0); + let mut rec = Vec::new(); + rec.i32(0); + rec.i32(0); + rec.i32(1); + rec.i32(2); + rec.u16(4); + // Each channel: compression 1, one row count (2 bytes), a run "two of v": [-1, v]. + for id in [-1i16, 0, 1, 2] { + rec.i16(id); + rec.u32(6); + } + rec.bytes(b"8BIMnorm"); + rec.u8(255); + rec.u8(0); + rec.u8(0); + rec.u8(0); + rec.u32(4 + 4 + 4); + rec.u32(0); + rec.u32(0); + rec.bytes(&[1, b'A', 0, 0]); + for v in [255u8, 10, 20, 30] { + rec.u16(1); + rec.u16(2); + rec.u8(0xFF); + rec.u8(v); + } + let mut info = Vec::new(); + info.i16(1); + info.bytes(&rec); + let mut section = Vec::new(); + section.u32(info.len() as u32); + section.bytes(&info); + section.u32(0); + f.u32(section.len() as u32); + f.bytes(§ion); + let doc = read_psd(&f).unwrap(); + let ReadKind::Pixels { image, .. } = &doc.layers[0].kind else { panic!() }; + assert_eq!(doc.layers[0].name, "A"); + assert_eq!(&image.data[4..8], &[10 * 257, 20 * 257, 30 * 257, 65535]); + } + + #[test] + fn hostile_input_is_an_error() { + assert!(read_psd(b"").is_err()); + assert!(read_psd(b"8BPS\x00\x02").is_err()); + assert!(read_psd(b"not a psd at all, really not").is_err()); + let doc = Document { layers: vec![], merged: Rgba16::transparent(4, 4), comps: vec![] }; + let mut bytes = write_psd(&doc).unwrap(); + bytes.truncate(bytes.len() / 2); + let _ = read_psd(&bytes); + let bad = Document { layers: vec![], merged: Rgba16 { width: 0, height: 0, data: vec![] }, comps: vec![] }; + assert!(write_psd(&bad).is_err()); + assert!(encode_pixels(&Rgba16 { width: 2, height: 2, data: vec![0; 3] }).is_err()); + assert!(encode_mask(&Mask16 { width: 0, height: 0, data: vec![] }).is_err()); + let wrong = Document { layers: vec![layer("x", px(Rgba16::transparent(2, 2)))], merged: Rgba16::transparent(4, 4), comps: vec![] }; + assert!(write_psd(&wrong).is_err()); + let mut deep = layer("l", px(Rgba16::transparent(4, 4))); + for _ in 0..=MAX_DEPTH { + deep = layer("g", Kind::Group(vec![deep])); + } + assert!(write_psd(&Document { layers: vec![deep], merged: Rgba16::transparent(4, 4), comps: vec![] }).is_err()); + // Every prefix of a valid file is an error or a document, never a panic. + let full = write_psd(&Document { + layers: vec![Layer { + mask: Some(encode_mask(&Mask16 { width: 4, height: 4, data: vec![65535; 16] }).unwrap()), + ..layer("g", Kind::Group(vec![layer("p", px(solid(4, 4, (0, 0, 4, 4), [1, 2, 3, 65535])))])) + }], + merged: Rgba16::transparent(4, 4), + comps: vec!["a".into()], + }) + .unwrap(); + for n in 0..full.len() { + let _ = read_psd(&full[..n]); + } + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4de90b31..c0731c3b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -338,25 +338,49 @@ OpenGL convention, `roughness`, `metallic`, `height`, `ambientOcclusion`, `emiss ## PhotoCraft hand-off -`file.sendToPhotoCraft` (File › Send layers to PhotoCraft...) writes the texture set's stack as layered -OpenRaster documents (`formats::ora`), one per texture set and channel, named -`__.ora`, and opens them in PhotoCraft (`$PHOTOCRAFT`, else `photocraft` next to the -TextureCraft executable, else on `PATH`). Each layer is rendered alone into a layer of the same name: -its fill sources, generators, filters and content effects, times its mask, so the mask becomes the -layer's transparency. Folders become groups (pass-through folders `isolation="auto"`), with the -channel's visibility, opacity and blend mode (`svg:*` names; modes OpenRaster lacks are sent as -Normal with a warning). Colour channels are sRGB, data channels as stored (height `0.5 + 0.5·h`, -normals OpenGL), 16-bit with straight alpha; `mergedimage.png` is the set's composite. +`file.sendToPhotoCraft` (File › Send layers to PhotoCraft...) writes texture sets as layered documents +and opens them in PhotoCraft (`$PHOTOCRAFT`, else `photocraft` next to the TextureCraft executable, +else on `PATH`). The menu item sends every texture set. -Each sent file is a link. When PhotoCraft saves it, its `mergedimage.png` becomes the image source of a -`PhotoCraft: ` fill at the top of the set (one undo step per save; the layers below are -untouched). The desktop app looks at the files' modification times about twice a second and never -during a stroke. Links last for the session and are not saved with the project. +**PSD (the default).** One 16-bit document per texture set, `_.psd` (`formats::psd`, +written from the public file format specification), holding every channel so that a mask edited +once shapes all of them: + +- Every folder is a group, with the folder's mask and, when all its channels blend alike, their + blend mode and opacity (otherwise a pass-through group at 100%, with a warning). +- Every layer is a pass-through group of the same name. The layer's mask (painted, generators, + filters, geometry and height masks included) is the group's own editable layer mask; it is left + out when it hides nothing. +- Inside each layer group, one pixel layer per enabled channel, named after it (`Base color`, + `Roughness`, `Metallic`, `Height`, ...), holds the layer's content for that channel (fill sources, + generators, filters and content effects, not masked), with the channel's opacity and blend mode + (modes the format lacks are sent as Normal with a warning). +- One layer comp per channel shows only that channel's layers; the document opens on the first. + The merged image is the first channel's composite. + +**OpenRaster** (`format: "ora"`). One document per texture set and channel, +`__.ora` (`formats::ora`). Each layer is rendered alone, times its mask, so the +mask becomes the layer's transparency; folders become groups (pass-through folders +`isolation="auto"`) with the channel's visibility, opacity and blend mode (`svg:*` names). + +In both, colour channels are sRGB and data channels as stored (height `0.5 + 0.5·h`, normals +OpenGL), 16-bit with straight alpha. + +Each sent file is a link. When PhotoCraft saves it, TextureCraft reads it back and every channel it +holds becomes the image source of a `PhotoCraft: ` fill at the top of the set, all in one +undo step (the layers below are untouched). An OpenRaster file brings back its `mergedimage.png`. A +PSD is recomposited per channel with TextureCraft's blend math: starting from the channel's default +value, every pixel layer named after the channel is blended in through the masks, opacity and +visibility of the groups above it; the pixel layers' own visibility is ignored, since layer comps +toggle it. Layers not named after a channel are skipped with a note in the log. A PSD whose size no +longer matches the texture set is refused. The desktop app looks at the files' modification times +about twice a second and never during a stroke. Links last for the session and are not saved with +the project. | Command | Params | |---|---| -| `file.sendToPhotoCraft` | `{dir, ts?: index\|"all" (default: the active set), channels?: [ids], open?: true}` → `{files, warnings}` | -| `photocraft.links` | `{}` → `[{path, ts, channel, layer?}]` | +| `file.sendToPhotoCraft` | `{dir, ts?: index\|"all" (default: the active set), channels?: [ids], format?: "psd"\|"ora" (default psd), open?: true}` → `{files, warnings}` | +| `photocraft.links` | `{}` → `[{path, ts, format, channels, layers: {channel: layer id}}]` | | `photocraft.sync` | `{}` → `{updated}`: read the linked files saved since the last look now | | `photocraft.unlink` | `{path?}`: stop watching one file, or all |