PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Codecs: save DDS textures, uncompressed or BC1–BC3, with optional mipmaps (#1327) (#5993)
Guillem Hermida872748fb5b2a
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rsindex 03001ab02..0e3429d07 100644--- a/apps/photocraft-cli/src/lib.rs+++ b/apps/photocraft-cli/src/lib.rs@@ -15,19 +15,21 @@ pub const USAGE: &str = "\photocraft-cli: headless PhotoCraftUSAGE:- photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]+ photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps]Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …).TIFF output is flat unless --tiff-layers keeps the layers (Photoshop layer data).--quality sets the JPEG or WebP quality; a WebP written with a quality is lossy, without one lossless.--tga-bits sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) asits alpha, 24 none. Without it: 32 with an alpha channel or transparency, else 24.--dpx-bits sets a DPX's bits per sample. Without it: 8 for an 8-bit document, else 16.+ --dds-compression sets a DDS texture's compression: none (uncompressed, the default), bc1+ (DXT1: alpha on or off), bc2 (DXT3) or bc3 (DXT5). --dds-mipmaps also writes the full mip chain.photocraft-cli info <file> [--compact]Print the document as JSON (size, mode, depth, layer tree).- photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]+ photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps]Open a file, run engine commands in order, save the result. Each --paramsapplies to the preceding --cmd. Prints each command's JSON result.- photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]+ photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps]Apply an action list to every image in a directory. A Photoshop Actions file (.atn) is aset: its action --action names plays, as below. JSON steps are [id, params] pairs,{\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them@@ -69,18 +71,23 @@ struct Subcommand {}const SUBCOMMANDS: &[Subcommand] = &[- Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits", "--dpx-bits"], bare: &["--tiff-layers"], run: convert },+ Subcommand {+ name: "convert",+ values: &["--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"],+ bare: &["--tiff-layers", "--dds-mipmaps"],+ run: convert,+ },Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) },Subcommand {name: "run",- values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"],- bare: &["--tiff-layers"],+ values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"],+ bare: &["--tiff-layers", "--dds-mipmaps"],run: run_cmds,},Subcommand {name: "batch",- values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"],- bare: &["--in-place", "--tiff-layers"],+ values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"],+ bare: &["--in-place", "--tiff-layers", "--dds-mipmaps"],run: batch,},Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet },@@ -219,6 +226,11 @@ fn export_opts(a: &Args) -> Result<ExportOptions, String> {o.encode.dpx_bits =Some(b.parse().ok().and_then(photocraft_io::DpxBits::from_bits).ok_or_else(|| format!("bad --dpx-bits `{b}`: expected 8, 10, 12 or 16"))?);}+ if let Some(c) = a.get("--dds-compression") {+ o.encode.dds.compression =+ photocraft_io::DdsCompression::from_name(c).ok_or_else(|| format!("bad --dds-compression `{c}`: expected none, bc1, bc2 or bc3"))?;+ }+ o.encode.dds.mipmaps = a.has("--dds-mipmaps");Ok(o)}diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rsindex 3c28a8196..6c62e4080 100644--- a/apps/photocraft-cli/tests/cli.rs+++ b/apps/photocraft-cli/tests/cli.rs@@ -494,6 +494,39 @@ fn dpx_converts_both_ways_with_the_bits_asked_for() {}}+/// DDS converts both ways; `--dds-compression` picks the FourCC (bytes 84–87; none writes+/// uncompressed pixels) and `--dds-mipmaps` the mip count (bytes 28–31). A compression that+/// isn't none, bc1, bc2 or bc3 is refused and nothing is written (#1327).+#[test]+fn dds_converts_both_ways_with_the_compression_asked_for() {+ let d = tmp("dds");+ let a = d.join("a.png");+ write_png(&a, 8, 4, 3);+ for (args, fourcc, mips) in [+ (&[][..], [0; 4], 1),+ (&["--dds-compression", "bc1"][..], *b"DXT1", 1),+ (&["--dds-compression", "DXT3", "--dds-mipmaps"][..], *b"DXT3", 4),+ (&["--dds-compression", "bc3"][..], *b"DXT5", 1),+ (&["--dds-mipmaps"][..], [0; 4], 4),+ ] {+ let out = d.join("a.dds");+ ok(bin().arg("convert").arg(&a).arg(&out).args(args));+ let bytes = std::fs::read(&out).unwrap();+ let mip_count = u32::from_le_bytes(bytes[28..32].try_into().unwrap());+ assert_eq!((&bytes[..4], &bytes[84..88], mip_count), (&b"DDS "[..], &fourcc[..], mips), "{args:?}");+ let back = d.join("back.png");+ ok(bin().arg("convert").arg(&out).arg(&back));+ assert!(back.exists(), "{args:?}");+ }+ for bad in ["bc7", "dxt2", ""] {+ let out = d.join("bad.dds");+ let o = bin().arg("convert").arg(&a).arg(&out).args(["--dds-compression", bad]).output().unwrap();+ assert_eq!(o.status.code(), Some(1), "--dds-compression {bad}");+ assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("bad --dds-compression `{bad}`")), "--dds-compression {bad}");+ assert!(!out.exists(), "--dds-compression {bad} wrote a file");+ }+}+/// `--tga-bits` picks a TGA's bits per pixel (byte 16 of its header); anything but 24 or 32 is/// refused and nothing is written.#[test]diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex fcacf81b2..437f5cee1 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -99,6 +99,8 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[("OpenEXR", &["exr"]),("FITS", &["fits", "fit"]),("DPX", &["dpx"]),+ // Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327).+ ("DDS", &["dds"]),];/// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog@@ -903,7 +905,7 @@ mod tests {assert!(format.caps().write, "{name}: .{ext} can't be written");}}- for ext in ["ico", "gif", "bmp"] {+ for ext in ["ico", "gif", "bmp", "dds"] {assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered");}assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type");diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.mdindex 2e65d5155..c333cbc73 100644--- a/book/src/formats/raster-formats.md+++ b/book/src/formats/raster-formats.md@@ -19,6 +19,7 @@ Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_- Formats without transparency (JPEG, Radiance HDR) get the image composited over white, as Export As and Quick Export do; in CMYK, white is no ink.- Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead (linear gray for a grayscale OpenEXR), which is how they are tagged when opened.- TGA, as Photoshop's Targa: an RGB Targa is 24 or 32 bits per pixel. Save As and Save a Copy ask (Targa Options, starting at 32 with an alpha channel, else 24); Export As has a Resolution choice (Auto, 24 or 32 bits/pixel); scripts pass `tgaBits` (`--tga-bits` on the CLI). At 32 bits the document's alpha channel is the file's alpha when it has exactly one (spot channels don't count; with several, none is used), and the colours are written exactly, never premultiplied or cleared where the alpha is 0, so a game texture's mask and its colours both survive. Without a usable alpha channel the layers' transparency is the alpha (opaque without any). 24 bits write no alpha, compositing transparency over white. Without a choice: 32 with an alpha channel or transparency, else 24. A 32-bit Targa opens as an opaque Background with its alpha as "Alpha 1", so it round-trips. Grayscale Targas are 8-bit.+- DDS, for game and 3D textures: Save As and Save a Copy ask (DDS Options) for the compression (None, uncompressed and lossless; BC1/DXT1, whose alpha is on or off; BC2/DXT3; BC3/DXT5) and whether to generate mipmaps (the full chain down to 1×1, each level a box filter of the one above). Scripts pass `ddsCompression` (`none`, `bc1`, `bc2`, `bc3`) and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Opening one reads its top mip level.Flat TIFF and JPEG exports of composited CMYK documents convert the RGB composite back throughthe document's CMYK ICC profile (relative colorimetric with black point compensation) and embeddiff --git a/contributors/people.toml b/contributors/people.tomlindex bc3533777..99d81059e 100644--- a/contributors/people.toml+++ b/contributors/people.toml@@ -181,3 +181,7 @@ sync_github_name = true[people.00xJS]sync_github_name = true++[people.guillehr2]+real_name = "Guillem Hermida"+sync_github_name = truediff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rsindex 15a0e24e3..3db25c4fd 100644--- a/crates/automation/src/rpc.rs+++ b/crates/automation/src/rpc.rs@@ -114,6 +114,7 @@ impl Headless {let mut opts =photocraft_io::ExportOptions { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits, ..Default::default() };opts.encode.dpx_bits = photocraft_engine::file_cmds::dpx_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?;+ opts.encode.dds = photocraft_engine::file_cmds::dds_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?.unwrap_or_default();if let Some(q) = p.get("quality").and_then(Value::as_u64) {opts.encode.jpeg_quality = q.clamp(1, 100) as u8;opts.encode.webp_quality = q.clamp(1, 100) as u8;diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rsindex f52376a9c..567d0b483 100644--- a/crates/automation/src/server.rs+++ b/crates/automation/src/server.rs@@ -170,6 +170,13 @@ pub struct SaveParams {/// DPX: 8, 10, 12 or 16 bits per sample. Unset: 8 for an 8-bit document, else 16.#[serde(default, rename = "dpxBits")]pub dpx_bits: Option<u8>,+ /// DDS: "none" (uncompressed, the default), "bc1" (DXT1: alpha on or off), "bc2" (DXT3) or+ /// "bc3" (DXT5).+ #[serde(default, rename = "ddsCompression")]+ pub dds_compression: Option<String>,+ /// DDS: also write the full mip chain, each level a box filter of the one above.+ #[serde(default, rename = "ddsMipmaps")]+ pub dds_mipmaps: bool,#[serde(default)]pub index: Option<usize>,}@@ -1001,10 +1008,15 @@ impl PhotocraftMcp {Some((_, Some(bits))) => Some(bits),Some((b, None)) => return Ok(fail(format!("`dpxBits` must be 8, 10, 12 or 16, got {b}"))),};+ let dds_compression = match p.dds_compression.as_deref().map(|c| (c, photocraft_io::DdsCompression::from_name(c))) {+ None => None,+ Some((_, Some(c))) => Some(c),+ Some((c, None)) => return Ok(fail(format!("`ddsCompression` must be none, bc1, bc2 or bc3, got {c:?}"))),+ };if let Some(b) = self.bridge_client() {// The bridge forwards to the running app's `app.save`, which takes only an optional// path (without one it writes back to the document's own layered file, as headless- // does) and the Targa bits, so the other options are headless-only. Saying so beats+ // does), the Targa bits and the DDS options, so the other options are headless-only. Saying so beats// saving with defaults while the caller believes their quality or format was applied.let unsupported: Vec<&str> = [p.format.is_some().then_some("format"),@@ -1026,12 +1038,19 @@ impl PhotocraftMcp {if let Some(bits) = tga_bits {params["tgaBits"] = json!(bits.bits());}+ if let Some(c) = dds_compression {+ params["ddsCompression"] = json!(c.name());+ }+ if p.dds_mipmaps {+ params["ddsMipmaps"] = json!(true);+ }return to_result(b.call("app.save", params).await);}let Some(r) = self.headless_op(move |h| {let mut opts = photocraft_io::ExportOptions { tiff_layers: p.tiff_layers, tga_bits, ..Default::default() };opts.encode.dpx_bits = dpx_bits;+ opts.encode.dds = photocraft_io::DdsOptions { compression: dds_compression.unwrap_or_default(), mipmaps: p.dds_mipmaps };if let Some(q) = p.quality {opts.encode.jpeg_quality = q.clamp(1, 100);opts.encode.webp_quality = q.clamp(1, 100);diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rsindex 7386f3d58..5a9fa7c56 100644--- a/crates/automation/tests/mcp.rs+++ b/crates/automation/tests/mcp.rs@@ -415,6 +415,45 @@ async fn headless_doc_save_writes_targa_bits() {cleanup(&dir);}+/// `ddsCompression` and `ddsMipmaps` reach the app's `app.save` through the bridge; an unknown+/// compression is refused before anything is sent.+#[tokio::test(flavor = "multi_thread")]+async fn bridge_doc_save_forwards_dds_options() {+ let (addr, app) = fake_app().await;+ let client = connect(PhotocraftMcp::bridge(&addr, CONTROL_TOKEN).unwrap()).await;+ let saved = json_of(&call(&client, "doc_save", json!({"path": "out.dds", "ddsCompression": "DXT5", "ddsMipmaps": true})).await);+ assert_eq!(saved, json!({"saved": {"path": "out.dds", "ddsCompression": "bc3", "ddsMipmaps": true}}));+ let r = call(&client, "doc_save", json!({"path": "out.dds", "ddsCompression": "bc7"})).await;+ assert_eq!(r.is_error, Some(true), "{}", text(&r));+ assert!(text(&r).contains("ddsCompression"), "{}", text(&r));+ client.cancel().await.unwrap();+ app.abort();+}++/// Headless `doc_save`/`doc_export` write the DDS compression (the FourCC, bytes 84–87) and mip+/// count (bytes 28–31) asked for; unset, an uncompressed texture without mipmaps.+#[tokio::test(flavor = "multi_thread")]+async fn headless_doc_save_writes_dds_options() {+ let dir = tmp("dds-options");+ let client = connect(headless_in(&dir)).await;+ call(&client, "doc_new", json!({"width": 16, "height": 8, "background": "white"})).await;+ for (tool, params, fourcc, mips) in [+ ("doc_export", json!({"path": "plain.dds"}), [0; 4], 1),+ ("doc_export", json!({"path": "bc1.dds", "ddsCompression": "bc1"}), *b"DXT1", 1),+ ("doc_save", json!({"path": "bc3.dds", "ddsCompression": "bc3", "ddsMipmaps": true}), *b"DXT5", 5),+ ] {+ let r = call(&client, tool, params.clone()).await;+ assert_ne!(r.is_error, Some(true), "{params}: {}", text(&r));+ let bytes = std::fs::read(dir.join(params["path"].as_str().unwrap())).unwrap();+ assert_eq!((&bytes[84..88], u32::from_le_bytes(bytes[28..32].try_into().unwrap())), (&fourcc[..], mips), "{params}");+ }+ let r = call(&client, "doc_export", json!({"path": "bad.dds", "ddsCompression": "bc7"})).await;+ assert_eq!(r.is_error, Some(true), "{}", text(&r));+ assert!(!dir.join("bad.dds").exists());+ client.cancel().await.unwrap();+ cleanup(&dir);+}+#[tokio::test(flavor = "multi_thread")]async fn bridge_response_budget_drops_connection_without_retrying_the_operation() {use photocraft_automation::{BridgeClient, budgets::MAX_RESPONSE_BYTES};diff --git a/crates/codecs/README.md b/crates/codecs/README.mdindex 46baf50f8..539365c95 100644--- a/crates/codecs/README.md+++ b/crates/codecs/README.md@@ -40,7 +40,7 @@ let out = encode(&img, Format::Tiff, &EncodeOptions::default())?;| BMP | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` || TGA | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | no | `image` (read) / built in (RLE write, one scanline per packet) || ICO | yes | yes | U8 | RGBA (at most 256×256) | yes | no | no | no | no | no | no | `image` |-| DDS | yes | **no** | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | n/a | built in |+| DDS | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | yes (BC1–BC3, when `EncodeOptions::dds` asks for one) | built in || Netpbm (PBM/PGM/PPM/PAM/PFM) | yes | yes | U8, U16, F32 (float: PFM gray/RGB only) | all six (PAM `CMYK`/`CMYK_ALPHA`) | yes (PAM) | no | no | no | no | no | no | built in || QOI | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` || OpenEXR | yes | yes | F16, F32 | Y, YA, RGB, RGBA | yes | no | no | no | no | no | no | `exr` |@@ -73,7 +73,15 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them(8, 16, 24 or 32 bits, RGB or luminance, with or without alpha) or BC1/BC2/BC3 (DXT1/DXT3/DXT5),with the legacy header or the DX10 one. Everything opens as U8; the other mip levels areignored. Cubemaps, texture arrays, volume textures, premultiplied DXT2/DXT4 and other formats- (BC4–BC7, float) are refused with `CodecError::Unsupported`. Writing is not provided.+ (BC4–BC7, float) are refused with `CodecError::Unsupported`. Writing (`EncodeOptions::dds`) makes+ a 2D texture with the legacy header: uncompressed by default (BGRA, BGRX, or luminance with or+ without alpha, so it reads back exactly), or BC1/BC2/BC3. The block encoder is our own, from+ Microsoft's public block-compression documentation: RGB565 endpoints fitted along each block's+ principal axis and refined by least squares, indices picked against the palette the reader+ decodes; BC1 turns texels under half opacity into its transparent black, and BC3 picks+ whichever alpha mode fits. `mipmaps` adds the full chain down to 1×1, each level a box filter+ of the one above (the last column and row of an odd-sized level average three pixels, so none+ is dropped). Cubemaps, arrays, BC4–BC7 and sRGB (DX10-only) formats aren't written.* **FITS.** The image in the primary HDU, or the first `IMAGE` extension, is read; `NAXIS3 = 3`opens as RGB and any other plane count opens the first plane with `DecodeWarning::MorePages`.diff --git a/crates/codecs/src/codecs/dds.rs b/crates/codecs/src/codecs/dds.rsindex efe93c7f2..d35c7d109 100644--- a/crates/codecs/src/codecs/dds.rs+++ b/crates/codecs/src/codecs/dds.rs@@ -1,13 +1,24 @@-//! DirectDraw Surface (DDS) reader: the top mip level of a 2D texture, either uncompressed-//! (8 to 32 bits per pixel described by channel masks, RGB or luminance) or block-compressed-//! BC1/BC2/BC3 (DXT1/DXT3/DXT5), with or without the DX10 header. Read-only. Cubemaps,-//! texture arrays and volume textures are refused rather than flattened to one face or slice.+//! DirectDraw Surface (DDS) textures, after Microsoft's public DDS documentation ("DDS",+//! "DDS_HEADER", "DDS_PIXELFORMAT", "DDS_HEADER_DXT10").+//!+//! Reading: the top mip level of a 2D texture, either uncompressed (8 to 32 bits per pixel+//! described by channel masks, RGB or luminance) or block-compressed BC1/BC2/BC3+//! (DXT1/DXT3/DXT5), with or without the DX10 header. Cubemaps, texture arrays and volume+//! textures are refused rather than flattened to one face or slice.+//!+//! Writing: a 2D texture, uncompressed (BGRA or BGRX, luminance with or without alpha) or+//! BC1/BC2/BC3, optionally with its full mip chain. The legacy header describes all of these,+//! so no DX10 header is written; formats only DXGI can name (BC4–BC7, sRGB) aren't written.+use std::borrow::Cow;++use super::dds_bc::{self, Block, Mask};use crate::SampleType;use crate::error::CodecError;+use crate::fidelity::Plan;use crate::format::Format;use crate::image::{ChannelLayout, Image};-use crate::options::Limits;+use crate::options::{DdsCompression, EncodeOptions, Limits};/// `DDS ` plus the 124-byte DDS_HEADER.const HEADER: usize = 128;@@ -224,27 +235,12 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {Image::from_u8(width, height, layout, pixels)}-fn rgb565(c: u16) -> [u8; 3] {- let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8;- [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)]-}-/// A BC1 colour block. BC2 and BC3 colour blocks always have four colours; only BC1's/// `c0 <= c1` order selects three colours and transparent black.fn bc1(block: &[u8], one_bit_alpha: bool) -> [[u8; 4]; 16] {let byte = |i: usize| block.get(i).copied().unwrap_or(0);let (c0, c1) = (u16::from_le_bytes([byte(0), byte(1)]), u16::from_le_bytes([byte(2), byte(3)]));- let (a, b) = (rgb565(c0), rgb565(c1));- let mix = |wa: u32, wb: u32| {- let d = wa + wb;- let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8;- [at(0), at(1), at(2), 255]- };- let palette = if c0 > c1 || !one_bit_alpha {- [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)]- } else {- [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]]- };+ let palette = dds_bc::colour_palette(c0, c1, c0 > c1 || !one_bit_alpha);let indices = u32::from_le_bytes([byte(4), byte(5), byte(6), byte(7)]);std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3])}@@ -259,21 +255,9 @@ fn bc2_alpha(block: &[u8]) -> [u8; 16] {/// 0 and 255 when `a0 <= a1`.fn bc3_alpha(block: &[u8]) -> [u8; 16] {let byte = |i: usize| block.get(i).copied().unwrap_or(0);- let (a0, a1) = (u32::from(byte(0)), u32::from(byte(1)));- let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255];- if a0 > a1 {- for (k, v) in palette.iter_mut().enumerate().skip(2) {- let k = k as u32;- *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7;- }- } else {- for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) {- let k = k as u32;- *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5;- }- }+ let palette = dds_bc::alpha_palette(byte(0), byte(1));let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]);- std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize] as u8)+ std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize])}fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] {@@ -282,3 +266,260 @@ fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] {}texels}++const DDSD_CAPS: u32 = 0x1;+const DDSD_HEIGHT: u32 = 0x2;+const DDSD_WIDTH: u32 = 0x4;+const DDSD_PITCH: u32 = 0x8;+const DDSD_PIXELFORMAT: u32 = 0x1000;+const DDSD_MIPMAPCOUNT: u32 = 0x2_0000;+const DDSD_LINEARSIZE: u32 = 0x8_0000;+const DDSCAPS_COMPLEX: u32 = 0x8;+const DDSCAPS_TEXTURE: u32 = 0x1000;+const DDSCAPS_MIPMAP: u32 = 0x40_0000;++fn encode_err(reason: impl std::fmt::Display) -> CodecError {+ CodecError::encode(Format::Dds, reason)+}++/// How a written texture stores its pixels.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Store {+ /// 8-bit luminance.+ Luminance,+ /// 8-bit luminance, then 8-bit alpha.+ LuminanceAlpha,+ /// Blue, green, red and an unused byte (written as 255, so a reader that takes it for+ /// alpha still sees an opaque texture).+ Bgrx,+ Bgra,+ Bc1,+ Bc2,+ Bc3,+}++impl Store {+ /// The storage for an image of `layout`, as [`crate::fidelity::plan`] chose it.+ fn new(compression: DdsCompression, layout: ChannelLayout) -> Result<Store, CodecError> {+ Ok(match (compression, layout) {+ (DdsCompression::None, ChannelLayout::Gray) => Store::Luminance,+ (DdsCompression::None, ChannelLayout::GrayA) => Store::LuminanceAlpha,+ (DdsCompression::None, ChannelLayout::Rgb) => Store::Bgrx,+ (DdsCompression::None, ChannelLayout::Rgba) => Store::Bgra,+ (DdsCompression::Bc1, ChannelLayout::Rgba) => Store::Bc1,+ (DdsCompression::Bc2, ChannelLayout::Rgba) => Store::Bc2,+ (DdsCompression::Bc3, ChannelLayout::Rgba) => Store::Bc3,+ (_, layout) => return Err(encode_err(format!("{layout:?} pixels can't be written as `{}`", compression.name()))),+ })+ }++ /// Bytes per pixel, or per 4×4 block for a block compression.+ fn unit(self) -> usize {+ match self {+ Store::Luminance => 1,+ Store::LuminanceAlpha => 2,+ Store::Bgrx | Store::Bgra => 4,+ Store::Bc1 => 8,+ Store::Bc2 | Store::Bc3 => 16,+ }+ }++ fn is_block(self) -> bool {+ matches!(self, Store::Bc1 | Store::Bc2 | Store::Bc3)+ }++ /// Bytes of one row of pixels (or of 4×4 blocks) of a level `width` wide.+ fn row_bytes(self, width: usize) -> Option<usize> {+ if self.is_block() { width.div_ceil(4).checked_mul(self.unit()) } else { width.checked_mul(self.unit()) }+ }++ fn level_bytes(self, width: usize, height: usize) -> Option<usize> {+ let rows = if self.is_block() { height.div_ceil(4) } else { height };+ self.row_bytes(width)?.checked_mul(rows)+ }++ /// DDS_PIXELFORMAT: flags, FourCC, bits per pixel and the red, green, blue and alpha masks.+ fn pixel_format(self) -> (u32, [u8; 4], u32, [u32; 4]) {+ match self {+ Store::Luminance => (DDPF_LUMINANCE, [0; 4], 8, [0xff, 0, 0, 0]),+ Store::LuminanceAlpha => (DDPF_LUMINANCE | DDPF_ALPHAPIXELS, [0; 4], 16, [0xff, 0, 0, 0xff00]),+ Store::Bgrx => (DDPF_RGB, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0]),+ Store::Bgra => (DDPF_RGB | DDPF_ALPHAPIXELS, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]),+ Store::Bc1 => (DDPF_FOURCC, *b"DXT1", 0, [0; 4]),+ Store::Bc2 => (DDPF_FOURCC, *b"DXT3", 0, [0; 4]),+ Store::Bc3 => (DDPF_FOURCC, *b"DXT5", 0, [0; 4]),+ }+ }+}++/// Levels in a full mip chain: the larger side halves down to 1.+fn mip_levels(width: u32, height: u32) -> u32 {+ 32 - width.max(height).max(1).leading_zeros()+}++fn half((w, h): (usize, usize)) -> (usize, usize) {+ ((w / 2).max(1), (h / 2).max(1))+}++pub(crate) fn encode(image: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError> {+ let img = image.converted(plan.layout, SampleType::U8);+ let pixels = img.as_u8().ok_or_else(|| encode_err("the image was not converted to 8 bits per channel"))?;+ let store = Store::new(opts.dds.compression, img.layout())?;+ let (width, height) = img.dimensions();+ let levels = if opts.dds.mipmaps { mip_levels(width, height) } else { 1 };+ let top = (width as usize, height as usize);+ // Every level's size, checked before anything is allocated.+ let mut sizes = Vec::new();+ let mut size = top;+ for _ in 0..levels {+ sizes.push(store.level_bytes(size.0, size.1).ok_or_else(|| encode_err("texture size overflow"))?);+ size = half(size);+ }+ let total = sizes.iter().try_fold(HEADER, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?;+ let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?;+ let mut out = crate::options::alloc_zeroed::<u8>(total)?;+ out.get_mut(..HEADER).ok_or_else(|| encode_err("output buffer too small"))?.copy_from_slice(&header);++ let channels = img.layout().channels();+ let mut level = Cow::Borrowed(pixels);+ let (mut size, mut at) = (top, HEADER);+ for (i, &bytes) in sizes.iter().enumerate() {+ let dst = out.get_mut(at..at + bytes).ok_or_else(|| encode_err("output buffer too small"))?;+ write_level(store, &level, size, dst)?;+ at += bytes;+ if i + 1 < sizes.len() {+ let next = half(size);+ level = Cow::Owned(downsample(&level, size, next, channels)?);+ size = next;+ }+ }+ Ok(out)+}++/// The `DDS ` signature and DDS_HEADER. `top` is the top level's size in bytes.+fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Result<[u8; HEADER], CodecError> {+ let mut b = [0u8; HEADER];+ let mut put = |at: usize, v: u32| {+ if let Some(d) = b.get_mut(at..at + 4) {+ d.copy_from_slice(&v.to_le_bytes());+ }+ };+ // Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size").+ let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) };+ let pitch_or_size =+ pitch_or_size.and_then(|v| u32::try_from(v).ok()).ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?;+ let mipmapped = levels > 1;+ put(4, 124);+ put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 });+ put(12, height);+ put(16, width);+ put(20, pitch_or_size);+ put(28, levels);+ let (flags, fourcc, bits, masks) = store.pixel_format();+ put(76, 32);+ put(80, flags);+ put(84, u32::from_le_bytes(fourcc));+ put(88, bits);+ for (i, mask) in masks.into_iter().enumerate() {+ put(92 + 4 * i, mask);+ }+ put(108, DDSCAPS_TEXTURE | if mipmapped { DDSCAPS_COMPLEX | DDSCAPS_MIPMAP } else { 0 });+ b[..4].copy_from_slice(b"DDS ");+ Ok(b)+}++/// Runs `f` on each `len`-byte row of `out` with its index, in parallel on native targets.+fn rows(out: &mut [u8], len: usize, f: impl Fn(usize, &mut [u8]) + Send + Sync) {+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ out.par_chunks_mut(len.max(1)).enumerate().for_each(|(i, row)| f(i, row));+ }+ #[cfg(target_arch = "wasm32")]+ for (i, row) in out.chunks_mut(len.max(1)).enumerate() {+ f(i, row);+ }+}++/// Writes one level of `width` × `height` pixels (in the image's layout) into `dst`.+fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), CodecError> {+ let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?;+ match store {+ Store::Luminance | Store::LuminanceAlpha => {+ // The image's gray (and alpha) samples, in the same order.+ let src = pixels.get(..dst.len()).ok_or_else(|| encode_err("the level is smaller than its size"))?;+ dst.copy_from_slice(src);+ }+ Store::Bgrx | Store::Bgra => {+ let channels = if store == Store::Bgra { 4 } else { 3 };+ rows(dst, row_bytes, |y, row| {+ let src = pixels.get(y * width * channels..).unwrap_or_default();+ for (d, s) in row.as_chunks_mut::<4>().0.iter_mut().zip(src.chunks_exact(channels)) {+ let byte = |i: usize| s.get(i).copied().unwrap_or(255);+ *d = [byte(2), byte(1), byte(0), byte(3)];+ }+ });+ }+ Store::Bc1 | Store::Bc2 | Store::Bc3 => {+ let (texels, _) = pixels.as_chunks::<4>();+ rows(dst, row_bytes, |by, row| {+ for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() {+ let (block, inside) = gather(texels, (width, height), bx, by);+ let encoded: &[u8] = match store {+ Store::Bc1 => &dds_bc::encode_bc1(&block, inside),+ Store::Bc2 => &dds_bc::encode_bc2(&block, inside),+ _ => &dds_bc::encode_bc3(&block, inside),+ };+ for (d, s) in d.iter_mut().zip(encoded) {+ *d = *s;+ }+ }+ });+ }+ }+ Ok(())+}++/// Block (`bx`, `by`)'s texels, and which of them lie inside the image.+fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: usize) -> (Block, Mask) {+ let mut block = [[0u8; 4]; 16];+ let mut inside: Mask = 0;+ for (t, texel) in block.iter_mut().enumerate() {+ let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4);+ if x < width+ && y < height+ && let Some(p) = texels.get(y * width + x)+ {+ *texel = *p;+ inside |= 1 << t;+ }+ }+ (block, inside)+}++/// The next mip level: each pixel the average of the 2×2 pixels it covers, or of 2×3, 3×2 or+/// 3×3 along the last column and row of an odd-sized level, so no pixel is dropped.+fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), channels: usize) -> Result<Vec<u8>, CodecError> {+ let len = nw.checked_mul(nh).and_then(|n| n.checked_mul(channels)).ok_or_else(|| encode_err("mip level size overflow"))?;+ let mut dst = crate::options::alloc_zeroed::<u8>(len)?;+ let span = |i: usize, n: usize, size: usize| 2 * i..=if i + 1 == n { size.saturating_sub(1) } else { 2 * i + 1 };+ rows(&mut dst, nw * channels, |y, row| {+ let ys = span(y, nh, h);+ for (x, px) in row.chunks_exact_mut(channels.max(1)).enumerate() {+ let xs = span(x, nw, w);+ for (c, v) in px.iter_mut().enumerate() {+ let (mut sum, mut n) = (0u32, 0u32);+ for sy in ys.clone() {+ for sx in xs.clone() {+ if let Some(&s) = src.get((sy * w + sx) * channels + c) {+ sum += u32::from(s);+ n += 1;+ }+ }+ }+ *v = ((sum + n / 2) / n.max(1)) as u8;+ }+ }+ });+ Ok(dst)+}diff --git a/crates/codecs/src/codecs/dds_bc.rs b/crates/codecs/src/codecs/dds_bc.rsnew file mode 100644index 000000000..bbd55b4bf--- /dev/null+++ b/crates/codecs/src/codecs/dds_bc.rs@@ -0,0 +1,368 @@+//! BC1, BC2 and BC3 (DXT1, DXT3, DXT5) blocks, after Microsoft's public block compression+//! documentation ("Block Compression (Direct3D 10)" and "Texture Block Compression in Direct3D+//! 11"): the palettes the DDS reader decodes with, and the block encoder the DDS writer uses.+//!+//! The encoder fits a block's colours with two RGB565 endpoints along their principal axis,+//! refines them by least squares, and scores every candidate against the exact palette the+//! reader rebuilds, so the indices it picks are the best ones for what a decoder shows.++/// The 16 texels of a 4×4 block, row by row, as RGBA.+pub(crate) type Block = [[u8; 4]; 16];++/// Bit `t` set for each texel `t` of a block that counts: edge blocks of a texture whose size is+/// not a multiple of four have texels outside the image.+pub(crate) type Mask = u16;++pub(crate) fn rgb565(c: u16) -> [u8; 3] {+ let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8;+ [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)]+}++/// The colours a colour block's indices select. Four-colour mode (BC1 with `c0 > c1`, and every+/// BC2 and BC3 block) adds two colours at thirds; three-colour mode adds the midpoint and+/// transparent black.+pub(crate) fn colour_palette(c0: u16, c1: u16, four: bool) -> [[u8; 4]; 4] {+ let (a, b) = (rgb565(c0), rgb565(c1));+ let mix = |wa: u32, wb: u32| {+ let d = wa + wb;+ let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8;+ [at(0), at(1), at(2), 255]+ };+ if four {+ [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)]+ } else {+ [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]]+ }+}++/// A BC3 alpha block's eight values: six interpolated at sevenths when `a0 > a1`, else four+/// interpolated at fifths followed by 0 and 255.+pub(crate) fn alpha_palette(a0: u8, a1: u8) -> [u8; 8] {+ let (a0, a1) = (u32::from(a0), u32::from(a1));+ let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255];+ if a0 > a1 {+ for (k, v) in palette.iter_mut().enumerate().skip(2) {+ let k = k as u32;+ *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7;+ }+ } else {+ for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) {+ let k = k as u32;+ *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5;+ }+ }+ palette.map(|v| v as u8)+}++/// A BC1 block. Texels under half opacity become BC1's transparent black, which needs the+/// three-colour mode; an opaque block takes whichever mode fits its colours better.+pub(crate) fn encode_bc1(block: &Block, inside: Mask) -> [u8; 8] {+ let transparent = select(block, inside, |t| t[3] < 128);+ colour_block(block, inside & !transparent, transparent, true)+}++/// A BC2 block: four bits of alpha per texel, then a four-colour block.+pub(crate) fn encode_bc2(block: &Block, inside: Mask) -> [u8; 16] {+ let bits = block.iter().enumerate().fold(0u64, |bits, (t, texel)| bits | ((u64::from(texel[3]) * 15 + 127) / 255) << (4 * t));+ join(bits.to_le_bytes(), colour_block(block, inside, 0, false))+}++/// A BC3 block: an interpolated alpha block, then a four-colour block.+pub(crate) fn encode_bc3(block: &Block, inside: Mask) -> [u8; 16] {+ join(alpha_block(block, inside), colour_block(block, inside, 0, false))+}++fn join(a: [u8; 8], b: [u8; 8]) -> [u8; 16] {+ std::array::from_fn(|i| if i < 8 { a.get(i) } else { b.get(i - 8) }.copied().unwrap_or(0))+}++/// The texels of `inside` for which `f` holds.+fn select(block: &Block, inside: Mask, f: impl Fn(&[u8; 4]) -> bool) -> Mask {+ block.iter().enumerate().filter(|(t, texel)| inside >> t & 1 != 0 && f(texel)).fold(0, |m, (t, _)| m | 1 << t)+}++fn rgb_of(texel: &[u8; 4]) -> [f32; 3] {+ [f32::from(texel[0]), f32::from(texel[1]), f32::from(texel[2])]+}++/// RGB565 of a colour, rounding each channel to the nearest level.+fn to565(c: [f32; 3]) -> u16 {+ let q = |v: f32, max: f32| (v.clamp(0.0, 255.0) * max / 255.0).round() as u16;+ q(c[0], 31.0) << 11 | q(c[1], 63.0) << 5 | q(c[2], 31.0)+}++fn distance(a: &[u8; 4], b: &[u8; 4]) -> u32 {+ (0..3).map(|i| u32::from(a[i].abs_diff(b[i])).pow(2)).sum()+}++/// A colour block (endpoints, then 2-bit indices) for the `opaque` texels' colours, with the+/// `transparent` ones on BC1's transparent index. `bc1` allows the three-colour mode; BC2 and+/// BC3 always decode four colours.+fn colour_block(block: &Block, opaque: Mask, transparent: Mask, bc1: bool) -> [u8; 8] {+ let colours: Vec<[f32; 3]> = block.iter().enumerate().filter(|(t, _)| opaque >> t & 1 != 0).map(|(_, texel)| rgb_of(texel)).collect();+ if colours.is_empty() {+ // Nothing visible: every texel on the transparent index (or index 0 of black).+ let indices = if transparent != 0 { u32::MAX } else { 0 };+ return pack(0, 0, indices);+ }+ let (lo, hi) = principal_endpoints(&colours);+ let mut candidates = vec![(to565(lo), to565(hi))];+ let modes: &[bool] = if transparent != 0 {+ &[false]+ } else if bc1 {+ &[true, false]+ } else {+ &[true]+ };+ let mut best: Option<(u32, [u8; 8])> = None;+ // Each refinement starts from the best block so far: its indices give the least-squares+ // endpoints, which become one more candidate.+ for round in 0..3 {+ for &(e0, e1) in &candidates {+ for &four in modes {+ let (bytes, error) = fit(block, opaque, transparent, e0, e1, four);+ if best.is_none_or(|(e, _)| error < e) {+ best = Some((error, bytes));+ }+ }+ }+ let Some((error, bytes)) = best else { break };+ if error == 0 || round == 2 {+ break;+ }+ candidates = least_squares(block, opaque, &bytes).into_iter().collect();+ if candidates.is_empty() {+ break;+ }+ }+ best.map_or([0; 8], |(_, bytes)| bytes)+}++/// Orders endpoints `e0`, `e1` for the mode (`c0 > c1` for four colours, `c0 <= c1` for three)+/// and picks each texel's nearest palette colour. Returns the block and its squared error.+fn fit(block: &Block, opaque: Mask, transparent: Mask, e0: u16, e1: u16, four: bool) -> ([u8; 8], u32) {+ let (c0, c1) = if four == (e0 >= e1) { (e0, e1) } else { (e1, e0) };+ // Equal endpoints can't be in four-colour order; the palette is then one colour either way.+ let palette = colour_palette(c0, c1, four && c0 > c1);+ let choices = if four && c0 > c1 { 4 } else { 3 };+ let mut indices = 0u32;+ let mut error = 0u32;+ for (t, texel) in block.iter().enumerate() {+ let index = if transparent >> t & 1 != 0 {+ 3+ } else if opaque >> t & 1 != 0 {+ let (i, d) = palette.iter().take(choices).enumerate().map(|(i, p)| (i, distance(texel, p))).min_by_key(|&(_, d)| d).unwrap_or((0, 0));+ error += d;+ i as u32+ } else {+ 0+ };+ indices |= index << (2 * t);+ }+ (pack(c0, c1, indices), error)+}++fn pack(c0: u16, c1: u16, indices: u32) -> [u8; 8] {+ let (c0, c1, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes());+ [c0[0], c0[1], c1[0], c1[1], i[0], i[1], i[2], i[3]]+}++/// The ends of the colours' spread along their principal axis (the covariance's dominant+/// eigenvector, by power iteration), clamped to the RGB cube.+fn principal_endpoints(colours: &[[f32; 3]]) -> ([f32; 3], [f32; 3]) {+ let n = colours.len().max(1) as f32;+ let mean = [0, 1, 2].map(|i| colours.iter().map(|c| c[i]).sum::<f32>() / n);+ let mut cov = [[0f32; 3]; 3];+ for c in colours {+ let d = [c[0] - mean[0], c[1] - mean[1], c[2] - mean[2]];+ for (i, row) in cov.iter_mut().enumerate() {+ for (j, v) in row.iter_mut().enumerate() {+ *v += d[i] * d[j];+ }+ }+ }+ let times = |a: [f32; 3]| [0, 1, 2].map(|i| cov[i][0] * a[0] + cov[i][1] * a[1] + cov[i][2] * a[2]);+ let iterate = |start: usize| {+ let mut axis = [0f32; 3];+ axis[start] = 1.0;+ for _ in 0..8 {+ let next = times(axis);+ let len = next.iter().map(|v| v * v).sum::<f32>().sqrt();+ if !len.is_normal() {+ break;+ }+ axis = next.map(|v| v / len);+ }+ axis+ };+ // From each channel's axis, keeping the one the colours spread along most: a channel that+ // varies on its own is already an eigenvector, so a single start there would never leave it+ // even when the others vary more together.+ let spread = |a: [f32; 3]| times(a).iter().zip(a).map(|(x, y)| x * y).sum::<f32>();+ let axis = [0, 1, 2].map(iterate).into_iter().max_by(|&a, &b| spread(a).total_cmp(&spread(b))).unwrap_or([1.0, 0.0, 0.0]);+ let along = |c: &[f32; 3]| (c[0] - mean[0]) * axis[0] + (c[1] - mean[1]) * axis[1] + (c[2] - mean[2]) * axis[2];+ let (lo, hi) = colours.iter().map(along).fold((f32::MAX, f32::MIN), |(lo, hi), t| (lo.min(t), hi.max(t)));+ let at = |t: f32| [0, 1, 2].map(|i| (mean[i] + t * axis[i]).clamp(0.0, 255.0));+ if lo > hi { (mean, mean) } else { (at(lo), at(hi)) }+}++/// The endpoints that minimise the squared error for the indices `bytes` already chose: each+/// texel's index fixes its weights between the endpoints, giving 2×2 normal equations per+/// channel. `None` when the indices don't constrain both endpoints.+fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u16)> {+ let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]]));+ let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);+ let four = c0 > c1;+ // How much of c0 each index holds.+ let weight = |i: u32| match (four, i) {+ (_, 0) => Some(1.0f32),+ (_, 1) => Some(0.0),+ (true, 2) => Some(2.0 / 3.0),+ (true, _) => Some(1.0 / 3.0),+ (false, 2) => Some(0.5),+ (false, _) => None,+ };+ let (mut aa, mut ab, mut bb) = (0f32, 0f32, 0f32);+ let (mut ax, mut bx) = ([0f32; 3], [0f32; 3]);+ for (t, texel) in block.iter().enumerate() {+ if opaque >> t & 1 == 0 {+ continue;+ }+ let Some(a) = weight(indices >> (2 * t) & 3) else { continue };+ let b = 1.0 - a;+ let c = rgb_of(texel);+ aa += a * a;+ ab += a * b;+ bb += b * b;+ for ((x0, x1), v) in ax.iter_mut().zip(bx.iter_mut()).zip(c) {+ *x0 += a * v;+ *x1 += b * v;+ }+ }+ let det = aa * bb - ab * ab;+ if det.abs() < 1e-3 {+ return None;+ }+ let e0 = [0, 1, 2].map(|i| (ax[i] * bb - bx[i] * ab) / det);+ let e1 = [0, 1, 2].map(|i| (bx[i] * aa - ax[i] * ab) / det);+ Some((to565(e0), to565(e1)))+}++/// A BC3 alpha block: whichever of the two modes (eight values between the extremes, or six+/// between the extremes other than 0 and 255, plus exact 0 and 255) fits better.+fn alpha_block(block: &Block, inside: Mask) -> [u8; 8] {+ let alphas = || block.iter().enumerate().filter(move |(t, _)| inside >> t & 1 != 0).map(|(_, texel)| texel[3]);+ let range = |values: &mut dyn Iterator<Item = u8>| values.fold(None, |r: Option<(u8, u8)>, a| Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a)))));+ let (lo, hi) = range(&mut alphas()).unwrap_or((0, 0));+ // Eight values need a0 > a1; equal ends fall to the six-value mode, which starts with a0 too.+ let eight = alpha_fit(block, inside, hi, lo);+ let (mid_lo, mid_hi) = range(&mut alphas().filter(|a| !matches!(a, 0 | 255))).unwrap_or((0, 0));+ let six = alpha_fit(block, inside, mid_lo, mid_hi);+ if six.1 < eight.1 { six.0 } else { eight.0 }+}++fn alpha_fit(block: &Block, inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) {+ let palette = alpha_palette(a0, a1);+ let mut bits = 0u64;+ let mut error = 0u32;+ for (t, texel) in block.iter().enumerate() {+ if inside >> t & 1 == 0 {+ continue;+ }+ let (i, d) = palette.iter().enumerate().map(|(i, &p)| (i, u32::from(p.abs_diff(texel[3])).pow(2))).min_by_key(|&(_, d)| d).unwrap_or((0, 0));+ error += d;+ bits |= (i as u64) << (3 * t);+ }+ let b = bits.to_le_bytes();+ ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn decode_colour(bytes: &[u8; 8], bc1: bool) -> Block {+ let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]]));+ let palette = colour_palette(c0, c1, c0 > c1 || !bc1);+ let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);+ std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3])+ }++ #[test]+ fn solid_blocks_land_on_the_nearest_565_colour() {+ for colour in [[0, 0, 0, 255], [255, 255, 255, 255], [12, 200, 77, 255]] {+ let block = [colour; 16];+ let out = decode_colour(&encode_bc1(&block, u16::MAX), true);+ for texel in out {+ assert!(texel.iter().zip(colour).all(|(a, b)| a.abs_diff(b) <= 4), "{texel:?} for {colour:?}");+ }+ }+ }++ #[test]+ fn two_colour_blocks_are_exact_when_the_colours_are_565() {+ let (a, b) = ([255, 0, 0, 255], [0, 0, 255, 255]);+ let block: Block = std::array::from_fn(|t| if t % 3 == 0 { a } else { b });+ for bc1 in [true, false] {+ let bytes = if bc1 { encode_bc1(&block, u16::MAX) } else { colour_block(&block, u16::MAX, 0, false) };+ assert_eq!(decode_colour(&bytes, bc1), block);+ }+ }++ #[test]+ fn bc1_punches_through_texels_under_half_alpha() {+ let block: Block = std::array::from_fn(|t| if t < 8 { [200, 100, 50, 255] } else { [9, 9, 9, 127] });+ let bytes = encode_bc1(&block, u16::MAX);+ let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]]));+ assert!(c0 <= c1, "three-colour mode");+ let out = decode_colour(&bytes, true);+ assert!(out[..8].iter().all(|t| t[3] == 255) && out[8..].iter().all(|t| *t == [0; 4]), "{out:?}");+ }++ #[test]+ fn four_colour_blocks_keep_c0_above_c1() {+ // A ramp needs all four colours; BC2 and BC3 blocks must not rely on the order, but+ // older decoders read c0 <= c1 as three colours, so the encoder never writes that.+ let block: Block = std::array::from_fn(|t| [(t * 16) as u8, 0, 0, 255]);+ let bytes = colour_block(&block, u16::MAX, 0, false);+ assert!(u16::from_le_bytes([bytes[0], bytes[1]]) > u16::from_le_bytes([bytes[2], bytes[3]]));+ }++ #[test]+ fn alpha_blocks_pick_the_mode_that_keeps_0_and_255() {+ // 0, 255 and a cluster in between: the six-value mode stores 0 and 255 exactly.+ let block: Block = std::array::from_fn(|t| [0, 0, 0, [0, 255, 100, 110][t % 4]]);+ let bytes = alpha_block(&block, u16::MAX);+ assert!(bytes[0] <= bytes[1], "six-value mode");+ let palette = alpha_palette(bytes[0], bytes[1]);+ let bits = u64::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], 0, 0]);+ for (t, texel) in block.iter().enumerate() {+ let got = palette[(bits >> (3 * t)) as usize & 7];+ assert!(got.abs_diff(texel[3]) <= 2, "texel {t}: {got} for {}", texel[3]);+ }+ }++ #[test]+ fn the_principal_axis_is_found_when_one_channel_varies_on_its_own() {+ // Red alternates on its own (variance 64); green and blue alternate together (variance 49+ // each, 98 along their shared axis), uncorrelated with red. Starting on red alone would+ // keep red's axis and flatten green and blue; the block must do better than its bounding box.+ let block: Block = std::array::from_fn(|t| {+ let gb = if (t / 2) % 2 == 0 { 121 } else { 135 };+ [if t % 2 == 0 { 120 } else { 136 }, gb, gb, 255]+ });+ let error = |bytes: &[u8; 8]| decode_colour(bytes, false).iter().zip(&block).map(|(a, b)| distance(a, b)).sum::<u32>();+ let (_, bounding_box) = fit(&block, u16::MAX, 0, to565([120.0, 121.0, 121.0]), to565([136.0, 135.0, 135.0]), true);+ let ours = error(&colour_block(&block, u16::MAX, 0, false));+ assert!(ours < bounding_box, "{ours} vs the bounding box's {bounding_box}");+ }++ #[test]+ fn texels_outside_the_image_are_ignored() {+ // Only the top-left texel is inside: its colour alone decides the endpoints.+ let mut block: Block = [[0, 255, 0, 255]; 16];+ block[0] = [255, 0, 255, 255];+ let out = decode_colour(&encode_bc1(&block, 1), true);+ assert_eq!(out[0], [255, 0, 255, 255]);+ }+}diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs/mod.rsindex 32e68b336..d9905ab97 100644--- a/crates/codecs/src/codecs/mod.rs+++ b/crates/codecs/src/codecs/mod.rs@@ -1,4 +1,5 @@pub(crate) mod dds;+pub(crate) mod dds_bc;pub(crate) mod deep_exr;pub(crate) mod dpx;pub(crate) mod exr;diff --git a/crates/codecs/src/fidelity.rs b/crates/codecs/src/fidelity.rsindex 594735edb..a6937b571 100644--- a/crates/codecs/src/fidelity.rs+++ b/crates/codecs/src/fidelity.rs@@ -6,7 +6,7 @@ use std::fmt;use crate::format::{Format, caps};use crate::image::{ChannelLayout, Image, SampleType};-use crate::options::EncodeOptions;+use crate::options::{DdsCompression, EncodeOptions};/// Something that will be lost or altered when writing an image to a format.#[derive(Debug, Clone, PartialEq)]@@ -165,6 +165,8 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Plan},// CIELab has no float form: float Lab is written with 16 bits.Format::Tiff if layout.is_lab() && sample.is_float() => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: SampleType::U16 },+ // A block-compressed DDS stores RGBA whatever the source; uncompressed keeps gray and RGB.+ Format::Dds if opts.dds.compression.is_block() => Plan { layout: ChannelLayout::Rgba, sample: SampleType::U8 },_ => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: pick_sample(sample, c.depths) },}}@@ -211,7 +213,8 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOptionif sl.has_alpha() && !p.layout.has_alpha() && image.has_translucency() {w.push(W::AlphaDiscarded);}- if format == Format::Gif && p.layout.has_alpha() && image.has_translucency() {+ let binary_alpha = format == Format::Gif || (format == Format::Dds && opts.dds.compression == DdsCompression::Bc1);+ if binary_alpha && p.layout.has_alpha() && image.has_translucency() {w.push(W::AlphaBinarized);}if sl.is_cmyk() && !p.layout.is_cmyk() {@@ -227,7 +230,7 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption// Compressionif format == Format::Gif {w.push(W::PaletteQuantized);- } else if c.lossy || (format == Format::WebP && !opts.webp_lossless) {+ } else if c.lossy || (format == Format::WebP && !opts.webp_lossless) || (format == Format::Dds && opts.dds.compression.is_block()) {w.push(W::LossyCompression);}diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rsindex fa2e1e6cb..24611bd90 100644--- a/crates/codecs/src/format.rs+++ b/crates/codecs/src/format.rs@@ -19,7 +19,8 @@ pub enum Format {Pcx,/// X PixMap icons (XPM2 plain text and XPM3 C-string arrays).Xpm,- /// DirectDraw Surface: the top mip level of a 2D texture, uncompressed or BC1–BC3.+ /// DirectDraw Surface: a 2D texture, uncompressed or BC1–BC3. Reading takes the top mip+ /// level; writing can add the full mip chain ([`crate::DdsOptions`]).Dds,Qoi,OpenExr,@@ -71,10 +72,6 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[Format::Pcx,"PCX is supported for opening legacy paint and clipart assets. New files should use PNG; writing obsolete indexed and planar variants is intentionally not provided.",),- (- Format::Dds,- "DDS is supported for opening game and 3D textures. Writing one well means choosing a block compression and generating mip levels, which belongs in a texture export, not Save As.",- ),(Format::Avif,"AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \@@ -255,7 +252,8 @@ pub fn caps(format: Format) -> FormatCaps {Format::Pnm => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, ..base },Format::Pcx => FormatCaps { read: true, write: false, layouts: &[L::Rgb], alpha: false, ..base },Format::Xpm => FormatCaps { read: true, write: false, layouts: &[L::Rgba], ..base },- Format::Dds => FormatCaps { read: true, write: false, layouts: RGB_GRAY, ..base },+ // Uncompressed by default; a block compression is lossy (see `fidelity_warnings_with`).+ Format::Dds => FormatCaps { layouts: RGB_GRAY, ..base },Format::Qoi => base,Format::OpenExr => FormatCaps { depths: &[S::F16, S::F32], layouts: RGB_GRAY, ..base },Format::Hdr => FormatCaps { depths: &[S::F32], layouts: &[L::Rgb], alpha: false, lossy: true, ..base },diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rsindex 67369d026..a5675c982 100644--- a/crates/codecs/src/lib.rs+++ b/crates/codecs/src/lib.rs@@ -38,7 +38,9 @@ pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect,pub use crate::image::{ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, Image, Metadata, SampleType,};-pub use crate::options::{DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, PngStereo, TiffCompression};+pub use crate::options::{+ DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, PngStereo, TiffCompression,+};pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp};pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding};@@ -252,7 +254,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result<VecFormat::Pnm => pnm::encode(image, plan, opts),Format::Pcx => Err(CodecError::unsupported(format, "PCX is import-only; save as PNG instead")),Format::Xpm => Err(CodecError::unsupported(format, "XPM is import-only; save as PNG instead")),- Format::Dds => Err(CodecError::unsupported(format, "DDS is import-only; save as PNG instead")),+ Format::Dds => dds::encode(image, plan, opts),Format::Fits => fits::encode(image, plan, opts),Format::Dpx => dpx::encode(image, plan, opts),Format::Cineon => Err(CodecError::unsupported(format, "Cineon is import-only; save as DPX, TIFF or EXR instead")),diff --git a/crates/codecs/src/options.rs b/crates/codecs/src/options.rsindex e6ca3cb94..08de32857 100644--- a/crates/codecs/src/options.rs+++ b/crates/codecs/src/options.rs@@ -182,6 +182,61 @@ impl DpxBits {}}+/// How a DDS texture stores its pixels.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum DdsCompression {+ /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or+ /// without alpha for grayscale. Lossless.+ #[default]+ None,+ /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become+ /// transparent black.+ Bc1,+ /// BC2 (DXT3): 8 bits per pixel, with 4 bits of explicit alpha per texel.+ Bc2,+ /// BC3 (DXT5): 8 bits per pixel, with smooth interpolated alpha.+ Bc3,+}++impl DdsCompression {+ pub const ALL: [DdsCompression; 4] = [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3];++ /// The name scripts and the CLI use: `none`, `bc1`, `bc2` or `bc3`.+ pub fn name(self) -> &'static str {+ match self {+ DdsCompression::None => "none",+ DdsCompression::Bc1 => "bc1",+ DdsCompression::Bc2 => "bc2",+ DdsCompression::Bc3 => "bc3",+ }+ }++ /// [`Self::name`] back to a compression, also taking the DXT names (`dxt1`, `dxt3`,+ /// `dxt5`), in any case. Anything else is `None`.+ pub fn from_name(name: &str) -> Option<Self> {+ match name.to_ascii_lowercase().as_str() {+ "none" => Some(DdsCompression::None),+ "bc1" | "dxt1" => Some(DdsCompression::Bc1),+ "bc2" | "dxt3" => Some(DdsCompression::Bc2),+ "bc3" | "dxt5" => Some(DdsCompression::Bc3),+ _ => None,+ }+ }++ /// A block compression (lossy), not uncompressed pixels.+ pub fn is_block(self) -> bool {+ self != DdsCompression::None+ }+}++/// What a DDS file is written with.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub struct DdsOptions {+ pub compression: DdsCompression,+ /// Write the full mip chain down to 1×1, each level a box filter of the one above.+ pub mipmaps: bool,+}+/// Options for [`crate::encode`].#[derive(Debug, Clone)]pub struct EncodeOptions {@@ -207,6 +262,8 @@ pub struct EncodeOptions {pub exr_compression: ExrCompression,/// DPX bits per sample. `None` follows the image: 8 for 8-bit, 16 otherwise.pub dpx_bits: Option<DpxBits>,+ /// DDS compression and mip chain.+ pub dds: DdsOptions,/// Embed the ICC profile when the format supports it.pub embed_icc: bool,/// Embed EXIF/XMP/DPI/text when the format supports it.@@ -227,6 +284,7 @@ impl Default for EncodeOptions {tiff_bigtiff: false,exr_compression: ExrCompression::Zip16,dpx_bits: None,+ dds: DdsOptions::default(),embed_icc: true,embed_metadata: true,}diff --git a/crates/codecs/tests/dds.rs b/crates/codecs/tests/dds.rsindex 766555f6e..ebf4042f4 100644--- a/crates/codecs/tests/dds.rs+++ b/crates/codecs/tests/dds.rs@@ -59,11 +59,12 @@ const WHITE: u16 = 0xffff;const INDICES_0123: [u8; 4] = [0x04, 0x0e, 0, 0];#[test]-fn dds_is_readable_but_not_writable() {+fn dds_is_readable_and_writable() {assert_eq!(from_extension("texture.DDS"), Some(Format::Dds));- assert!(caps(Format::Dds).read && !caps(Format::Dds).write);- let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgba, vec![0, 0, 0, 0]).unwrap();- assert!(matches!(encode(&img, Format::Dds, &Default::default()), Err(CodecError::Unsupported { .. })));+ assert!(caps(Format::Dds).read && caps(Format::Dds).write);+ let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgba, vec![1, 2, 3, 0]).unwrap();+ let b = encode(&img, Format::Dds, &Default::default()).unwrap();+ assert_eq!(decode(&b).unwrap().data(), &[1, 2, 3, 0]);}#[test]diff --git a/crates/codecs/tests/dds_write.rs b/crates/codecs/tests/dds_write.rsnew file mode 100644index 000000000..3225dd14d--- /dev/null+++ b/crates/codecs/tests/dds_write.rs@@ -0,0 +1,372 @@+//! Writing DDS textures: every storage read back through the reader, the header fields, sizes+//! that aren't a multiple of four, the mip chain, and the block-compression error on ramps.++use photocraft_codecs::{ChannelLayout, DdsCompression, DdsOptions, EncodeOptions, FidelityWarning, Format, Image, decode, encode, fidelity_warnings_with};++const DDSD_PITCH: u32 = 0x8;+const DDSD_MIPMAPCOUNT: u32 = 0x2_0000;+const DDSD_LINEARSIZE: u32 = 0x8_0000;+const REQUIRED: u32 = 0x1007; // CAPS | HEIGHT | WIDTH | PIXELFORMAT+const DDSCAPS_COMPLEX: u32 = 0x8;+const DDSCAPS_TEXTURE: u32 = 0x1000;+const DDSCAPS_MIPMAP: u32 = 0x40_0000;+const DDPF_ALPHAPIXELS: u32 = 0x1;+const DDPF_FOURCC: u32 = 0x4;+const DDPF_RGB: u32 = 0x40;+const DDPF_LUMINANCE: u32 = 0x2_0000;++const BLOCKS: [DdsCompression; 3] = [DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3];++fn opts(compression: DdsCompression, mipmaps: bool) -> EncodeOptions {+ EncodeOptions { dds: DdsOptions { compression, mipmaps }, ..Default::default() }+}++fn le32(b: &[u8], at: usize) -> u32 {+ u32::from_le_bytes(b[at..at + 4].try_into().unwrap())+}++/// A ramp along one line through RGB (red up, green up half as fast, blue down) across the+/// texture, and alpha falling from opaque down it: every block's colours lie on a line, which+/// is what a colour block stores.+fn ramp(w: u32, h: u32, layout: ChannelLayout) -> Image {+ let ch = layout.channels();+ let at = |v: u32, n: u32| (v * 255 / (n - 1).max(1)) as u8;+ let mut data = Vec::new();+ for y in 0..h {+ for x in 0..w {+ let r = at(x, w);+ let rgba = [r, 64 + r / 2, 255 - r, 255 - at(y, h)];+ match ch {+ 1 => data.push(rgba[0]),+ 2 => data.extend([rgba[0], rgba[3]]),+ _ => data.extend(&rgba[..ch]),+ }+ }+ }+ Image::from_u8(w, h, layout, data).unwrap()+}++/// The same RGBA image, fully opaque.+fn opaque(img: &Image) -> Image {+ let data = img.data().chunks(4).flat_map(|p| [p[0], p[1], p[2], 255]).collect();+ Image::from_u8(img.width(), img.height(), ChannelLayout::Rgba, data).unwrap()+}++/// Largest difference in channel `c` (of four) between RGBA images.+fn max_diff_channel(a: &Image, b: &Image, c: usize) -> u8 {+ a.data().chunks(4).zip(b.data().chunks(4)).map(|(x, y)| x[c].abs_diff(y[c])).max().unwrap_or(0)+}++/// Largest colour difference between RGBA images where `b` is visible (BC1 turns texels under+/// half opacity into transparent black).+fn max_colour_diff(a: &Image, b: &Image) -> u8 {+ a.data().chunks(4).zip(b.data().chunks(4)).filter(|(_, y)| y[3] != 0).flat_map(|(x, y)| (0..3).map(|c| x[c].abs_diff(y[c]))).max().unwrap_or(0)+}++/// A 2D gradient: red across, green down and blue along the diagonal, opaque.+fn gradient(w: u32, h: u32) -> Image {+ let data = (0..h).flat_map(|y| (0..w).flat_map(move |x| [(x * 4).min(255) as u8, (y * 4).min(255) as u8, ((x + y) * 2).min(255) as u8, 255])).collect();+ Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap()+}++/// PSNR of the colour (not the alpha) of two RGBA images.+fn psnr(a: &Image, b: &Image) -> f64 {+ let rgb = |i: &Image| i.data().chunks(4).flat_map(|p| [p[0], p[1], p[2]]).map(f64::from).collect::<Vec<_>>();+ let (a, b) = (rgb(a), rgb(b));+ let mse = a.iter().zip(&b).map(|(x, y)| (x - y).powi(2)).sum::<f64>() / a.len() as f64;+ if mse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64.powi(2) / mse).log10() }+}++/// Bytes of one level as a reader computes them from the header's pixel format.+fn level_bytes(file: &[u8], w: usize, h: usize) -> usize {+ if le32(file, 80) & DDPF_FOURCC != 0 {+ let block = if &file[84..88] == b"DXT1" { 8 } else { 16 };+ w.div_ceil(4) * h.div_ceil(4) * block+ } else {+ w * h * le32(file, 88) as usize / 8+ }+}++/// Mip level `i` of a written texture, cut out as a single-level texture and decoded.+fn level(file: &[u8], i: u32) -> Image {+ let (w, h) = (le32(file, 16) as usize, le32(file, 12) as usize);+ let size = |i: u32| ((w >> i).max(1), (h >> i).max(1));+ let start = 128 + (0..i).map(|j| level_bytes(file, size(j).0, size(j).1)).sum::<usize>();+ let (lw, lh) = size(i);+ let mut b = file[..128].to_vec();+ b[12..16].copy_from_slice(&(lh as u32).to_le_bytes());+ b[16..20].copy_from_slice(&(lw as u32).to_le_bytes());+ b[28..32].copy_from_slice(&1u32.to_le_bytes());+ b.extend(&file[start..start + level_bytes(file, lw, lh)]);+ decode(&b).unwrap()+}++#[test]+fn uncompressed_textures_round_trip_every_layout_exactly() {+ for (layout, pf_flags, bits, masks) in [+ (ChannelLayout::Gray, DDPF_LUMINANCE, 8, [0xff, 0, 0, 0]),+ (ChannelLayout::GrayA, DDPF_LUMINANCE | DDPF_ALPHAPIXELS, 16, [0xff, 0, 0, 0xff00]),+ (ChannelLayout::Rgb, DDPF_RGB, 32, [0xff_0000, 0xff00, 0xff, 0]),+ (ChannelLayout::Rgba, DDPF_RGB | DDPF_ALPHAPIXELS, 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]),+ ] {+ for (w, h) in [(1, 1), (5, 3), (17, 9)] {+ let img = ramp(w, h, layout);+ let b = encode(&img, Format::Dds, &EncodeOptions::default()).unwrap();+ let back = decode(&b).unwrap();+ assert_eq!(back.layout(), layout, "{layout:?} {w}x{h}");+ assert_eq!(back.data(), img.data(), "{layout:?} {w}x{h}");++ assert_eq!((&b[..4], le32(&b, 4), le32(&b, 76)), (&b"DDS "[..], 124, 32));+ assert_eq!(le32(&b, 8), REQUIRED | DDSD_PITCH, "pitch, not linear size, and no mip count");+ assert_eq!((le32(&b, 12), le32(&b, 16)), (h, w));+ assert_eq!(le32(&b, 20), w * bits / 8, "pitch of {layout:?} {w}x{h}");+ assert_eq!((le32(&b, 28), le32(&b, 108)), (1, DDSCAPS_TEXTURE));+ assert_eq!((le32(&b, 80), le32(&b, 88)), (pf_flags, bits));+ assert_eq!([le32(&b, 92), le32(&b, 96), le32(&b, 100), le32(&b, 104)], masks);+ assert_eq!(b.len(), 128 + (w * h * bits / 8) as usize);+ }+ }+}++#[test]+fn block_compressed_textures_round_trip_through_the_reader() {+ for (compression, fourcc, block) in [(DdsCompression::Bc1, b"DXT1", 8), (DdsCompression::Bc2, b"DXT3", 16), (DdsCompression::Bc3, b"DXT5", 16)] {+ // Not multiples of four, and the 1×1 and 2×2 textures smaller than one block.+ for (w, h) in [(1, 1), (2, 2), (4, 4), (5, 3), (7, 13), (33, 17)] {+ let img = ramp(w, h, ChannelLayout::Rgba);+ let b = encode(&img, Format::Dds, &opts(compression, false)).unwrap();+ let linear = w.div_ceil(4) * h.div_ceil(4) * block;+ assert_eq!(&b[84..88], fourcc);+ assert_eq!((le32(&b, 80), le32(&b, 88)), (DDPF_FOURCC, 0));+ assert_eq!(le32(&b, 8), REQUIRED | DDSD_LINEARSIZE, "linear size, not pitch");+ assert_eq!(le32(&b, 20), linear, "{compression:?} {w}x{h}: the top level's size");+ assert_eq!(b.len(), 128 + linear as usize);++ let back = decode(&b).unwrap();+ assert_eq!((back.dimensions(), back.layout()), ((w, h), ChannelLayout::Rgba));+ // Steep ramps across tiny textures put three colours where a block interpolates at+ // thirds, so this bound is loose; it still catches swapped channels or misplaced+ // blocks. `block_compression_error_on_gradients_is_bounded` is the tight one. A BC1+ // block with transparent texels has only three colours, so BC1's colours are+ // checked on the opaque ramp.+ let (src, back_colour) = if compression == DdsCompression::Bc1 {+ let o = opaque(&img);+ let back = decode(&encode(&o, Format::Dds, &opts(compression, false)).unwrap()).unwrap();+ (o, back)+ } else {+ (img.clone(), back.clone())+ };+ let colour = max_colour_diff(&src, &back_colour);+ assert!(colour <= 24, "{compression:?} {w}x{h}: colour off by {colour}");+ let alpha = max_diff_channel(&img, &back, 3);+ match compression {+ DdsCompression::Bc1 => assert!(back.data().chunks(4).zip(img.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 })),+ _ => assert!(alpha <= 8, "{compression:?} {w}x{h}: alpha off by {alpha}"),+ }+ }+ }+}++#[test]+fn gray_and_rgb_sources_are_written_as_rgba_blocks() {+ for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb] {+ for compression in BLOCKS {+ let img = ramp(8, 8, layout);+ let back = decode(&encode(&img, Format::Dds, &opts(compression, false)).unwrap()).unwrap();+ let want = img.convert(ChannelLayout::Rgba, img.sample_type());+ assert_eq!(back.layout(), ChannelLayout::Rgba);+ let colour = max_colour_diff(&want, &back);+ assert!(colour <= 8, "{layout:?} {compression:?}: colour off by {colour}");+ }+ }+}++#[test]+fn block_compression_error_on_gradients_is_bounded() {+ let (line, plane) = (ramp(64, 64, ChannelLayout::Rgba), gradient(64, 64));+ for compression in BLOCKS {+ let roundtrip = |img: &Image| decode(&encode(img, Format::Dds, &opts(compression, false)).unwrap()).unwrap();+ let (line_back, plane_back) = (roundtrip(&line), roundtrip(&plane));+ let (line_err, plane_err) = (max_colour_diff(&line, &line_back), max_colour_diff(&plane, &plane_back));+ let p = psnr(&plane, &plane_back);+ let alpha = max_diff_channel(&line, &line_back, 3);+ // Colours on a line only lose the RGB565 rounding of the endpoints (up to 4 levels in+ // red and blue). A gradient in two directions is not on a line: the spread off a+ // block's best line alone limits this one to about 40 dB, and RGB565 costs a little+ // more (the encoder measures 38.6 dB and 9 levels at most).+ assert!(line_err <= 5, "{compression:?}: colour ramp off by {line_err}");+ assert!(plane_err <= 10, "{compression:?}: 2D gradient off by {plane_err}");+ assert!(p >= 38.0, "{compression:?}: 2D gradient PSNR {p:.1} dB");+ match compression {+ DdsCompression::Bc1 => assert!(line_back.data().chunks(4).zip(line.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 })),+ // Four bits: within half a step of 17.+ DdsCompression::Bc2 => assert!(alpha <= 8, "BC2 alpha off by {alpha}"),+ // Eight values across a block's few levels of alpha.+ _ => assert!(alpha <= 2, "BC3 alpha off by {alpha}"),+ }+ }+}++#[test]+fn solid_and_cutout_textures_keep_their_values() {+ // RGB565-exact colours and BC2's 4-bit alpha steps come back exactly.+ let solid = Image::from_u8(6, 5, ChannelLayout::Rgba, [255, 0, 255, 170].repeat(30)).unwrap();+ for compression in BLOCKS {+ let back = decode(&encode(&solid, Format::Dds, &opts(compression, false)).unwrap()).unwrap();+ let want = if compression == DdsCompression::Bc1 { [255, 0, 255, 255] } else { [255, 0, 255, 170] };+ assert!(back.data().chunks(4).all(|p| p == want), "{compression:?}: {:?}", &back.data()[..4]);+ }+ // A cutout: BC1's transparent texels decode as transparent black, the rest stay opaque.+ let cutout: Vec<u8> = (0..36).flat_map(|i| if (i / 6 + i % 6) % 2 == 0 { [200, 40, 40, 255] } else { [10, 10, 10, 0] }).collect();+ let cutout = Image::from_u8(6, 6, ChannelLayout::Rgba, cutout).unwrap();+ for compression in BLOCKS {+ let back = decode(&encode(&cutout, Format::Dds, &opts(compression, false)).unwrap()).unwrap();+ assert_eq!(max_diff_channel(&cutout, &back, 3), 0, "{compression:?}");+ if compression == DdsCompression::Bc1 {+ assert!(back.data().chunks(4).filter(|p| p[3] == 0).all(|p| p == [0, 0, 0, 0]));+ }+ }+}++#[test]+fn mipmaps_write_the_full_chain_box_filtered() {+ // 16×8 halves to 8×4, 4×2, 2×1 and 1×1: five levels.+ let img = ramp(16, 8, ChannelLayout::Rgba);+ let b = encode(&img, Format::Dds, &opts(DdsCompression::None, true)).unwrap();+ assert_eq!(le32(&b, 8), REQUIRED | DDSD_PITCH | DDSD_MIPMAPCOUNT);+ assert_eq!(le32(&b, 28), 5);+ assert_eq!(le32(&b, 108), DDSCAPS_TEXTURE | DDSCAPS_COMPLEX | DDSCAPS_MIPMAP);+ assert_eq!(b.len(), 128 + 4 * (16 * 8 + 8 * 4 + 4 * 2 + 2 + 1));+ assert_eq!(decode(&b).unwrap().data(), img.data(), "the reader still reads the top level");+ let mut above = img.clone();+ for i in 1..5 {+ let got = level(&b, i);+ assert_eq!(got.dimensions(), ((16 >> i).max(1), (8 >> i).max(1)));+ let want = box_filter(&above);+ assert_eq!(got.data(), want.data(), "level {i}");+ above = got;+ }+ // 1×1 has a single level.+ let one = encode(&ramp(1, 1, ChannelLayout::Rgba), Format::Dds, &opts(DdsCompression::None, true)).unwrap();+ assert_eq!((le32(&one, 28), le32(&one, 8) & DDSD_MIPMAPCOUNT), (1, 0));+}++/// The documented filter, written independently: each pixel averages the 2×2 pixels it covers,+/// and the last column and row of an odd-sized level take in the leftover pixel too.+fn box_filter(src: &Image) -> Image {+ let (w, h) = (src.width() as usize, src.height() as usize);+ let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));+ let ch = src.layout().channels();+ let span = |i: usize, n: usize, size: usize| (2 * i, if i + 1 == n { size } else { 2 * i + 2 });+ let mut out = Vec::new();+ for y in 0..nh {+ for x in 0..nw {+ let ((x0, x1), (y0, y1)) = (span(x, nw, w), span(y, nh, h));+ for c in 0..ch {+ let values: Vec<u32> =+ (y0..y1).flat_map(|sy| (x0..x1).map(move |sx| (sy, sx))).map(|(sy, sx)| u32::from(src.data()[(sy * w + sx) * ch + c])).collect();+ let n = values.len() as u32;+ out.push(((values.iter().sum::<u32>() + n / 2) / n) as u8);+ }+ }+ }+ Image::from_u8(nw as u32, nh as u32, src.layout(), out).unwrap()+}++#[test]+fn odd_sized_mip_chains_keep_every_pixel() {+ // 5×3 → 2×1 → 1×1. The 2×1 level's right pixel averages columns 2–4 of all three rows.+ let img = ramp(5, 3, ChannelLayout::Gray);+ let b = encode(&img, Format::Dds, &opts(DdsCompression::None, true)).unwrap();+ assert_eq!(le32(&b, 28), 3);+ assert_eq!(b.len(), 128 + 5 * 3 + 2 + 1);+ let second = level(&b, 1);+ assert_eq!(second.data(), box_filter(&img).data());+ let px = |x: usize, y: usize| u32::from(img.data()[y * 5 + x]);+ let right: u32 = (0..3).flat_map(|y| (2..5).map(move |x| (x, y))).map(|(x, y)| px(x, y)).sum();+ assert_eq!(u32::from(second.data()[1]), (right + 4) / 9);+}++#[test]+fn block_compressed_mip_chains_have_a_block_per_small_level() {+ for compression in BLOCKS {+ let block = if compression == DdsCompression::Bc1 { 8 } else { 16 };+ let img = ramp(12, 6, ChannelLayout::Rgba);+ let b = encode(&img, Format::Dds, &opts(compression, true)).unwrap();+ // 12×6, 6×3, 3×1, 1×1: 3×2, 2×1, 1 and 1 blocks.+ assert_eq!(le32(&b, 28), 4);+ assert_eq!(le32(&b, 8), REQUIRED | DDSD_LINEARSIZE | DDSD_MIPMAPCOUNT);+ assert_eq!(le32(&b, 20), 6 * block);+ assert_eq!(b.len(), 128 + (6 + 2 + 1 + 1) * block as usize);+ for i in 0..4 {+ let got = level(&b, i);+ assert_eq!(got.dimensions(), ((12 >> i).max(1), (6 >> i).max(1)), "{compression:?} level {i}");+ }+ }+}++#[test]+fn strips_and_tiny_textures_encode_with_every_option() {+ for (w, h) in [(1, 1), (1, 9), (9, 1), (2, 3), (3, 2)] {+ for compression in DdsCompression::ALL {+ for mipmaps in [false, true] {+ let img = ramp(w, h, ChannelLayout::Rgba);+ let b = encode(&img, Format::Dds, &opts(compression, mipmaps)).unwrap_or_else(|e| panic!("{w}x{h} {compression:?} {mipmaps}: {e}"));+ assert_eq!(decode(&b).unwrap().dimensions(), (w, h));+ }+ }+ }+}++#[test]+fn fidelity_warnings_follow_the_compression() {+ let translucent = ramp(8, 8, ChannelLayout::Rgba);+ let warns = |c| fidelity_warnings_with(&translucent, Format::Dds, &opts(c, false));+ assert!(warns(DdsCompression::None).is_empty(), "uncompressed RGBA loses nothing");+ for c in BLOCKS {+ assert!(warns(c).contains(&FidelityWarning::LossyCompression), "{c:?}");+ }+ assert!(warns(DdsCompression::Bc1).contains(&FidelityWarning::AlphaBinarized));+ assert!(!warns(DdsCompression::Bc3).contains(&FidelityWarning::AlphaBinarized));+}++#[test]+fn compression_names_round_trip() {+ for c in DdsCompression::ALL {+ assert_eq!(DdsCompression::from_name(c.name()), Some(c));+ }+ assert_eq!(DdsCompression::from_name("DXT5"), Some(DdsCompression::Bc3));+ assert_eq!(DdsCompression::from_name("dxt1"), Some(DdsCompression::Bc1));+ for bad in ["", "bc7", "dxt2", "uncompressed "] {+ assert_eq!(DdsCompression::from_name(bad), None, "{bad:?}");+ }+}++/// Encode timings on a synthetic ~30 MP texture (6336×4752). Ignored by default; run in release:+///+/// ```sh+/// cargo test --release -p photocraft-codecs --test dds_write -- --ignored --nocapture+/// ```+#[test]+#[ignore]+fn dds_encode_timings_on_30_mp() {+ let (w, h) = (6336u32, 4752u32);+ let mut s = 0x1234_5678u32;+ let mut data = Vec::with_capacity(w as usize * h as usize * 4);+ for y in 0..h {+ for x in 0..w {+ s ^= s << 13;+ s ^= s >> 17;+ s ^= s << 5;+ data.extend([(x / 25 + y / 19) as u8, (x / 31) as u8 ^ (s as u8 & 3), (y / 23) as u8, (255 - x / 25) as u8]);+ }+ }+ let img = Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap();+ for compression in DdsCompression::ALL {+ for mipmaps in [false, true] {+ let t = std::time::Instant::now();+ let b = encode(&img, Format::Dds, &opts(compression, mipmaps)).unwrap();+ eprintln!("{compression:?} mipmaps={mipmaps}: {:.0} ms, {} MB", t.elapsed().as_secs_f64() * 1e3, b.len() >> 20);+ }+ }+}diff --git a/crates/codecs/tests/roundtrip.rs b/crates/codecs/tests/roundtrip.rsindex 7918d313b..9c6cb8cb6 100644--- a/crates/codecs/tests/roundtrip.rs+++ b/crates/codecs/tests/roundtrip.rs@@ -137,6 +137,9 @@ mod fits {mod dpx {cases!(Format::Dpx);}+mod dds {+ cases!(Format::Dds);+}mod qoi {cases!(Format::Qoi);}diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 2299aa3e4..f9cee9e21 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -288,8 +288,8 @@ pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {Ok(r.document)}-/// What a headless save writes beyond the format: JPEG quality, TIFF layers, Targa bits, PSD-/// previews and the PSD merged image.+/// What a headless save writes beyond the format: JPEG quality, TIFF layers, Targa bits, DPX+/// bits, DDS compression and mipmaps, PSD previews and the PSD merged image.#[derive(Debug, Clone, Copy)]pub(crate) struct SaveOpts {/// Photoshop's 0–12 JPEG scale.@@ -301,6 +301,9 @@ pub(crate) struct SaveOpts {pub tga_bits: Option<photocraft_io::TgaBits>,/// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16.pub dpx_bits: Option<photocraft_io::DpxBits>,+ /// DDS: the compression and whether to write the mip chain (`"ddsCompression"`,+ /// `"ddsMipmaps"`); unset, uncompressed without mipmaps.+ pub dds: photocraft_io::DdsOptions,/// PSD/PSB: embed the thumbnail resource (Preferences › File Handling › Image Previews).pub image_previews: bool,/// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB@@ -310,7 +313,15 @@ pub(crate) struct SaveOpts {impl Default for SaveOpts {fn default() -> Self {- SaveOpts { quality: None, tiff_layers: false, tga_bits: None, dpx_bits: None, image_previews: true, psd_maximize_compatibility: true }+ SaveOpts {+ quality: None,+ tiff_layers: false,+ tga_bits: None,+ dpx_bits: None,+ dds: photocraft_io::DdsOptions::default(),+ image_previews: true,+ psd_maximize_compatibility: true,+ }}}@@ -326,6 +337,7 @@ impl SaveOpts {tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false),tga_bits: tga_bits_param(p, cmd)?,dpx_bits: dpx_bits_param(p, cmd)?,+ dds: dds_param(p, cmd)?.unwrap_or_default(),image_previews: file_handling.image_previews != crate::prefs::Ask::Never,psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never,})@@ -370,6 +382,30 @@ pub fn dpx_bits_param(p: &Value, cmd: &str) -> Result<Option<photocraft_io::DpxB}}+/// The DDS options in `p`: `"ddsCompression": "none" | "bc1" | "bc2" | "bc3"` (or the DXT names)+/// and `"ddsMipmaps": bool`. `None` when neither is given (Save As then asks); either alone+/// leaves the other at its default (uncompressed, no mipmaps). Anything else is a bad parameter+/// of command `cmd`.+pub fn dds_param(p: &Value, cmd: &str) -> Result<Option<photocraft_io::DdsOptions>> {+ let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg };+ let compression = match p.get("ddsCompression") {+ None | Some(Value::Null) => None,+ Some(v) => Some(+ v.as_str()+ .and_then(photocraft_io::DdsCompression::from_name)+ .ok_or_else(|| bad(format!("`ddsCompression` must be \"none\", \"bc1\", \"bc2\" or \"bc3\", got {v}")))?,+ ),+ };+ let mipmaps = match p.get("ddsMipmaps") {+ None | Some(Value::Null) => None,+ Some(v) => Some(v.as_bool().ok_or_else(|| bad(format!("`ddsMipmaps` must be true or false, got {v}")))?),+ };+ if compression.is_none() && mipmaps.is_none() {+ return Ok(None);+ }+ Ok(Some(photocraft_io::DdsOptions { compression: compression.unwrap_or_default(), mipmaps: mipmaps.unwrap_or(false) }))+}+/// Encodes `doc` for `path`'s extension.pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> Result<(Vec<u8>, Vec<String>)> {crate::allocation::checkpoint("saving document")?;@@ -387,6 +423,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> R// lossy or lossless as it was), as Photoshop's Save does.photocraft_io::apply_file_encoding(doc, &mut opts.encode);opts.encode.dpx_bits = save.dpx_bits;+ opts.encode.dds = save.dds;if let Some(q) = save.quality {let q = (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8;opts.encode.jpeg_quality = q;@@ -1651,7 +1688,7 @@ pub fn specs() -> Vec<CommandSpec> {"Save a Copy…",&["File"],Some("Cmd+Alt+S"),- r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)}"##,+ r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)}"##,native_doc,save_a_copy),@@ -1714,7 +1751,7 @@ pub fn specs() -> Vec<CommandSpec> {"Batch…",&["File", "Automate"],None,- r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"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)"##,+ r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"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),@@ -1723,7 +1760,7 @@ pub fn specs() -> Vec<CommandSpec> {"Image Processor…",&["File", "Scripts"],None,- r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,+ r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,native,image_processor),@@ -1751,7 +1788,7 @@ pub fn specs() -> Vec<CommandSpec> {"Layers to Files…",&["File", "Export"],None,- r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)} → {files}"##,+ r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##,native_doc,layers_to_files),diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rsindex b07c64985..167ddfb89 100644--- a/crates/engine/src/file_cmds/tests.rs+++ b/crates/engine/src/file_cmds/tests.rs@@ -219,6 +219,53 @@ fn save_a_copy_writes_the_dpx_bits_asked_for() {}}+/// `ddsCompression` picks the DDS FourCC (or none, uncompressed) and `ddsMipmaps` the mip count+/// in the header; unset, an uncompressed texture without mipmaps. Bad values are refused before+/// anything is written.+#[test]+fn save_a_copy_writes_the_dds_options_asked_for() {+ let dir = tmp("dds-options");+ let le32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap());+ for (params, fourcc, mips) in [+ (json!({}), [0; 4], 1),+ (json!({"ddsCompression": "none", "ddsMipmaps": true}), [0; 4], 5),+ (json!({"ddsCompression": "bc1"}), *b"DXT1", 1),+ (json!({"ddsCompression": "DXT3", "ddsMipmaps": false}), *b"DXT3", 1),+ (json!({"ddsCompression": "bc3", "ddsMipmaps": true}), *b"DXT5", 5),+ (json!({"ddsCompression": null, "ddsMipmaps": null}), [0; 4], 1),+ ] {+ let mut s = session(16, 12, 8);+ let out = join(&dir, "a.dds");+ let mut p = params.clone();+ p["path"] = json!(out);+ s.execute("file.saveACopy", p).unwrap();+ let bytes = std::fs::read(&out).unwrap();+ assert_eq!((&bytes[..4], &bytes[84..88], le32(&bytes, 28)), (&b"DDS "[..], &fourcc[..], mips), "{params}");+ assert_eq!(photocraft_io::import("a.dds", &bytes).unwrap().document.size, photocraft_geom::Size::new(16, 12), "{params}");+ }+ let mut s = session(8, 8, 8);+ let state = |s: &Session| s.active().map(|st| (st.revision, st.path.clone(), st.is_dirty()));+ let before = state(&s);+ for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsCompression": 1}), json!({"ddsMipmaps": "yes"}), json!({"ddsMipmaps": 1})] {+ let out = join(&dir, "bad.dds");+ let mut p = bad.clone();+ p["path"] = json!(out);+ let r = s.execute("file.saveACopy", p);+ assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}");+ assert!(!std::path::Path::new(&out).exists(), "{bad}: nothing written");+ assert_eq!(state(&s), before, "{bad}: the document is untouched");+ }+}++#[test]+fn dds_params_are_none_until_one_is_given() {+ use photocraft_io::{DdsCompression, DdsOptions};+ assert_eq!(dds_param(&json!({}), "file.saveAs").unwrap(), None);+ assert_eq!(dds_param(&json!({"ddsCompression": null}), "file.saveAs").unwrap(), None);+ assert_eq!(dds_param(&json!({"ddsMipmaps": true}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::None, mipmaps: true }));+ assert_eq!(dds_param(&json!({"ddsCompression": "bc2"}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::Bc2, mipmaps: false }));+}+/// A `tgaBits` other than 24 or 32 is a bad parameter, reported before anything is written.#[test]fn bad_targa_bits_are_refused_before_writing() {diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex 00163e93c..f604b8c17 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -68,8 +68,8 @@ pub mod text_styles_map;pub mod tiff_layers;pub mod vector_map;-pub use photocraft_codecs::DpxBits;use photocraft_codecs::{CodecError, EncodeOptions};+pub use photocraft_codecs::{DdsCompression, DdsOptions, DpxBits};use photocraft_doc::{Adjustment, Document, Layer, LayerContent};use photocraft_psd::{PsdError, PsdFile};diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rsindex 0d227255d..c6ca4cd60 100644--- a/crates/ui-egui/examples/snapshot.rs+++ b/crates/ui-egui/examples/snapshot.rs@@ -54,6 +54,7 @@ fn main() {opts.encode.webp_quality = q;}opts.tga_bits = settings.tga_bits;+ opts.encode.dds = settings.dds;photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string())})),write: Some(Box::new(|path: &str, bytes: &[u8]| photocraft_format::atomic_write(std::path::Path::new(path), bytes).map_err(|e| e.to_string()))),diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 581925f83..321c73ec6 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -1280,10 +1280,10 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)}None => err("missing `path`"),},- "app.save" => match crate::targa_options_ui::bits_param(p, "app.save") {- Ok(tga_bits) => {+ "app.save" => match crate::FormatChoices::from_params(p, "app.save") {+ Ok(choices) => {let path = s("path").map(str::to_string);- run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, tga_bits))+ run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, choices))}Err(e) => err(e),},@@ -2441,6 +2441,37 @@ mod tests {assert_eq!(written.borrow().len(), 3, "a bad tgaBits writes nothing");}+ /// `app.save` takes the DDS options (`ddsCompression`, `ddsMipmaps`) and never stops at DDS+ /// Options.+ #[test]+ fn automation_save_passes_dds_options_without_asking() {+ use photocraft_io::{DdsCompression, DdsOptions};+ use std::cell::RefCell;+ use std::rc::Rc;+ let asked: Rc<RefCell<Vec<DdsOptions>>> = Rc::default();+ let a = asked.clone();+ let services = crate::Services {+ export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| {+ a.borrow_mut().push(s.dds);+ Ok((b"out".to_vec(), Vec::new()))+ })),+ automation_write: Some(Box::new(|_: &str, _: &[u8]| Ok(()))),+ ..Default::default()+ };+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);+ let ctx = egui::Context::default();+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();+ for params in [json!({"path": "a.dds"}), json!({"path": "b.dds", "ddsCompression": "bc1", "ddsMipmaps": true})] {+ let r = call(&mut app, &ctx, "app.save", params.clone());+ assert_eq!(r["result"]["path"], params["path"], "{r}");+ assert!(app.dds_options.is_none(), "automation saves never prompt");+ }+ assert_eq!(*asked.borrow(), [DdsOptions::default(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }]);+ let r = call(&mut app, &ctx, "app.save", json!({"path": "c.dds", "ddsCompression": "bc9"}));+ assert!(r["error"].as_str().unwrap().contains("ddsCompression"), "{r}");+ assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing");+ }+#[test]fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {use photocraft_color::{ColorMode, SampleType};diff --git a/crates/ui-egui/src/dds_options_ui.rs b/crates/ui-egui/src/dds_options_ui.rsnew file mode 100644index 000000000..c795643a7--- /dev/null+++ b/crates/ui-egui/src/dds_options_ui.rs@@ -0,0 +1,148 @@+//! DDS Options: the compression and mip chain File › Save As and Save a Copy ask for before+//! writing a DirectDraw Surface texture (#1327). Photoshop has no DDS writer of its own (a plug-in+//! adds one), so this follows the texture tools' usual choices: uncompressed, or BC1/BC2/BC3+//! (DXT1/DXT3/DXT5), and whether to generate mipmaps (see `photocraft_io::DdsOptions`).+//!+//! The save is parked in [`Prompt`] while the modal is up (egui is immediate-mode) and written+//! once answered. Cancel drops the save. Scripts skip the prompt by passing `ddsCompression` or+//! `ddsMipmaps`.++use photocraft_io::{DdsCompression, DdsOptions};++use crate::{ExportSettings, PhotocraftApp};++/// A save waiting on the DDS Options answer.+pub struct Prompt {+ /// The document that requested the save, even if tabs change while this is open.+ doc: photocraft_doc::DocId,+ /// Where the texture goes.+ pub path: String,+ /// The options chosen, starting uncompressed without mipmaps.+ pub options: DdsOptions,+ /// Save a Copy: the document keeps its path and unsaved changes.+ pub copy: bool,+ /// The step the answered save is recorded as (`file.saveAs` or `file.saveACopy`), so an+ /// action being recorded keeps it; `file.save` when File › Save confirmed the document's own+ /// texture (#3531), which plays back on the file the action is played on.+ pub record: &'static str,+}++/// `true` when `path` names a DDS texture.+pub fn wants_prompt(path: &str) -> bool {+ photocraft_engine::file_cmds::extension(path).and_then(|e| photocraft_codecs::from_extension(&e)) == Some(photocraft_codecs::Format::Dds)+}++/// The DDS options a command or control call asks for (`"ddsCompression"`, `"ddsMipmaps"`),+/// which skip the prompt.+pub fn options_param(params: &serde_json::Value, cmd: &str) -> Result<Option<DdsOptions>, String> {+ photocraft_engine::file_cmds::dds_param(params, cmd).map_err(|e| e.to_string())+}++/// The params a save with `options` is recorded with.+pub fn record(options: DdsOptions, step: &mut serde_json::Value) {+ step["ddsCompression"] = options.compression.name().into();+ step["ddsMipmaps"] = options.mipmaps.into();+}++/// Parks the save behind the prompt. A prompt already waiting is never replaced.+pub fn park(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str) -> Result<(), String> {+ if app.save_options_open() {+ return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());+ }+ let doc = app.active_doc_id()?;+ app.dds_options = Some(Prompt { doc, path, options: DdsOptions::default(), copy, record });+ Ok(())+}++/// The block compressions go by their format names, which stay untranslated like other+/// technology names.+fn label(c: DdsCompression) -> &'static str {+ match c {+ DdsCompression::None => tl!("None"),+ DdsCompression::Bc1 => "BC1 / DXT1",+ DdsCompression::Bc2 => "BC2 / DXT3",+ DdsCompression::Bc3 => "BC3 / DXT5",+ }+}++pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {+ let Some(p) = &mut app.dds_options else { return };+ let (mut ok, mut cancel) = (false, false);+ let mut options = p.options;+ let modal = egui::Modal::new(egui::Id::new("dds-options")).show(ctx, |ui| {+ ui.set_max_width(340.0);+ ui.label(egui::RichText::new(tl!("DDS Options")).font(crate::theme::semibold(15.0)));+ ui.add_space(4.0);+ crate::widgets::hairline(ui);+ ui.add_space(8.0);+ crate::widgets::section_label(ui, tl!("Compression"));+ for c in DdsCompression::ALL {+ ui.radio_value(&mut options.compression, c, label(c));+ }+ ui.add_space(8.0);+ crate::widgets::checkbox(ui, &mut options.mipmaps, tl!("Generate Mipmaps"));+ ui.add_space(12.0);+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.spacing_mut().item_spacing.x = 10.0;+ ok = crate::widgets::primary_button(ui, tl!("OK"), 84.0).clicked();+ cancel = crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked();+ });+ });+ cancel |= modal.should_close();+ p.options = options;+ // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels.+ if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) {+ let Some(p) = app.dds_options.take() else { return };+ let settings = ExportSettings { dds: p.options, ..app.save_settings() };+ let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) };+ record(p.options, &mut step);+ let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy));+ if written.is_ok() {+ // An action being recorded keeps the Save As or Save a Copy with this answer.+ app.session.journal.push((p.record.into(), step));+ }+ match written {+ Err(e) => {+ app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);+ app.ui.status_error = true;+ }+ Ok(Some(_)) if !p.copy => crate::discard_ui::saved_document(app, ctx, p.doc),+ // A background save releases the close prompt when it finishes (`jobs_ui`).+ Ok(_) => {}+ }+ } else if cancel {+ app.dds_options = None;+ app.ui.status = tl!("Save cancelled").into();+ app.ui.status_error = false;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn dds_names() {+ assert!(wants_prompt("a.dds"));+ assert!(wants_prompt("dir/sub/a.DDS"));+ assert!(wants_prompt("C:\\x\\y.dds"));+ assert!(!wants_prompt("a.dds.psd"));+ assert!(!wants_prompt(".dds"));+ assert!(!wants_prompt("a.png"));+ }++ #[test]+ fn options_params() {+ use serde_json::json;+ assert_eq!(options_param(&json!({}), "file.saveAs"), Ok(None));+ assert_eq!(options_param(&json!({"ddsCompression": "bc3"}), "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::Bc3, mipmaps: false })));+ assert_eq!(options_param(&json!({"ddsMipmaps": true}), "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::None, mipmaps: true })));+ for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsCompression": 3}), json!({"ddsMipmaps": "yes"})] {+ assert!(options_param(&bad, "file.saveAs").is_err(), "{bad}");+ }+ let mut step = json!({"path": "a.dds"});+ record(DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }, &mut step);+ assert_eq!(step, json!({"path": "a.dds", "ddsCompression": "bc1", "ddsMipmaps": true}));+ assert_eq!(options_param(&step, "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::Bc1, mipmaps: true })));+ }+}diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rsindex 82e4497d9..e9b5504be 100644--- a/crates/ui-egui/src/discard_ui.rs+++ b/crates/ui-egui/src/discard_ui.rs@@ -959,6 +959,9 @@ mod tests {#[path = "targa_tests.rs"]mod targa_tests;+ #[path = "dds_tests.rs"]+ mod dds_tests;+/// One frame with the window's close button pressed; the commands the guard sent.fn window_close_commands(app: &mut PhotocraftApp) -> Vec<egui::ViewportCommand> {let mut info = egui::ViewportInfo::default();diff --git a/crates/ui-egui/src/discard_ui/tests/dds_tests.rs b/crates/ui-egui/src/discard_ui/tests/dds_tests.rsnew file mode 100644index 000000000..f1c88dec8--- /dev/null+++ b/crates/ui-egui/src/discard_ui/tests/dds_tests.rs@@ -0,0 +1,217 @@+//! DDS Options on Save As and Save a Copy: the compression and mipmaps it asks for, the scripted+//! `ddsCompression` and `ddsMipmaps` that skip it, and action recording and playback (#1327).+use super::*;+use crate::{FileDialogAnswer, dds_options_ui};+use egui_kittest::kittest::Queryable;+use photocraft_io::{DdsCompression, DdsOptions};+use std::{cell::RefCell, rc::Rc};++/// Each write: the path, and the DDS options the export was asked for.+type Writes = Rc<RefCell<Vec<(String, DdsOptions)>>>;++const PLAIN: DdsOptions = DdsOptions { compression: DdsCompression::None, mipmaps: false };++/// One 8×8 RGB document whose exports record their DDS options, in a harness showing DDS Options+/// and answering a save dialog with `to`.+fn dds_app(to: &str) -> (Prompted, Writes) {+ let mut app = app_with_docs(1);+ let writes: Writes = Rc::default();+ let (asked, written) = (Rc::new(RefCell::new(PLAIN)), writes.clone());+ let seen = asked.clone();+ app.services.file_dialog = Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo(to.into()))]).0);+ app.services.export = Some(Box::new(move |_, _, settings| {+ *seen.borrow_mut() = settings.dds;+ Ok((Vec::new(), Vec::new()))+ }));+ app.services.write = Some(Box::new(move |path, _| {+ written.borrow_mut().push((path.to_string(), *asked.borrow()));+ Ok(())+ }));+ let h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state(+ |ui, app| {+ show(app, ui.ctx());+ dds_options_ui::show(app, ui.ctx());+ app.poll_file_dialog(ui.ctx(), None);+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h.ctx.set_os(egui::os::OperatingSystem::Windows);+ (h, writes)+}++/// Save As to a DDS texture asks first, starting uncompressed without mipmaps, and writes only+/// what is chosen once answered.+#[test]+fn save_as_to_a_dds_texture_asks_for_its_compression() {+ let (mut h, writes) = dds_app("unused.dds");+ h.state_mut().save_as(Some("t.dds".into())).unwrap();+ h.run_steps(2);+ assert_eq!(h.state().dds_options.as_ref().map(|p| (p.options, p.copy)), Some((PLAIN, false)));+ assert!(writes.borrow().is_empty(), "nothing is written before the answer");+ assert!(h.state_mut().save_as(Some("other.dds".into())).is_err(), "one save at a time");+ h.get_by_label("BC3 / DXT5").click();+ h.run_steps(2);+ h.get_by_label("Generate Mipmaps").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ let chosen = DdsOptions { compression: DdsCompression::Bc3, mipmaps: true };+ assert_eq!(writes.borrow().as_slice(), &[("t.dds".to_string(), chosen)]);+ assert!(h.state().dds_options.is_none());+ assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("t.dds"));++ // Cancel writes nothing.+ h.state_mut().save_as(Some("c.dds".into())).unwrap();+ h.run_steps(2);+ h.key_press(Key::Escape);+ h.run_steps(3);+ assert!(h.state().dds_options.is_none());+ assert_eq!(writes.borrow().len(), 1, "cancelled: nothing more written");+ assert_eq!(h.state().ui.status, "Save cancelled");+}++/// Scripts choose with `ddsCompression` or `ddsMipmaps` and are never asked; bad values write+/// nothing, and other formats aren't asked.+#[test]+fn scripted_dds_options_and_other_formats_skip_the_prompt() {+ let (mut h, writes) = dds_app("unused.dds");+ let ctx = h.ctx.clone();+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "s.dds", "ddsCompression": "bc1"})).unwrap();+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "m.dds", "ddsMipmaps": true})).unwrap();+ assert!(h.state().dds_options.is_none());+ for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsMipmaps": 1})] {+ let mut p = bad.clone();+ p["path"] = json!("bad.dds");+ assert!(crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", p).is_err(), "{bad}");+ }+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "p.png"})).unwrap();+ assert!(h.state().dds_options.is_none());+ assert_eq!(+ writes.borrow().as_slice(),+ &[+ ("s.dds".to_string(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }),+ ("m.dds".to_string(), DdsOptions { compression: DdsCompression::None, mipmaps: true }),+ ("p.png".to_string(), PLAIN),+ ]+ );+}++/// Save a Copy to a DDS texture asks too, and the copy leaves the document's path and unsaved+/// state.+#[test]+fn save_a_copy_to_a_dds_texture_asks_and_keeps_the_document_unsaved() {+ let (mut h, writes) = dds_app("copy.dds");+ make_dirty(h.state_mut(), 0);+ let ctx = h.ctx.clone();+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveACopy", json!({})).unwrap();+ h.run_steps(3);+ assert_eq!(h.state().dds_options.as_ref().map(|p| (p.options, p.copy)), Some((PLAIN, true)));+ assert!(dds_options_ui::park(h.state_mut(), "other.dds".into(), false, "file.saveAs").is_err(), "the waiting prompt is kept");+ h.key_press(Key::Enter);+ h.run_steps(3);+ assert_eq!(writes.borrow().as_slice(), &[("copy.dds".to_string(), PLAIN)]);+ let st = h.state().session.active().unwrap();+ assert!(st.is_dirty());+ assert_eq!(st.path, None);+}++/// An action being recorded keeps a DDS Save As or Save a Copy with its options, answered in DDS+/// Options or scripted, and plays them back without asking.+#[test]+fn recorded_dds_saves_keep_their_options_and_replay_without_asking() {+ let (mut h, writes) = dds_app("copy.dds");+ let ctx = h.ctx.clone();+ h.state_mut().run("actions.record", json!({})).unwrap();+ h.state_mut().save_as(Some("t.dds".into())).unwrap();+ h.run_steps(2);+ h.get_by_label("BC1 / DXT1").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveACopy", json!({})).unwrap();+ h.run_steps(3);+ h.get_by_label("Generate Mipmaps").click();+ h.run_steps(2);+ h.key_press(Key::Enter);+ h.run_steps(3);+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "s.dds", "ddsCompression": "bc2"})).unwrap();+ h.state_mut().run("actions.stop", json!({})).unwrap();+ let want = [+ ("t.dds".to_string(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }),+ ("copy.dds".to_string(), DdsOptions { compression: DdsCompression::None, mipmaps: true }),+ ("s.dds".to_string(), DdsOptions { compression: DdsCompression::Bc2, mipmaps: false }),+ ];+ assert_eq!(writes.borrow().as_slice(), &want);+ let steps = &h.state().session.actions.list[0].steps;+ assert_eq!(+ steps,+ &[+ ("file.saveAs".into(), json!({"path": "t.dds", "ddsCompression": "bc1", "ddsMipmaps": false})),+ ("file.saveACopy".into(), json!({"path": "copy.dds", "ddsCompression": "none", "ddsMipmaps": true})),+ ("file.saveAs".into(), json!({"path": "s.dds", "ddsCompression": "bc2", "ddsMipmaps": false}))+ ]+ );+ writes.borrow_mut().clear();+ let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap();+ assert!(played.get("failed").is_none(), "{played}");+ assert!(h.state().dds_options.is_none(), "playback doesn't ask");+ assert_eq!(writes.borrow().as_slice(), &want);+}++/// File › Save confirming the document's own texture asks DDS Options, and an action being+/// recorded keeps it as a plain Save with the answer (scripted options too): played back, it+/// writes the texture the action is played on as recorded, without asking (#3531).+#[test]+fn recorded_plain_save_of_a_dds_texture_keeps_its_options() {+ let (mut h, writes) = dds_app("own.dds");+ let ctx = h.ctx.clone();+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "own.dds", "ddsCompression": "none"})).unwrap();+ assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("own.dds"));+ h.state_mut().run("actions.record", json!({})).unwrap();+ crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({})).unwrap();+ h.run_steps(3);+ assert!(h.state().dds_options.is_some(), "confirming its own texture asks DDS Options");+ h.get_by_label("BC1 / DXT1").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ h.state_mut().services.file_dialog = Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo("own.dds".into()))]).0);+ crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({"ddsCompression": "bc3", "ddsMipmaps": true})).unwrap();+ h.run_steps(3);+ assert!(h.state().dds_options.is_none(), "scripted options don't ask");+ h.state_mut().run("actions.stop", json!({})).unwrap();+ let bc1 = DdsOptions { compression: DdsCompression::Bc1, mipmaps: false };+ let bc3 = DdsOptions { compression: DdsCompression::Bc3, mipmaps: true };+ assert_eq!(&writes.borrow()[1..], &[("own.dds".to_string(), bc1), ("own.dds".to_string(), bc3)]);+ let steps = &h.state().session.actions.list[0].steps;+ assert_eq!(+ steps,+ &[+ ("file.save".into(), json!({"ddsCompression": "bc1", "ddsMipmaps": false})),+ ("file.save".into(), json!({"ddsCompression": "bc3", "ddsMipmaps": true}))+ ]+ );+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "other.dds", "ddsCompression": "none"})).unwrap();+ writes.borrow_mut().clear();+ let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap();+ assert!(played.get("failed").is_none(), "{played}");+ assert!(h.state().dds_options.is_none(), "playback doesn't ask");+ assert_eq!(writes.borrow().as_slice(), &[("other.dds".to_string(), bc1), ("other.dds".to_string(), bc3)]);+}++/// Enter on a focused Cancel cancels: egui clicks the focused button on Enter without consuming+/// the key, so the dialog's Enter-for-OK must not save as well.+#[test]+fn enter_on_a_focused_cancel_writes_nothing() {+ let (mut h, writes) = dds_app("unused.dds");+ h.state_mut().save_as(Some("t.dds".into())).unwrap();+ h.run_steps(2);+ h.get_by_label("Cancel").focus();+ h.run_steps(2);+ h.key_press(Key::Enter);+ h.run_steps(3);+ assert!(h.state().dds_options.is_none());+ assert!(writes.borrow().is_empty(), "nothing written");+ assert_eq!(h.state().ui.status, "Save cancelled");+}diff --git a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs b/crates/ui-egui/src/discard_ui/tests/targa_tests.rsindex 565fe0103..0a05370ec 100644--- a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs+++ b/crates/ui-egui/src/discard_ui/tests/targa_tests.rs@@ -201,3 +201,46 @@ fn closing_after_a_targa_save_waits_for_targa_options() {assert!(h.state().discard.is_none());assert!(h.state().session.documents().is_empty());}++/// File › Save confirming the document's own Targa asks Targa Options, and an action being+/// recorded keeps it as a plain Save with the bits chosen: played back, it writes the Targa the+/// action is played on with them, without asking (#3531).+#[test]+fn recorded_plain_save_of_a_targa_keeps_its_bits() {+ let (mut h, writes) = targa_app(false, "own.tga");+ let ctx = h.ctx.clone();+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "own.tga", "tgaBits": 24})).unwrap();+ h.state_mut().run("actions.record", json!({})).unwrap();+ crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({})).unwrap();+ h.run_steps(3);+ assert!(h.state().targa_options.is_some(), "confirming its own Targa asks Targa Options");+ h.get_by_label("32 bits/pixel").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ h.state_mut().run("actions.stop", json!({})).unwrap();+ let steps = &h.state().session.actions.list[0].steps;+ assert_eq!(steps, &[("file.save".into(), json!({"tgaBits": 32}))]);+ crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "other.tga", "tgaBits": 24})).unwrap();+ writes.borrow_mut().clear();+ let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap();+ assert!(played.get("failed").is_none(), "{played}");+ assert!(h.state().targa_options.is_none(), "playback doesn't ask");+ assert_eq!(writes.borrow().as_slice(), &[("other.tga".to_string(), asked(Some(32)))]);+}++/// Enter on a focused Cancel cancels: egui clicks the focused button on Enter without consuming+/// the key, so the dialog's Enter-for-OK must not save as well.+#[test]+fn enter_on_a_focused_cancel_writes_nothing() {+ let (mut h, writes) = targa_app(false, "unused.tga");+ h.state_mut().save_as(Some("t.tga".into())).unwrap();+ h.run_steps(2);+ h.get_by_label("Cancel").focus();+ h.run_steps(2);+ h.key_press(Key::Enter);+ h.run_steps(3);+ assert!(h.state().targa_options.is_none());+ assert!(writes.borrow().is_empty(), "nothing written");+ assert_eq!(h.state().ui.status, "Save cancelled");+}diff --git a/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs b/crates/ui-egui/src/discard_ui/tests/tiff_tests.rsindex f42de68ea..eb52dfb5a 100644--- a/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs+++ b/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs@@ -79,7 +79,7 @@ fn closing_after_tiff_save_waits_for_options_and_writes_the_requested_document()#[test]fn cancelling_failing_or_copying_a_tiff_keeps_the_original_unsaved() {- for outcome in ["cancel", "export error", "write error", "copy"] {+ for outcome in ["cancel", "enter on cancel", "export error", "write error", "copy"] {let (mut h, writes, saved, _) = tiff_prompt("file.close");h.key_press(Key::Y);h.run_steps(3);@@ -90,6 +90,11 @@ fn cancelling_failing_or_copying_a_tiff_keeps_the_original_unsaved() {h.get_by_label("Discard Layers and Save a Copy").click();h.run_steps(2);}+ // Enter on a focused Cancel is its click, not OK.+ "enter on cancel" => {+ h.get_by_label("Cancel").focus();+ h.run_steps(2);+ }_ => {}}h.key_press(if outcome == "cancel" { Key::Escape } else { Key::Enter });diff --git a/crates/ui-egui/src/disk_change_prompt.rs b/crates/ui-egui/src/disk_change_prompt.rsindex dd9b8215b..b65985cd4 100644--- a/crates/ui-egui/src/disk_change_prompt.rs+++ b/crates/ui-egui/src/disk_change_prompt.rs@@ -47,11 +47,11 @@ pub fn confirm(app: &mut PhotocraftApp, fields: &Map<String, Value>) -> Result<Vlet flat = fields.get("flat").and_then(Value::as_bool) == Some(true);app.with_document(doc, |app| {if flat {- let r = app.save_to(path.clone(), None)?;+ let r = app.save_to(path.clone(), crate::FormatChoices::default())?;app.journal_as_plain_save(&path);Ok(r)} else {- app.save_in_place(path)+ app.save_in_place(path, crate::FormatChoices::default())}})}diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex f6046fc20..6789b7513 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -3852,3 +3852,7 @@ navigator Zoom ZvětšeníUse PoužítIn Front VpředuBehind Vzadu++# DDS Options (#1327)+ DDS Options Možnosti DDS+ Generate Mipmaps Generovat mipmapydiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 0ad7366c4..3aa7e7212 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -3245,3 +3245,8 @@ curves Smooth GlättenIn Front DavorBehind DahinterBlend Mischen++# DDS Options (#1327)+ DDS Options DDS-Optionen+ Compression Komprimierung+ Generate Mipmaps Mipmaps erzeugendiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 83621629f..7b653fbbf 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3944,3 +3944,7 @@ curves Smooth ΕξομάλυνσηUse ΧρήσηIn Front ΜπροστάBehind Πίσω++# DDS Options (#1327)+ DDS Options Επιλογές DDS+ Generate Mipmaps Δημιουργία mipmapdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex e23b4e84c..eab6215df 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -4206,3 +4206,7 @@ navigator Zoom ZoomUse UsarIn Front DelanteBehind Detrás++# DDS Options (#1327)+ DDS Options Opciones de DDS+ Generate Mipmaps Generar mipmapsdiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 3bcca7037..80c7f110f 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -3252,3 +3252,8 @@ curves Smooth LisserUse UtiliserIn Front DevantBehind Derrière++# DDS Options (#1327)+ DDS Options Options DDS+ Compression Compression+ Generate Mipmaps Générer les mipmapsdiff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsvindex 4907e2da0..ca747637c 100644--- a/crates/ui-egui/src/i18n/hu.tsv+++ b/crates/ui-egui/src/i18n/hu.tsv@@ -4163,3 +4163,7 @@ cameraRaw Yellow SárgaUse HasználatIn Front ElölBehind Mögött++# DDS Options (#1327)+ DDS Options DDS-beállítások+ Generate Mipmaps Mipmapek létrehozásadiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex fc0d66afa..4fd06fd88 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -3239,3 +3239,8 @@ curves Smooth HaluskanUse GunakanIn Front Di DepanBehind Di Belakang++# DDS Options (#1327)+ DDS Options Opsi DDS+ Compression Kompresi+ Generate Mipmaps Buat mipmapdiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 609469635..1143b138f 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -4361,3 +4361,7 @@ shape Appearance AspettoUse UsaIn Front DavantiBehind Dietro++# DDS Options (#1327)+ DDS Options Opzioni DDS+ Generate Mipmaps Genera mipmapdiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 39a38a114..8564b9b30 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3921,3 +3921,8 @@ curves Smooth スムーズUse 使用In Front 前面Behind 背面++# DDS Options (#1327)+ DDS Options DDS オプション+ Compression 圧縮+ Generate Mipmaps ミップマップを生成diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 241c81bef..b99fde823 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -3426,3 +3426,8 @@ curves Smooth 매끄럽게In Front 앞Behind 뒤Blend 혼합++# DDS Options (#1327)+ DDS Options DDS 옵션+ Compression 압축+ Generate Mipmaps 밉맵 생성diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex e0dd17ff5..791d173cb 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -4004,3 +4004,7 @@ curves Smooth Vloeiend makenUse GebruikenIn Front VoorBehind Achter++# DDS Options (#1327)+ DDS Options DDS-opties+ Generate Mipmaps Mipmaps genererendiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 10435771f..23e253d62 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3843,3 +3843,8 @@ curves Smooth WygładźUse UżyjIn Front Z przoduBehind Z tyłu++# DDS Options (#1327)+ DDS Options Opcje DDS+ Compression Kompresja+ Generate Mipmaps Generuj mipmapydiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex f4dc857f7..327533ad8 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -4034,3 +4034,7 @@ layerLabel No Color Sem corUse UsarIn Front Na frenteBehind Atrás++# DDS Options (#1327)+ DDS Options Opções de DDS+ Generate Mipmaps Gerar mipmapsdiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex b497b4185..6b2e36845 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -3218,3 +3218,8 @@ curves Smooth СгладитьUse ИспользоватьIn Front СпередиBehind Сзади++# DDS Options (#1327)+ DDS Options Параметры DDS+ Compression Сжатие+ Generate Mipmaps Создать MIP-картыdiff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsvindex dc3608c51..5530f81ce 100644--- a/crates/ui-egui/src/i18n/sr.tsv+++ b/crates/ui-egui/src/i18n/sr.tsv@@ -4317,3 +4317,7 @@ shape Appearance IzgledUse KoristiIn Front IspredBehind Iza++# DDS Options (#1327)+ DDS Options DDS opcije+ Generate Mipmaps Generiši mipmapediff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsvindex 5e5326f9f..2e6f96a0e 100644--- a/crates/ui-egui/src/i18n/tr.tsv+++ b/crates/ui-egui/src/i18n/tr.tsv@@ -3974,3 +3974,7 @@ cameraData Lens LensUse KullanIn Front ÖndeBehind Arkada++# DDS Options (#1327)+ DDS Options DDS Seçenekleri+ Generate Mipmaps Mipmap oluşturdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex cc3df8834..5280372ca 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3952,3 +3952,8 @@ curves Smooth ЗгладитиUse ВикористатиIn Front СпередуBehind Ззаду++# DDS Options (#1327)+ DDS Options Параметри DDS+ Compression Стиснення+ Generate Mipmaps Створити MIP-картиdiff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsvindex d19e3d576..8f8e1c344 100644--- a/crates/ui-egui/src/i18n/vi.tsv+++ b/crates/ui-egui/src/i18n/vi.tsv@@ -3731,3 +3731,8 @@ curves Smooth Làm mượtUse DùngIn Front Phía trướcBehind Phía sau++# DDS Options (#1327)+ DDS Options Tùy chọn DDS+ Compression Nén+ Generate Mipmaps Tạo mipmapdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 675a54450..5efbe2899 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2868,3 +2868,8 @@ curves Smooth 平滑In Front 前面Behind 后面Blend 混合++# DDS Options (#1327)+ DDS Options DDS 选项+ Compression 压缩+ Generate Mipmaps 生成 Mipmapdiff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 982fa9731..ea0af7945 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2853,3 +2853,8 @@ curves Smooth 平滑In Front 前面Behind 後面Blend 混合++# DDS Options (#1327)+ DDS Options DDS 選項+ Compression 壓縮+ Generate Mipmaps 產生 Mipmapdiff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 89f293a2c..3e3b1d2e5 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -69,6 +69,7 @@ pub mod crop_shield;pub mod crop_size;pub mod crop_straighten;pub mod crop_ui;+pub mod dds_options_ui;pub mod delete_layer_prompt;pub mod dialog_alt_reset;pub mod dialog_blend_ui;@@ -272,6 +273,9 @@ pub struct ExportSettings {/// Targa: bits per pixel from Targa Options or Export As (`None`: 32 with an alpha channel or/// transparency, else 24).pub tga_bits: Option<photocraft_io::TgaBits>,+ /// DDS: the compression and mip chain from DDS Options (uncompressed without mipmaps unless+ /// chosen).+ pub dds: photocraft_io::DdsOptions,/// PSD/PSB: embed a thumbnail (Preferences › File Handling › Image Previews; see/// [`PhotocraftApp::save_settings`]).pub image_previews: bool,@@ -298,6 +302,7 @@ impl Default for ExportSettings {tiff_layers: true,xmp_all: true,tga_bits: None,+ dds: photocraft_io::DdsOptions::default(),image_previews: true,psd_maximize_compatibility: true,embed_icc: true,@@ -324,6 +329,7 @@ impl ExportSettings {opts.tiff_layers = self.tiff_layers;opts.xmp = if self.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };opts.tga_bits = self.tga_bits;+ opts.encode.dds = self.dds;opts.image_previews = self.image_previews;opts.psd_maximize_compatibility = self.psd_maximize_compatibility;opts.document_path = self.document_path.clone();@@ -331,6 +337,37 @@ impl ExportSettings {}}+/// The format answers a save takes instead of asking: the Targa bits per pixel and the DDS options+/// (`"tgaBits"`, `"ddsCompression"`, `"ddsMipmaps"`). `None` asks in Save As and takes the+/// default in automation saves, which never prompt.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct FormatChoices {+ pub tga_bits: Option<photocraft_io::TgaBits>,+ pub dds: Option<photocraft_io::DdsOptions>,+}++impl FormatChoices {+ /// The answers in command `cmd`'s params; a bad value is an error.+ pub fn from_params(params: &Value, cmd: &str) -> Result<Self, String> {+ Ok(FormatChoices { tga_bits: targa_options_ui::bits_param(params, cmd)?, dds: dds_options_ui::options_param(params, cmd)? })+ }++ /// The export settings with these answers applied.+ pub(crate) fn apply(self, settings: ExportSettings) -> ExportSettings {+ ExportSettings { tga_bits: self.tga_bits, dds: self.dds.unwrap_or(settings.dds), ..settings }+ }++ /// Adds the answers to a recorded save step.+ fn record(self, step: &mut Value) {+ if let Some(bits) = self.tga_bits {+ step["tgaBits"] = bits.bits().into();+ }+ if let Some(dds) = self.dds {+ dds_options_ui::record(dds, step);+ }+ }+}+/// The document's lone layer when it is a plain raster a flat file keeps: visible, at full/// opacity, in Normal mode, with no masks, effects or blending restrictions (#2234).pub(crate) fn plain_raster(doc: &Document) -> Option<&photocraft_doc::Layer> {@@ -840,6 +877,8 @@ pub struct PhotocraftApp {pub(crate) disk_stamps: HashMap<photocraft_doc::DocId, (String, FileStamp)>,/// A save to an RGB Targa parked behind the Targa Options prompt (see `targa_options_ui`).pub(crate) targa_options: Option<targa_options_ui::Prompt>,+ /// A save to a DDS texture parked behind the DDS Options prompt (see `dds_options_ui`).+ pub(crate) dds_options: Option<dds_options_ui::Prompt>,/// Files read but not opened yet: the first waits on its profile prompt, the rest behind it/// (see `open_prompt`).pub(crate) held_opens: std::collections::VecDeque<open_prompt::Held>,@@ -991,6 +1030,7 @@ impl PhotocraftApp {save_dirs: HashMap::new(),disk_stamps: HashMap::new(),targa_options: None,+ dds_options: None,held_opens: Default::default(),allow_close: false,stylus: Default::default(),@@ -1442,21 +1482,22 @@ impl PhotocraftApp {/// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export/// warnings are also shown to the user).pub fn save_as(&mut self, path: Option<String>) -> Result<Value, String> {- self.save_as_with(path, None)+ self.save_as_with(path, FormatChoices::default())}- /// [`Self::save_as`], writing a Targa with `tga_bits` per pixel when given (no Targa Options- /// prompt): `file.save` and `file.saveAs` with `tgaBits`.- pub fn save_as_with(&mut self, path: Option<String>, tga_bits: Option<photocraft_io::TgaBits>) -> Result<Value, String> {- self.save_dialog_flow(path, tga_bits, false)+ /// [`Self::save_as`], writing a Targa or DDS texture with the `choices` given instead of+ /// asking for them (no Targa or DDS Options prompt): `file.save` and `file.saveAs` with+ /// `tgaBits`, `ddsCompression` or `ddsMipmaps`.+ pub fn save_as_with(&mut self, path: Option<String>, choices: FormatChoices) -> Result<Value, String> {+ self.save_dialog_flow(path, choices, false)}/// [`Self::save_as_with`]. `plain_save` marks File › Save that had to ask for a file name/// (a flat file): confirming the document's own file is recorded as a `file.save` step,/// which writes whichever file the action is played on, not as a Save As to a fixed path.- pub(crate) fn save_dialog_flow(&mut self, path: Option<String>, tga_bits: Option<photocraft_io::TgaBits>, plain_save: bool) -> Result<Value, String> {+ pub(crate) fn save_dialog_flow(&mut self, path: Option<String>, choices: FormatChoices, plain_save: bool) -> Result<Value, String> {if self.save_options_open() {- return Err("Answer TIFF or Targa Options before starting another save".into());+ return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());}// Edit Contents documents save back into their smart object.if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") {@@ -1464,7 +1505,7 @@ impl PhotocraftApp {return Ok(serde_json::json!({"path": "smart object", "warnings": []}));}if let Some(path) = path {- return self.save_to(path, tga_bits);+ return self.save_to(path, choices);}let st = self.session.active().ok_or("no document")?;// PDN imports default to our native format, which preserves Paint.NET's blend modes;@@ -1504,7 +1545,7 @@ impl PhotocraftApp {{return r;}- let r = app.save_to(path.clone(), tga_bits)?;+ let r = app.save_to(path.clone(), choices)?;if plain_save && own.as_deref() == Some(path.as_str()) {app.journal_as_plain_save(&path);}@@ -1514,70 +1555,89 @@ impl PhotocraftApp {}/// [`Self::save_as_with`] once the path is known.- pub(crate) fn save_to(&mut self, path: String, tga_bits: Option<photocraft_io::TgaBits>) -> Result<Value, String> {- // An RGB Targa asks for its bits per pixel, unless the caller chose them; the save- // continues from the prompt (still a copy when it would be one without the prompt),- // which records the step once answered.- if tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) {+ pub(crate) fn save_to(&mut self, path: String, choices: FormatChoices) -> Result<Value, String> {+ // An RGB Targa asks for its bits per pixel, and a DDS texture for its compression, unless+ // the caller chose them; the save continues from the prompt (still a copy when it would+ // be one without the prompt), which records the step once answered.+ if choices.tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) {let copy = self.saves_copy(&path, None)?;targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?;return Ok(serde_json::json!({"path": path, "warnings": []}));}+ if choices.dds.is_none() && dds_options_ui::wants_prompt(&path) {+ let copy = self.saves_copy(&path, None)?;+ dds_options_ui::park(self, path.clone(), copy, "file.saveAs")?;+ return Ok(serde_json::json!({"path": path, "warnings": []}));+ }// A layered TIFF asks about its layers first (Preferences › File Handling); the save// continues from the prompt, which records the step once answered.if tiff_options_ui::wants_prompt(self, &path) {tiff_options_ui::park(self, path.clone())?;return Ok(serde_json::json!({"path": path, "warnings": []}));}- self.save_as_step(path, None, tga_bits)+ self.save_as_step(path, None, choices)}- /// File › Save back to the document's own layered file, recorded as a `file.save` step.- pub(crate) fn save_in_place(&mut self, path: String) -> Result<Value, String> {+ /// File › Save back to the document's own file, recorded as a `file.save` step with the+ /// Targa or DDS answer in `choices` (a replayed Save of a flat file brings its own).+ pub(crate) fn save_in_place(&mut self, path: String, choices: FormatChoices) -> Result<Value, String> {if self.save_options_open() {- return Err("Answer TIFF or Targa Options before starting another save".into());+ return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());}- let r = self.write_save(path, None, None)?;- self.session.journal.push(("file.save".into(), Value::Object(Default::default())));+ let r = self.write_save(path, None, choices)?;+ let mut step = Value::Object(Default::default());+ choices.record(&mut step);+ self.session.journal.push(("file.save".into(), step));Ok(r)}- /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF or- /// Targa answer), so an action being recorded keeps it (#2032).- fn save_as_step(&mut self, path: String, tiff_layers: Option<bool>, tga_bits: Option<photocraft_io::TgaBits>) -> Result<Value, String> {- let r = self.write_save(path.clone(), tiff_layers, tga_bits)?;+ /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF,+ /// Targa or DDS answer), so an action being recorded keeps it (#2032).+ fn save_as_step(&mut self, path: String, tiff_layers: Option<bool>, choices: FormatChoices) -> Result<Value, String> {+ let r = self.write_save(path.clone(), tiff_layers, choices)?;let mut step = serde_json::json!({"path": path});if let Some(layers) = tiff_layers {step["tiffLayers"] = layers.into();}- if let Some(bits) = tga_bits {- step["tgaBits"] = bits.bits().into();- }+ choices.record(&mut step);self.session.journal.push(("file.saveAs".into(), step));Ok(r)}- /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]).+ /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]),+ /// keeping its Targa or DDS answer so playback writes the file the same way. A save parked+ /// behind Targa or DDS Options hasn't been journaled yet: it is recorded as File › Save once+ /// answered.pub(crate) fn journal_as_plain_save(&mut self, path: &str) {+ let parked = [self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)), self.dds_options.as_mut().map(|p| (&p.path, &mut p.record))];+ if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") {+ *record = "file.save";+ return;+ }if let Some(last) = self.session.journal.last_mut()&& last.0 == "file.saveAs"&& last.1.get("path").and_then(Value::as_str) == Some(path)- && last.1.as_object().is_some_and(|o| o.len() == 1)+ && let Some(step) = last.1.as_object()+ && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps")){- *last = ("file.save".into(), Value::Object(Default::default()));+ let mut step = step.clone();+ step.remove("path");+ *last = ("file.save".into(), Value::Object(step));}}/// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` step: no dialog or prompt, and the- /// recorded TIFF or Targa answer (if any) stands in for the TIFF or Targa Options prompt.+ /// recorded TIFF, Targa or DDS answer (if any) stands in for the TIFF, Targa or DDS Options prompt.pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result<Value, String> {if self.save_options_open() {- return Err("Answer TIFF or Targa Options before starting another save".into());+ return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());}if id == "file.save" {// The file the action is played on: one that holds the whole document, or a flat// file a recorded Save confirmed in the dialog while the document is still a plain- // raster, so it is never flattened over (#3531, #3806).+ // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa+ // or DDS answer stands in for the prompt.+ let choices = FormatChoices::from_params(params, id)?;let st = self.session.active().ok_or("no document")?;let flat_own = |p: &str| {!photocraft_engine::file_cmds::saves_in_place(p)@@ -1587,16 +1647,16 @@ impl PhotocraftApp {let path = st.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p) || flat_own(p)).ok_or("Save writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file (OpenRaster only when it holds everything), or to its own flat file while the document is a single plain layer",)?;- return self.save_in_place(path);+ return self.save_in_place(path, choices);}let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?;- let tga_bits = targa_options_ui::bits_param(params, id)?;+ let choices = FormatChoices::from_params(params, id)?;if id == "file.saveACopy" {// A copy: the document keeps its own file and unsaved state, as when recorded (#4373).let doc = self.session.active().ok_or("no document")?.doc.clone();- return crate::view_cmds::write_copy(self, &doc, path, tga_bits);+ return crate::view_cmds::write_copy(self, &doc, path, choices);}- self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), tga_bits)+ self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), choices)}/// What a save writes by default under the preferences: File Handling › Image Previews@@ -1636,11 +1696,11 @@ impl PhotocraftApp {}/// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer:- /// `Some(false)` discards the layers and saves a copy. `tga_bits` is the Targa bits per- /// pixel (`None`: 32 with an alpha channel or transparency, else 24).- fn write_save(&mut self, path: String, tiff_layers: Option<bool>, tga_bits: Option<photocraft_io::TgaBits>) -> Result<Value, String> {+ /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per+ /// pixel (`None`: 32 with an alpha channel or transparency, else 24) and the DDS options.+ fn write_save(&mut self, path: String, tiff_layers: Option<bool>, choices: FormatChoices) -> Result<Value, String> {let copy = self.saves_copy(&path, tiff_layers)?;- let settings = ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), tga_bits, ..self.save_settings() };+ let settings = choices.apply(ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..self.save_settings() });match self.write_document(path.clone(), &settings, copy)? {Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})),None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})),@@ -1746,9 +1806,9 @@ impl PhotocraftApp {own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then)}- /// TIFF Options or Targa Options is waiting on an answer before a save is written.+ /// TIFF, Targa or DDS Options is waiting on an answer before a save is written.pub(crate) fn save_options_open(&self) -> bool {- self.tiff_options.is_some() || self.targa_options.is_some()+ self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some()}/// A print worker may still be handing a job to the system queue.@@ -1765,12 +1825,13 @@ impl PhotocraftApp {/// picker or ambient writer is reachable from this path. Returns the path/// written and the export warnings (also shown to the user).pub fn save_automation(&mut self, path: Option<String>) -> Result<Value, String> {- self.save_automation_with(path, None)+ self.save_automation_with(path, FormatChoices::default())}- /// [`Self::save_automation`] writing a Targa with `tga_bits` per pixel (`None`: 32 with an- /// alpha channel or transparency, else 24). Automation saves never prompt.- pub fn save_automation_with(&mut self, path: Option<String>, tga_bits: Option<photocraft_io::TgaBits>) -> Result<Value, String> {+ /// [`Self::save_automation`] writing a Targa or DDS texture with the `choices` given (a+ /// Targa's `None`: 32 with an alpha channel or transparency, else 24; a DDS texture's:+ /// uncompressed without mipmaps). Automation saves never prompt.+ pub fn save_automation_with(&mut self, path: Option<String>, choices: FormatChoices) -> Result<Value, String> {let target = {let state = self.session.active().ok_or("no document")?;// As File › Save: without `path` only a layered file is written back (#416).@@ -1783,7 +1844,7 @@ impl PhotocraftApp {if self.background_jobs&& let Some(save) = self.services.automation_save.clone(){- return match jobs_ui::start_save(self, target.clone(), ExportSettings { tga_bits, ..self.save_settings() }, false, save, true)? {+ return match jobs_ui::start_save(self, target.clone(), choices.apply(self.save_settings()), false, save, true)? {Some((path, warnings)) => Ok(reply(&path, &warnings)),None => {let job = self.jobs.last_started;@@ -1793,7 +1854,7 @@ impl PhotocraftApp {}let state = self.session.active().ok_or("no document")?;let (doc, revision) = (state.doc.id, state.revision);- let settings = ExportSettings { tga_bits, ..self.save_settings() };+ let settings = choices.apply(self.save_settings());let export = self.services.export.as_ref().ok_or("no exporter configured")?;let (bytes, warnings) = export(&state.doc, &target, &settings)?;let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?;@@ -2093,6 +2154,7 @@ impl eframe::App for PhotocraftApp {discard_ui::show(self, &ctx);tiff_options_ui::show(self, &ctx);targa_options_ui::show(self, &ctx);+ dds_options_ui::show(self, &ctx);distort_ui::show(self, &ctx);camera_raw_ui::show(self, &ctx);wide_angle_ui::show(self, &ctx);diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex ea9437968..79632791d 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -231,16 +231,17 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:"file.save" => {// Writes back only to a layered file that holds the whole document; anything else// goes through Save As, so the original is never overwritten with less (#3806).- let tga_bits = crate::targa_options_ui::bits_param(¶ms, id)?;+ let choices = crate::FormatChoices::from_params(¶ms, id)?;match params.get("path").and_then(Value::as_str) {- Some(path) => app.save_as_with(Some(path.to_string()), tga_bits),+ Some(path) => app.save_as_with(Some(path.to_string()), choices),None => {let own = app.session.active().and_then(|d| d.path.clone().map(|p| (photocraft_engine::file_cmds::holds_at(&d.doc, &p), p, d)));match own {Some((true, path, d)) => {// Another app changed the file since it was opened or saved: ask first (#6596).let doc = d.doc.id;- crate::disk_change_prompt::intercept(app, doc, &path, false).unwrap_or_else(|| app.save_in_place(path))+ crate::disk_change_prompt::intercept(app, doc, &path, false)+ .unwrap_or_else(|| app.save_in_place(path, crate::FormatChoices::default()))}Some((false, path, d)) if photocraft_engine::file_cmds::saves_in_place(&path) => {// Its own file is layered but can't hold what the document has now.@@ -250,11 +251,11 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:let mut lines = losses;lines.push(tl!("Choose a format that keeps it, such as Photoshop (PSD), or save a copy.").to_string());crate::notices::post(app, title, lines, false, None);- app.save_as_with(None, tga_bits)+ app.save_as_with(None, choices)}// A flat file asks for its name; confirming its own file records a// plain Save that writes the file an action is played on (#3531).- _ => app.save_dialog_flow(None, tga_bits, true),+ _ => app.save_dialog_flow(None, choices, true),}}}@@ -288,8 +289,8 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:}}"file.saveAs" => {- let tga_bits = crate::targa_options_ui::bits_param(¶ms, id)?;- app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), tga_bits)+ let choices = crate::FormatChoices::from_params(¶ms, id)?;+ app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), choices)}"view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => app.run(id, params),"window.newWindowForDocument" => {diff --git a/crates/ui-egui/src/targa_options_ui.rs b/crates/ui-egui/src/targa_options_ui.rsindex c2161a0c9..5a8b47d58 100644--- a/crates/ui-egui/src/targa_options_ui.rs+++ b/crates/ui-egui/src/targa_options_ui.rs@@ -21,8 +21,9 @@ pub struct Prompt {/// Save a Copy: the document keeps its path and unsaved changes.pub copy: bool,/// The step the answered save is recorded as, so an action being recorded keeps it:- /// `file.saveAs` for Save As (#2032, even when a flat Targa is written as a copy) and- /// `file.saveACopy` for Save a Copy (#4373).+ /// `file.saveAs` for Save As (#2032, even when a flat Targa is written as a copy),+ /// `file.saveACopy` for Save a Copy (#4373), and `file.save` when File › Save confirmed the+ /// document's own Targa (#3531), which plays back on the file the action is played on.pub record: &'static str,}@@ -46,7 +47,7 @@ pub fn bits_param(params: &serde_json::Value, cmd: &str) -> Result<Option<TgaBit/// A prompt already waiting is never replaced (a shortcut can still reach Save a Copy).pub fn park(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str) -> Result<(), String> {if app.save_options_open() {- return Err("Answer TIFF or Targa Options before starting another save".into());+ return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());}let doc = app.active_doc_id()?;let bits = app.session.active().map_or(TgaBits::Bits24, |st| photocraft_io::tga_default_bits(&st.doc));@@ -76,10 +77,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {});cancel |= modal.should_close();p.bits = bits;- if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {+ // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels.+ if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) {let Some(p) = app.targa_options.take() else { return };let settings = ExportSettings { tga_bits: Some(p.bits), ..app.save_settings() };- let step = serde_json::json!({"path": p.path, "tgaBits": p.bits.bits()});+ let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) };+ step["tgaBits"] = p.bits.bits().into();let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy));if written.is_ok() {// An action being recorded keeps the Save As or Save a Copy with this answer (#2032).diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rsindex febd5964c..eed78830a 100644--- a/crates/ui-egui/src/tiff_options_ui.rs+++ b/crates/ui-egui/src/tiff_options_ui.rs@@ -65,7 +65,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {cancel |= modal.should_close();p.discard_layers = discard;p.dont_ask_again = dont_ask;- if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {+ // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels.+ if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) {let Some(p) = app.tiff_options.take() else { return };if p.dont_ask_again {app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false);diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rsindex 1da1f918d..ae19bfa6a 100644--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@ -1442,32 +1442,32 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {let suggested = format!("{stem} copy.psd");// The copy is of the document as it was when asked.app.pick_save(&suggested, move |app, path| {- // An RGB Targa asks for its bits per pixel first; the copy is written from the prompt.+ // An RGB Targa asks for its bits per pixel first, and a DDS texture for its compression;+ // the copy is written from the prompt.let parked = app.with_document(doc.id, |app| {- let ask = crate::targa_options_ui::wants_prompt(app, &path);- if ask {+ if crate::targa_options_ui::wants_prompt(app, &path) {crate::targa_options_ui::park(app, path.clone(), true, "file.saveACopy")?;+ return Ok(true);}- Ok(ask)+ if crate::dds_options_ui::wants_prompt(&path) {+ crate::dds_options_ui::park(app, path.clone(), true, "file.saveACopy")?;+ return Ok(true);+ }+ Ok(false)})?;if parked {return Ok(json!({"path": path, "warnings": []}));}- let r = write_copy(app, &doc, &path, None)?;+ let r = write_copy(app, &doc, &path, crate::FormatChoices::default())?;app.session.journal.push(("file.saveACopy".into(), json!({"path": path})));Ok(r)})}/// Writes `doc` to `path` as a copy (Save a Copy, and its replayed action step): the document's-/// path and saved state are untouched. `tga_bits` is the Targa answer, when there is one.-pub(crate) fn write_copy(- app: &mut PhotocraftApp,- doc: &photocraft_doc::Document,- path: &str,- tga_bits: Option<photocraft_io::TgaBits>,-) -> Result<Value, String> {- let settings = crate::ExportSettings { tga_bits, ..app.save_settings() };+/// path and saved state are untouched. `choices` are the Targa and DDS answers, when there are any.+pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, path: &str, choices: crate::FormatChoices) -> Result<Value, String> {+ let settings = choices.apply(app.save_settings());let export = app.services.export.as_ref().ok_or("no exporter configured")?;let (bytes, warnings) = export(doc, path, &settings)?;let write = app.services.write.as_mut().ok_or("no writer configured")?;diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 78f44b07d..918a9f811 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -88,7 +88,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are ibase64 PNG data; a path is relative to the automation write root. Raises the window first(default) because occluded macOS windows stop rendering- `ui.focus`: bring the main window to the front-- `app.open {path}` / `app.save {path?, tgaBits?}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. Automation saves never show TGA or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))+- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))- `app.quit`## Engine commands@@ -321,7 +321,7 @@ How each MCP tool maps onto control methods in bridge mode:| `doc_export_layers {dir, …}` | `engine.execute {command: "file.export.layersToFiles", params}` || `doc_export_data_sets {dir, …}` | `engine.execute {command: "file.export.dataSetsAsFiles", params}` || `doc_import_data_sets {path, …}` | `engine.execute {command: "file.import.variableDataSets", params}` |-| `doc_save {path?, tgaBits?}` / `doc_export {path, tgaBits?}` | `app.save {path?, tgaBits?}` |+| `doc_save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}` / `doc_export {path, tgaBits?, ddsCompression?, ddsMipmaps?}` | `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}` || `doc_render_preview {max_side?}` | `ui.screenshot`, returned directly as PNG image content || `session_list`, `ui_inspect` | `ui.inspect` || `ui_screenshot {max_side?}` | `ui.screenshot`, returned as PNG image content |@@ -378,7 +378,7 @@ no MCP framing, no app start-up per command. Configure its file access with the| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, count}`: one file per exported layer, named like `file.export.layersToFiles` names them. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file || `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command || `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root |-| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |+| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty || `doc.inspect` | `{index?}`: same JSON as `document.inspect` || `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` || `doc.select` / `doc.close` | `{index}` / `{index?}` |diff --git a/docs/file-format-parity.md b/docs/file-format-parity.mdindex 9b878583a..938a723b6 100644--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@ -1,6 +1,6 @@# File-format parity-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (PNG `sTER` stereo pairing kept on save, #6063; earlier: PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); earlier: PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity andtests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write@@ -90,7 +90,7 @@ D5100 colour profile. Counts and the G14 estimate are unchanged.| Paint.NET `.pdn` | yes | no | [pdn.md](pdn.md) || OpenRaster `.ora` | yes | yes | [ora.md](ora.md) || ICO, QOI | yes | yes | |-| DirectDraw Surface `.dds` | yes | no | Top mip level of a 2D texture: uncompressed RGB, RGBA or luminance, BC1–BC3 (DXT1/3/5), legacy or DX10 header. Cubemaps, arrays, volumes and BC4–BC7 are refused (#1327). Photoshop needs a plug-in |+| DirectDraw Surface `.dds` | yes | yes | Opens the top mip level of a 2D texture: uncompressed RGB, RGBA or luminance, BC1–BC3 (DXT1/3/5), legacy or DX10 header. Saves a 2D texture uncompressed (BGRA, BGRX, luminance with or without alpha) or BC1–BC3 with the legacy header, optionally with its full mip chain (box filter); Save As and Save a Copy ask (DDS Options), scripts pass `ddsCompression` and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Cubemaps, arrays, volumes and BC4–BC7 are refused (#1327). Photoshop needs a plug-in || Krita `.kra`, GIMP `.xcf`, Procreate | no | no | Not in Photoshop either |### Affinity import notes (moved from `roadmap.md`)@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.| Date | Change | Summary ||---|---|---|+| 2026-10-15 | minor | DDS textures save (#1327): uncompressed or BC1/BC2/BC3 (DXT1/3/5) from a clean-room block encoder, optional box-filtered mip chain, legacy header; DDS Options in Save As and Save a Copy, `ddsCompression`/`ddsMipmaps` for scripts, the CLI and MCP || 2026-10-15 | minor | PNG: a stereo PNG's `sTER` pairing (PNG Extensions 1.4.0 §3.6) is read on open and written back on save, so the file still says it is a stereo pair (#6063) || 2026-10-15 | minor | PSD guides: image resource 1092 (guides v2) gives guides their own colours on import; 1092 and 1097 (guide GUIDs) are written back only while they still describe the document's guides, so an edit no longer leaves Photoshop a stale second guide list (#5966) || 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 |