diff --git a/.coderabbit.yaml b/.coderabbit.yaml
new file mode 100644
index 0000000000..2408084cf9
--- /dev/null
+++ b/.coderabbit.yaml
@@ -0,0 +1,6 @@
+# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
+reviews:
+ auto_review:
+ # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
+ ignore_usernames:
+ - "dependabot[bot]"
diff --git a/Cargo.lock b/Cargo.lock
index aff38ac01b..6b5a7bbf9b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4630,7 +4630,7 @@ dependencies = [
[[package]]
name = "photocraft"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"arboard",
"async-io",
@@ -4675,7 +4675,7 @@ dependencies = [
[[package]]
name = "photocraft-affinity"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"crc32fast",
"flate2",
@@ -4685,7 +4685,7 @@ dependencies = [
[[package]]
name = "photocraft-algo"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4698,7 +4698,7 @@ dependencies = [
[[package]]
name = "photocraft-automation"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -4721,7 +4721,7 @@ dependencies = [
[[package]]
name = "photocraft-cli"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-automation",
"photocraft-codecs",
@@ -4735,7 +4735,7 @@ dependencies = [
[[package]]
name = "photocraft-cms"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"moxcms",
"rayon",
@@ -4743,7 +4743,7 @@ dependencies = [
[[package]]
name = "photocraft-codecs"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"exr",
"flate2",
@@ -4764,7 +4764,7 @@ dependencies = [
[[package]]
name = "photocraft-color"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-cms",
"serde",
@@ -4772,7 +4772,7 @@ dependencies = [
[[package]]
name = "photocraft-compose"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"criterion",
"photocraft-color",
@@ -4787,7 +4787,7 @@ dependencies = [
[[package]]
name = "photocraft-doc"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4798,7 +4798,7 @@ dependencies = [
[[package]]
name = "photocraft-engine"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"blake3",
"craft-print",
@@ -4835,7 +4835,7 @@ dependencies = [
[[package]]
name = "photocraft-format"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"blake3",
"crc32fast",
@@ -4858,14 +4858,14 @@ dependencies = [
[[package]]
name = "photocraft-geom"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"serde",
]
[[package]]
name = "photocraft-gpu"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"half",
"log",
@@ -4882,14 +4882,14 @@ dependencies = [
[[package]]
name = "photocraft-heif"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"heic-rs",
]
[[package]]
name = "photocraft-io"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"blake3",
"craft-docpath",
@@ -4919,18 +4919,18 @@ dependencies = [
[[package]]
name = "photocraft-ipp"
-version = "0.10.0"
+version = "0.11.1"
[[package]]
name = "photocraft-ops"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-doc",
]
[[package]]
name = "photocraft-paint"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4941,7 +4941,7 @@ dependencies = [
[[package]]
name = "photocraft-plugins"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4956,7 +4956,7 @@ dependencies = [
[[package]]
name = "photocraft-psd"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"flate2",
"photocraft-psd",
@@ -4967,17 +4967,18 @@ dependencies = [
[[package]]
name = "photocraft-raster"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-color",
"photocraft-geom",
"proptest",
+ "rayon",
"serde",
]
[[package]]
name = "photocraft-raw"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"flate2",
"image",
@@ -4992,7 +4993,7 @@ dependencies = [
[[package]]
name = "photocraft-tablet"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"block2 0.6.2",
"objc2 0.6.4",
@@ -5004,7 +5005,7 @@ dependencies = [
[[package]]
name = "photocraft-testkit"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"memory-stats",
"photocraft-color",
@@ -5015,7 +5016,7 @@ dependencies = [
[[package]]
name = "photocraft-text"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"flate2",
"parley",
@@ -5024,12 +5025,13 @@ dependencies = [
"photocraft-geom",
"photocraft-psd",
"photocraft-raster",
+ "rayon",
"skrifa",
]
[[package]]
name = "photocraft-ui-egui"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"base64 0.22.1",
"craft-print",
@@ -5071,7 +5073,7 @@ dependencies = [
[[package]]
name = "photocraft-vector"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"photocraft-color",
"photocraft-doc",
@@ -5082,7 +5084,7 @@ dependencies = [
[[package]]
name = "photocraft-web"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"eframe",
"egui",
@@ -5104,7 +5106,7 @@ dependencies = [
[[package]]
name = "photocraft-web-boot"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"flate2",
"js-sys",
@@ -8691,7 +8693,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xtask"
-version = "0.10.0"
+version = "0.11.1"
dependencies = [
"serde",
"serde_json",
diff --git a/Cargo.toml b/Cargo.toml
index 3f8dbb0a72..b3f49802e3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
[workspace.package]
-version = "0.10.0"
+version = "0.11.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
diff --git a/README.md b/README.md
index 12e2ef4b12..7554fcd8f2 100644
--- a/README.md
+++ b/README.md
@@ -20,6 +20,9 @@
+
+
+
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index e79e63a701..4d3e67858d 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -15,22 +15,24 @@ pub const USAGE: &str = "\
photocraft-cli: headless PhotoCraft
USAGE:
- photocraft-cli convert [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--jpeg-format ]
+ photocraft-cli convert [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] [--jpeg-format ]
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) as
its 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.
--jpeg-format picks a JPEG's scans, as JPEG Options does: baseline (the default), optimized
(Huffman tables fitted to the image; RGB is written 4:2:0 and keeps the standard tables, so
only Gray and CMYK shrink) or progressive.
photocraft-cli info [--compact]
Print the document as JSON (size, mode, depth, layer tree).
- photocraft-cli run ( | --new ) --cmd [--params ] [--cmd …] [--out ] [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--jpeg-format ]
+ photocraft-cli run ( | --new ) --cmd [--params ] [--cmd …] [--out ] [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] [--jpeg-format ]
Open a file, run engine commands in order, save the result. Each --params
applies to the preceding --cmd. Prints each command's JSON result.
- photocraft-cli batch --actions [--action ] --in --out [--format ] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--jpeg-format ]
+ photocraft-cli batch --actions [--action ] --in --out [--format ] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] [--jpeg-format ]
Apply an action list to every image in a directory. A Photoshop Actions file (.atn) is a
set: 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
@@ -72,18 +74,23 @@ struct Subcommand {
}
const SUBCOMMANDS: &[Subcommand] = &[
- Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits", "--dpx-bits", "--jpeg-format"], bare: &["--tiff-layers"], run: convert },
+ Subcommand {
+ name: "convert",
+ values: &["--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression", "--jpeg-format"],
+ 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", "--jpeg-format"],
- bare: &["--tiff-layers"],
+ values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression", "--jpeg-format"],
+ bare: &["--tiff-layers", "--dds-mipmaps"],
run: run_cmds,
},
Subcommand {
name: "batch",
- values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--jpeg-format"],
- bare: &["--in-place", "--tiff-layers"],
+ values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression", "--jpeg-format"],
+ bare: &["--in-place", "--tiff-layers", "--dds-mipmaps"],
run: batch,
},
Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet },
@@ -226,6 +233,11 @@ fn export_opts(a: &Args) -> Result {
o.encode.jpeg_format =
photocraft_codecs::JpegFormat::parse(f).ok_or_else(|| format!("bad --jpeg-format `{f}`: expected baseline, optimized or progressive"))?;
}
+ 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.rs
index 7553702381..23d242729c 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.rs
index fcacf81b26..437f5cee12 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.md
index 4411a0b45f..8733da8b2e 100644
--- a/book/src/formats/raster-formats.md
+++ b/book/src/formats/raster-formats.md
@@ -20,6 +20,7 @@ Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_
- 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.
- JPEG, as Photoshop's JPEG Options: Save As and Save a Copy ask for the Quality on Photoshop's 0–12 scale (with its Low, Medium, High and Maximum presets) and a Format Option: Baseline ("Standard"), Baseline Optimized (Huffman tables fitted to the image) or Progressive. The quality starts at the opened JPEG's own quality, else at the Export preference's JPEG quality; left there, an opened JPEG is written at exactly its own quality. Scripts pass `"quality": 0..12` and `"jpegFormat": "baseline" | "optimized" | "progressive"` (on the CLI, `--quality` on the encoder's 1–100 scale and `--jpeg-format`) and aren't asked; recorded actions replay the answer. The scale maps onto the encoder's 1–100 as `round(q / 12 × 99 + 1)`. RGB JPEGs are written 4:2:0, where Baseline Optimized keeps the standard tables for now (Gray and CMYK, written 4:4:4, get fitted ones). Matte and the file-size preview aren't offered.
+- 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 through
the document's CMYK ICC profile (relative colorimetric with black point compensation) and embed
diff --git a/contributors/people.toml b/contributors/people.toml
index bc3533777b..99d81059e9 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 = true
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index 15a0e24e30..3db25c4fdd 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.rs
index f52376a9c5..567d0b4837 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,
+ /// DDS: "none" (uncompressed, the default), "bc1" (DXT1: alpha on or off), "bc2" (DXT3) or
+ /// "bc3" (DXT5).
+ #[serde(default, rename = "ddsCompression")]
+ pub dds_compression: Option,
+ /// 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,
}
@@ -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/src/workspace.rs b/crates/automation/src/workspace.rs
index 77f728ce04..99dedac77d 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -591,7 +591,7 @@ mod tests {
/// #7095: replacing a file through the automation path keeps the old file's extended
/// attributes, the same as a save through `atomic_write` does.
- #[cfg(unix)]
+ #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
#[test]
fn write_keeps_the_replaced_files_extended_attributes() {
#[cfg(target_os = "macos")]
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index 7386f3d58c..5a9fa7c56e 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.md
index 46baf50f82..539365c95b 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 are
ignored. 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.rs
index efe93c7f2e..d35c7d1092 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::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 {
+ 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 {
+ 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 {
+ 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, 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::(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, 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::(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.rs
new file mode 100644
index 0000000000..bbd55b4bf3
--- /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::() / 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::().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::();
+ 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- | 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::();
+ 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.rs
index 32e68b336a..d9905ab978 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.rs
index 594735edb4..a6937b571c 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: &EncodeOption
if 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
// Compression
if 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.rs
index fa2e1e6cb3..24611bd90d 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.rs
index a6f25007b7..6a52c5585e 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, JpegFormat, Limits, PngCompression, PngStereo, TiffCompression};
+pub use crate::options::{
+ DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, 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 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.rs
index 046a27466f..258779d823 100644
--- a/crates/codecs/src/options.rs
+++ b/crates/codecs/src/options.rs
@@ -213,6 +213,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 {
+ 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 {
@@ -240,6 +295,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,
+ /// 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.
@@ -261,6 +318,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.rs
index 766555f6e5..ebf4042f48 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.rs
new file mode 100644
index 0000000000..3225dd14d6
--- /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::>();
+ let (a, b) = (rgb(a), rgb(b));
+ let mse = a.iter().zip(&b).map(|(x, y)| (x - y).powi(2)).sum::() / 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::();
+ 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 = (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 =
+ (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::() + 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.rs
index ce0ef7ae8f..9ba9423509 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/compose/src/effects.rs b/crates/compose/src/effects.rs
index 20657a2535..cbdf7f35a2 100644
--- a/crates/compose/src/effects.rs
+++ b/crates/compose/src/effects.rs
@@ -1528,13 +1528,16 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern
tent(&mut h, g.width);
h
} else {
- let sharp = sharp_edges(shape);
- let (din, dout) = (bevel_dist_inside(shape, &sharp, size), bevel_dist_outside(shape, &sharp, size));
- let mut h = Map::new(shape.w, shape.h, 0.0);
+ let [din, dout] = bevel_dists(shape, size);
let soft = g.chisel_soft > 0.0;
- for i in 0..h.v.len() {
- h.v[i] = bevel_chisel_h(g.paint, size, din[i], dout[i], soft);
- }
+ let w = shape.w;
+ let v = par_fill(w, shape.h, 0.0, |y, row| {
+ for (x, o) in row.iter_mut().enumerate() {
+ let i = y * w + x;
+ *o = bevel_chisel_h(g.paint, size, din[i], dout[i], soft);
+ }
+ });
+ let mut h = Map { w, h: shape.h, v };
// Inner and outer Chisel Soft are not blurred in Photoshop (their facets equal Chisel
// Hard's across a straight edge); emboss styles keep the blur until measured.
if soft && g.paint == BevelPaint::Both {
@@ -1555,14 +1558,23 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern
let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0);
let k = t.depth / unit;
let (x0, y0) = (tex.rect.x0, tex.rect.y0);
- for y in 0..h.h {
- for x in 0..h.w {
- let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5);
- let p = tile.sample(u, v);
- let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3];
- h.v[y * h.w + x] += k * if t.invert { 1.0 - l } else { l };
- }
- }
+ let w = h.w;
+ par_units(
+ h.v.len(),
+ &mut h.v,
+ w,
+ &mut [] as &mut [()],
+ 0,
+ || (),
+ |_, y, row, _| {
+ for (x, o) in row.iter_mut().enumerate() {
+ let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5);
+ let p = tile.sample(u, v);
+ let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3];
+ *o += k * if t.invert { 1.0 - l } else { l };
+ }
+ },
+ );
}
if b.soften >= 1.0 {
tent(&mut h, b.soften);
@@ -1644,23 +1656,33 @@ fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, pat
};
let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) {
let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0));
- for y in 0..shape.h as i64 {
- for x in 0..shape.w as i64 {
- let i = y as usize * shape.w + x as usize;
- let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth;
- let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth;
- let n = [-gx, -gy, 1.0];
- let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt();
- let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len;
- let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) };
- let k = shade - se;
- if k > 0.0 {
- hi.v[i] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region;
- } else {
- sh.v[i] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region;
+ // Rows on threads: every pixel reads only `hmap` and `shape`.
+ par_units(
+ hi.v.len(),
+ &mut hi.v,
+ shape.w,
+ &mut sh.v,
+ shape.w,
+ || (),
+ |_, y, hi_row, sh_row| {
+ let y = y as i64;
+ for x in 0..shape.w as i64 {
+ let i = y as usize * shape.w + x as usize;
+ let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth;
+ let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth;
+ let n = [-gx, -gy, 1.0];
+ let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt();
+ let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len;
+ let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) };
+ let k = shade - se;
+ if k > 0.0 {
+ hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region;
+ } else {
+ sh_row[x as usize] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region;
+ }
}
- }
- }
+ },
+ );
(apply_contour(hi, &b.gloss_contour), apply_contour(sh, &b.gloss_contour))
};
let maps = match g.paint {
@@ -1676,7 +1698,13 @@ fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, pat
let (hi, sh) = shade_into(g.depth, 0);
let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, 1);
let mix = |a: Map, b: Map| -> Map {
- let v = a.v.iter().zip(&b.v).zip(&shape.v).map(|((x, y), s)| if *s > INSIDE_EPS { *x } else { 0.0 } + y * (1.0 - s.min(1.0))).collect();
+ let v = par_fill(a.w, a.h, 0.0, |y, row| {
+ for (x, o) in row.iter_mut().enumerate() {
+ let i = y * a.w + x;
+ let (x, y, s) = (a.v[i], b.v[i], shape.v[i]);
+ *o = if s > INSIDE_EPS { x } else { 0.0 } + y * (1.0 - s.min(1.0));
+ }
+ });
Map { w: a.w, h: a.h, v }
};
vec![mix(hi, ho), mix(sh, so)]
@@ -2309,6 +2337,18 @@ pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reac
}
}
+/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its
+/// [`distance_field`], with the sharp edges they both start from found once.
+pub fn bevel_distance_fields(alpha: Vec, w: usize, h: usize, reach: f32) -> [Vec; 2] {
+ bevel_dists(&Map { w, h, v: alpha }, reach)
+}
+
+/// The inside and outside bevel distances of `s`, from one set of sharp edges.
+fn bevel_dists(s: &Map, reach: f32) -> [Vec; 2] {
+ let sharp = sharp_edges(s);
+ [bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)]
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -2951,6 +2991,55 @@ mod tests {
}
}
+ #[test]
+ fn bevel_maps_do_not_depend_on_the_threads() {
+ // Every style and technique, softened or not, and a texture; one thread (in order) is the reference.
+ let mut patchy = aa_disc(101, 101, 40.0);
+ for (i, v) in patchy.v.iter_mut().enumerate() {
+ if (i % 101 / 13 + i / 101 / 17) % 5 == 0 {
+ *v *= 0.6;
+ }
+ }
+ let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy];
+ let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
+ sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]);
+ sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]);
+ let pats = [Pattern::new("stripes", sf, 4, 4)];
+ let light = GlobalLight::default();
+ let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss];
+ for (k, shape) in shapes.iter().enumerate() {
+ let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) };
+ for style in styles {
+ for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] {
+ for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] {
+ let mut b = bevel_of(style, technique);
+ (b.size, b.soften) = (size, soften);
+ if textured {
+ b.texture = Some(photocraft_doc::BevelTexture {
+ name: "stripes".into(),
+ id: String::new(),
+ scale: 1.0,
+ depth: 1.0,
+ invert: false,
+ link: true,
+ phase: (0.0, 0.0),
+ });
+ }
+ let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0;
+ let one = with_threads(1, run);
+ for threads in [2, 5, 16] {
+ let many = with_threads(threads, run);
+ assert_eq!(one.len(), many.len());
+ for (j, (a, m)) in one.iter().zip(&many).enumerate() {
+ assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads");
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
/// The four fields that use the distance transform, of `m`.
fn distance_field_of(m: &Map, reach: f32) -> Vec> {
[FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside]
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 396d22157d..671dbf95ca 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 {
Ok(r.document)
}
-/// What a headless save writes beyond the format: JPEG quality and format, TIFF layers, Targa bits,
-/// PSD previews and the PSD merged image.
+/// What a headless save writes beyond the format: JPEG quality and format, 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.
@@ -303,6 +303,9 @@ pub(crate) struct SaveOpts {
pub tga_bits: Option,
/// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16.
pub dpx_bits: Option,
+ /// 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
@@ -318,6 +321,7 @@ impl Default for SaveOpts {
tiff_layers: false,
tga_bits: None,
dpx_bits: None,
+ dds: photocraft_io::DdsOptions::default(),
image_previews: true,
psd_maximize_compatibility: true,
}
@@ -338,6 +342,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,
})
@@ -401,6 +406,30 @@ pub fn dpx_bits_param(p: &Value, cmd: &str) -> Result