mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 04:38:29 +00:00
Merge pull request #8965 from dotCooCoo/feat/save-for-web-transparency-dither
Save for Web: Transparency Dither makes a share of partly transparent pixels clear
This commit is contained in:
@@ -701,8 +701,15 @@ impl Indexing {
|
||||
v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8
|
||||
}
|
||||
};
|
||||
let options =
|
||||
|r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None };
|
||||
let options = |r: Reduction| PaletteOptions {
|
||||
colors: colors.unwrap_or(256),
|
||||
reduction: r,
|
||||
dither,
|
||||
dither_amount,
|
||||
transparency: true,
|
||||
matte: None,
|
||||
..PaletteOptions::default()
|
||||
};
|
||||
let refuse_colors = |name: &str| match colors {
|
||||
Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))),
|
||||
None => Ok(()),
|
||||
|
||||
@@ -348,6 +348,7 @@ impl RasterOptions {
|
||||
Some(v) => background(v).map_err(|e| bad(C, format!("matte: {e}")))?,
|
||||
None => Some([255; 3]),
|
||||
},
|
||||
..PaletteOptions::default()
|
||||
},
|
||||
tiff: TiffOptions {
|
||||
color_model,
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (gif/png8 with transparency: partly transparent pixels become transparent or keep their color in a dither, about as many keeping it as their opacity says with pattern, noise or diffusion at amount 100; fully transparent and opaque pixels do not change), transparencyDitherAmount?: 100 (0–100: the diffusion dither's strength, a lower amount closer to none, 0 as none), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -403,6 +403,12 @@ pub struct WebSettings {
|
||||
pub dither_amount: u8,
|
||||
/// Keep transparent pixels transparent (GIF, PNG-8, PNG-24).
|
||||
pub transparency: bool,
|
||||
/// GIF and PNG-8 with `transparency`: how partly transparent pixels are split between the
|
||||
/// transparent entry and their color (`none`: under half opacity is transparent).
|
||||
#[serde(serialize_with = "ser_key", deserialize_with = "de_key")]
|
||||
pub transparency_dither: Dither,
|
||||
/// 0–100: the strength of the `diffusion` transparency dither.
|
||||
pub transparency_dither_amount: u8,
|
||||
/// What partly transparent edges blend into (JPEG and opaque PNG-24: the background): `white`,
|
||||
/// `black`, `none` or `#rrggbb`.
|
||||
pub matte: String,
|
||||
@@ -449,6 +455,8 @@ impl Default for WebSettings {
|
||||
dither: Dither::Diffusion,
|
||||
dither_amount: 100,
|
||||
transparency: true,
|
||||
transparency_dither: Dither::None,
|
||||
transparency_dither_amount: 100,
|
||||
matte: "white".into(),
|
||||
interlaced: false,
|
||||
web_snap: 0,
|
||||
@@ -497,6 +505,10 @@ impl WebSettings {
|
||||
fn checked(mut self) -> std::result::Result<Self, String> {
|
||||
self.colors = self.colors.clamp(2, 256);
|
||||
self.dither_amount = self.dither_amount.min(100);
|
||||
if self.transparency_dither_amount > 100 {
|
||||
let key = "transparencyDitherAmount";
|
||||
return Err(format!("`{key}` must be from 0 to 100"));
|
||||
}
|
||||
self.web_snap = self.web_snap.min(100);
|
||||
self.lossy = self.lossy.min(100);
|
||||
self.quality = self.quality.min(100);
|
||||
@@ -804,6 +816,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
dither_amount: s.dither_amount,
|
||||
transparency: s.transparency,
|
||||
matte,
|
||||
transparency_dither: s.transparency_dither,
|
||||
transparency_dither_amount: s.transparency_dither_amount,
|
||||
};
|
||||
let (mut ix, dropped) = reduced(rgba, w, h, s, &o, &kept)?;
|
||||
// Map to transparent works on the colours the reduction made.
|
||||
@@ -910,7 +924,7 @@ fn reduced(
|
||||
return Ok((quantize::quantize_to(rgba, w, h, o, &left), vec![]));
|
||||
}
|
||||
// A fixed palette holds at most `colors` entries, the transparent one included.
|
||||
let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128);
|
||||
let has_clear = quantize::clear_mask(rgba, w, o).contains(&true);
|
||||
let removed = custom.iter().any(|c| deleted.contains(c));
|
||||
let mut left: Vec<[u8; 3]> = vec![];
|
||||
for c in custom {
|
||||
@@ -977,12 +991,13 @@ fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8;
|
||||
return vec![];
|
||||
}
|
||||
let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect();
|
||||
let width = ix.width;
|
||||
let Indexed { palette, transparent, indices, .. } = ix;
|
||||
// The entry such pixels take, looked up at the first of them.
|
||||
let mut entry: Option<Option<u8>> = None;
|
||||
let mut taken = vec![false; dropped.len()];
|
||||
let mut pixel = 0;
|
||||
quantize::nearest_entries(rgba, o, &all, |n| {
|
||||
quantize::nearest_entries(rgba, width, o, &all, |n| {
|
||||
if let Some(d) = n.and_then(|n| n.checked_sub(kept.len())) {
|
||||
let e = *entry.get_or_insert_with(|| {
|
||||
transparent.or_else(|| palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())).or_else(|| {
|
||||
|
||||
@@ -163,6 +163,92 @@ fn gif_transparency_index_and_map_to_transparent() {
|
||||
assert_eq!(pixels(&gif).get_pixel(25, 15)[3], 0, "index {i}");
|
||||
}
|
||||
|
||||
/// 40×30: red at 25% opacity on the left half, blue at 75% on the right, nothing behind them.
|
||||
fn see_through() -> Session {
|
||||
let mut s = session(40.0, 30.0);
|
||||
rect(&mut s, [0.0, 0.0, 20.0, 30.0], "#ff0000");
|
||||
run(&mut s, "transparency.set", json!({"opacity": 25}));
|
||||
rect(&mut s, [20.0, 0.0, 20.0, 30.0], "#0000ff");
|
||||
run(&mut s, "transparency.set", json!({"opacity": 75}));
|
||||
s
|
||||
}
|
||||
|
||||
/// The shares of the left and right halves' pixels that are opaque.
|
||||
fn opaque_halves(img: &image::RgbaImage) -> [f64; 2] {
|
||||
[0, 20].map(|x0| (x0..x0 + 20).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(x, y)[3] == 255).count() as f64 / 600.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() {
|
||||
let mut s = see_through();
|
||||
for format in ["gif", "png8"] {
|
||||
let file = |s: &mut Session, extra: Value| {
|
||||
let mut p = json!({"format": format, "antiAlias": "none"});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
one(s, p)
|
||||
};
|
||||
// By default the pixels under half opacity are transparent and the others opaque.
|
||||
let none = file(&mut s, json!({}));
|
||||
assert_eq!(opaque_halves(&pixels(&none)), [0.0, 1.0], "{format}");
|
||||
assert_eq!(file(&mut s, json!({"transparencyDither": "none"})), none, "{format}");
|
||||
assert_eq!(file(&mut s, json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}");
|
||||
for method in ["diffusion", "pattern", "noise"] {
|
||||
let p = json!({"transparencyDither": method});
|
||||
let dithered = file(&mut s, p.clone());
|
||||
let [left, right] = opaque_halves(&pixels(&dithered));
|
||||
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
|
||||
if format == "gif" {
|
||||
assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}");
|
||||
}
|
||||
assert_eq!(file(&mut s, p.clone()), dithered, "{format} {method}: the same art gives the same file");
|
||||
// The preview shows what Save writes.
|
||||
let mut pv = json!({"format": format, "antiAlias": "none", "image": true});
|
||||
pv["transparencyDither"] = json!(method);
|
||||
let shown = run(&mut s, "document.exportForWeb.preview", pv);
|
||||
assert_eq!(vectorcraft_format::base64_decode(shown["dataBase64"].as_str().unwrap()).unwrap(), dithered, "{format} {method}");
|
||||
// Without transparency the dither does nothing.
|
||||
let opaque = file(&mut s, json!({"transparencyDither": method, "transparency": false}));
|
||||
assert_eq!(opaque, file(&mut s, json!({"transparency": false})), "{format} {method}");
|
||||
}
|
||||
// A fixed palette keeps the transparent entry for the dithered pixels.
|
||||
let fixed = file(&mut s, json!({"transparencyDither": "pattern", "colorTable": {"customPalette": ["#ffbfbf", "#4040ff"]}}));
|
||||
let [left, right] = opaque_halves(&pixels(&fixed));
|
||||
assert!(left > 0.0 && left < 1.0 && right > 0.0 && right < 1.0, "{format}: {left} {right}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_dither_settings_are_checked_and_remembered() {
|
||||
let mut s = see_through();
|
||||
for bad in [
|
||||
json!({"transparencyDither": "spray"}),
|
||||
json!({"transparencyDither": 3}),
|
||||
json!({"transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDitherAmount": -1}),
|
||||
] {
|
||||
assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}");
|
||||
assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}");
|
||||
}
|
||||
let e = s.execute("document.exportForWeb", &json!({"transparencyDitherAmount": 101})).unwrap_err().to_string();
|
||||
assert!(e.contains("`transparencyDitherAmount` must be from 0 to 100"), "{e}");
|
||||
assert_eq!(defaults()["transparencyDither"], "none");
|
||||
assert_eq!(defaults()["transparencyDitherAmount"], 100);
|
||||
// The remembered settings and a saved preset keep both.
|
||||
let set = run(&mut s, "webExport.settings", json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40}));
|
||||
assert_eq!((&set["settings"]["transparencyDither"], &set["settings"]["transparencyDitherAmount"]), (&json!("diffusion"), &json!(40)));
|
||||
let read = run(&mut s, "webExport.settings", json!({}));
|
||||
assert_eq!(read["settings"], set["settings"]);
|
||||
run(&mut s, "webExport.presets.save", json!({"name": "Soft edges", "transparencyDither": "noise", "transparencyDitherAmount": 60}));
|
||||
let list = run(&mut s, "webExport.presets.list", json!({}));
|
||||
let saved = list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Soft edges").unwrap();
|
||||
assert_eq!((&saved["settings"]["transparencyDither"], &saved["settings"]["transparencyDitherAmount"]), (&json!("noise"), &json!(60)));
|
||||
let by_preset = one(&mut s, json!({"preset": "Soft edges", "format": "gif", "antiAlias": "none"}));
|
||||
assert_eq!(by_preset, one(&mut s, json!({"format": "gif", "antiAlias": "none", "transparencyDither": "noise", "transparencyDitherAmount": 60})));
|
||||
// Settings saved before the keys existed take the defaults.
|
||||
let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"format": "png8", "dither": "pattern"})).unwrap();
|
||||
assert_eq!((old.transparency_dither.id(), old.transparency_dither_amount), ("none", 100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_size_grows_with_quality() {
|
||||
let mut s = many_colours();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Colour reduction for palette formats (PNG-8, GIF): a palette of at most 256 colours chosen by
|
||||
//! median cut over a 15-bit histogram (refined by a few k-means passes) or a fixed palette, then
|
||||
//! each pixel mapped to its nearest entry with optional dithering (Floyd–Steinberg diffusion, an
|
||||
//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry;
|
||||
//! the others are blended over the matte colour.
|
||||
//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry, or
|
||||
//! with a transparency dither a share of the partly transparent pixels that follows their
|
||||
//! opacity; the others are blended over the matte color.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -111,11 +112,18 @@ pub struct PaletteOptions {
|
||||
pub dither: Dither,
|
||||
/// Dither strength 0–100.
|
||||
pub dither_amount: u8,
|
||||
/// Pixels under half opacity become a transparent entry; otherwise every pixel is opaque.
|
||||
/// Pixels under half opacity become a transparent entry (see `transparency_dither`);
|
||||
/// otherwise every pixel is opaque.
|
||||
pub transparency: bool,
|
||||
/// The colour partly transparent pixels are blended over. `None`: with transparency, they
|
||||
/// keep their own colour (hard edges); without, white.
|
||||
pub matte: Option<[u8; 3]>,
|
||||
/// With `transparency`, how partly transparent pixels are split between the transparent entry
|
||||
/// and their color ([`clear_mask`]); `Dither::None` cuts them at half opacity.
|
||||
pub transparency_dither: Dither,
|
||||
/// The strength of the diffusion transparency dither, 0–100 (0 cuts at half opacity); the
|
||||
/// pattern and noise methods do not use it.
|
||||
pub transparency_dither_amount: u8,
|
||||
}
|
||||
|
||||
impl Default for PaletteOptions {
|
||||
@@ -127,6 +135,8 @@ impl Default for PaletteOptions {
|
||||
dither_amount: 100,
|
||||
transparency: true,
|
||||
matte: Some([255; 3]),
|
||||
transparency_dither: Dither::None,
|
||||
transparency_dither_amount: 100,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,12 +163,12 @@ pub fn quantize(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions) -> Ind
|
||||
/// them all anyway; locked colours no pixel ends up using are left out.
|
||||
pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, locked: &[[u8; 3]]) -> Indexed {
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
let clear = |p: &[u8; 4]| o.transparency && p[3] < 128;
|
||||
let clear = clear_mask(rgba, width, o);
|
||||
let matte = o.matte.unwrap_or([255; 3]);
|
||||
let colors = opaque_colors(px, o, matches!(o.reduction, Reduction::Gray | Reduction::BlackWhite));
|
||||
let has_clear = px.iter().any(clear);
|
||||
let has_clear = clear.contains(&true);
|
||||
let k = (o.colors.clamp(2, 256) as usize - usize::from(has_clear)).max(1);
|
||||
let opaque = || colors.iter().zip(px).filter(|(_, p)| !clear(p)).map(|(c, _)| *c);
|
||||
let opaque = || colors.iter().zip(&clear).filter(|(_, c)| !**c).map(|(c, _)| *c);
|
||||
// Locked colours take their slots first (at least one is left for the reduction).
|
||||
let mut lock: Vec<[u8; 3]> = Vec::with_capacity(locked.len().min(k));
|
||||
for c in locked {
|
||||
@@ -168,6 +178,22 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions,
|
||||
}
|
||||
let free = k - lock.len();
|
||||
let (mut palette, exact) = match o.reduction {
|
||||
// With one entry left (two colors and a transparent entry, or the others locked): black or
|
||||
// white, whichever leaves the opaque pixels nearer the palette, the locked colors included.
|
||||
Reduction::BlackWhite if free < 2 => {
|
||||
let mut hist = [0u64; 256];
|
||||
for c in opaque() {
|
||||
hist[c[0] as usize] += 1;
|
||||
}
|
||||
let w = o.reduction.weights();
|
||||
let cost = |end: [u8; 3]| -> f32 {
|
||||
let entries: Vec<[f32; 3]> = lock.iter().chain([&end]).map(|c| c.map(f32::from)).collect();
|
||||
let near = |g: f32| entries.iter().map(|&e| dist([g; 3], e, w)).fold(f32::INFINITY, f32::min);
|
||||
hist.iter().enumerate().filter(|(_, n)| **n > 0).map(|(g, &n)| n as f32 * near(g as f32)).sum()
|
||||
};
|
||||
let ends = [[0; 3], [255; 3]].into_iter().filter(|c| !lock.contains(c));
|
||||
(ends.min_by(|a, b| cost(*a).total_cmp(&cost(*b))).into_iter().collect(), false)
|
||||
}
|
||||
Reduction::BlackWhite => (vec![[0; 3], [255; 3]], false),
|
||||
Reduction::Gray => ((0..free).map(|i| [(i * 255 / (free - 1).max(1)) as u8; 3]).collect(), false),
|
||||
Reduction::Web => (web(opaque(), free), false),
|
||||
@@ -185,7 +211,7 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions,
|
||||
if palette.is_empty() {
|
||||
palette.push(matte);
|
||||
}
|
||||
finish(px, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither })
|
||||
finish(&clear, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither })
|
||||
}
|
||||
|
||||
/// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither,
|
||||
@@ -195,26 +221,92 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions,
|
||||
pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed {
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
let colors = opaque_colors(px, o, false);
|
||||
let has_clear = o.transparency && px.iter().any(|p| p[3] < 128);
|
||||
let clear = clear_mask(rgba, width, o);
|
||||
let has_clear = clear.contains(&true);
|
||||
let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect();
|
||||
if palette.is_empty() {
|
||||
palette.push(o.matte.unwrap_or([255; 3]));
|
||||
}
|
||||
finish(px, &colors, width, height, &palette, o, o.dither)
|
||||
finish(&clear, &colors, width, height, &palette, o, o.dither)
|
||||
}
|
||||
|
||||
/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures
|
||||
/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a
|
||||
/// pixel that becomes transparent, and for every pixel when `palette` is empty. `f` gets each
|
||||
/// pixel's entry in pixel order, worked out one pixel at a time.
|
||||
pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]], mut f: impl FnMut(Option<usize>)) {
|
||||
/// For each pixel of `rgba` (`width` pixels a row), the entry of `palette` nearest its color, as
|
||||
/// [`quantize_to`] measures it (the matte, transparency and `o.reduction`'s distance weights)
|
||||
/// without dither; `None` for a pixel that becomes transparent ([`clear_mask`]), and for every
|
||||
/// pixel when `palette` is empty. `f` gets each pixel's entry in pixel order, worked out one pixel
|
||||
/// at a time.
|
||||
pub fn nearest_entries(rgba: &[u8], width: u32, o: &PaletteOptions, palette: &[[u8; 3]], mut f: impl FnMut(Option<usize>)) {
|
||||
let clear = clear_mask(rgba, width, o);
|
||||
let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect();
|
||||
let index = PaletteIndex::new(&pal, o.reduction.weights());
|
||||
for p in rgba.as_chunks::<4>().0 {
|
||||
f(if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(opaque_color(p, o, false).map(f32::from))) });
|
||||
for (p, &clear) in rgba.as_chunks::<4>().0.iter().zip(&clear) {
|
||||
f(if pal.is_empty() || clear { None } else { Some(index.nearest(opaque_color(p, o, false).map(f32::from))) });
|
||||
}
|
||||
}
|
||||
|
||||
/// Which pixels of `rgba` (`width` pixels a row) become the transparent entry. Without
|
||||
/// `o.transparency`, none. Otherwise fully transparent pixels always do and opaque ones never; a
|
||||
/// partly transparent pixel does under half opacity with no transparency dither, and else by
|
||||
/// `o.transparency_dither`. With pattern, noise, or diffusion at amount 100, about as many of an
|
||||
/// area's pixels stay opaque as its opacity says; a lower diffusion amount moves the result toward
|
||||
/// the cut at half opacity. Diffusion spreads each partly transparent pixel's opacity error to the
|
||||
/// pixels right of it and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), and
|
||||
/// fully transparent and opaque pixels pass on the error they receive; pattern compares the
|
||||
/// opacity with the 8×8 ordered pattern and noise with a noise threshold. The result depends only
|
||||
/// on the pixels and the options, so exports are reproducible.
|
||||
pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec<bool> {
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
if !o.transparency {
|
||||
return vec![false; px.len()];
|
||||
}
|
||||
let width = (width as usize).min(px.len()).max(1);
|
||||
let amount = f32::from(o.transparency_dither_amount.min(100)) / 100.0;
|
||||
let dither = match o.transparency_dither {
|
||||
Dither::Diffusion if amount == 0.0 => Dither::None,
|
||||
d => d,
|
||||
};
|
||||
// Two rows of opacity error for diffusion (the current one and the next), one pixel of margin
|
||||
// on each side.
|
||||
let mut err = vec![0f32; if dither == Dither::Diffusion { 2 * (width + 2) } else { 0 }];
|
||||
let half = err.len() / 2;
|
||||
let mut out = Vec::with_capacity(px.len());
|
||||
for (y, row) in px.chunks(width).enumerate() {
|
||||
let (cur, next) = err.split_at_mut(half);
|
||||
next.fill(0.0);
|
||||
for (x, p) in row.iter().enumerate() {
|
||||
let a = f32::from(p[3]);
|
||||
let clear = match (p[3], dither) {
|
||||
(0, _) => true,
|
||||
(255, _) => false,
|
||||
(_, Dither::None) => p[3] < 128,
|
||||
(_, Dither::Pattern) => a < 255.0 * bayer(x % 8, y % 8),
|
||||
// Another noise than the color dither's, so the two do not line up.
|
||||
(_, Dither::Noise) => a < 255.0 * noise(x ^ 0x5a5a, y ^ 0xa5a5),
|
||||
(_, Dither::Diffusion) => a + cur[x + 1] < 127.5,
|
||||
};
|
||||
if dither == Dither::Diffusion {
|
||||
// A partly transparent pixel spreads its own opacity error. A fully transparent or
|
||||
// opaque pixel keeps its state and passes on the error it received unchanged, so
|
||||
// the partly transparent pixels around it keep their share of opacity
|
||||
// (VectorCraft's own rule).
|
||||
let got = cur[x + 1];
|
||||
let e = match p[3] {
|
||||
0 | 255 => got,
|
||||
_ => (a + got - if clear { 0.0 } else { 255.0 }) * amount,
|
||||
};
|
||||
// 7/16 right, 3/16 below left, 5/16 below, 1/16 below right.
|
||||
cur[x + 2] += e * 7.0 / 16.0;
|
||||
next[x] += e * 3.0 / 16.0;
|
||||
next[x + 1] += e * 5.0 / 16.0;
|
||||
next[x + 2] += e / 16.0;
|
||||
}
|
||||
out.push(clear);
|
||||
}
|
||||
cur.copy_from_slice(next);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The color of each pixel when opaque: blended over the matte, and gray when `gray`.
|
||||
fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> {
|
||||
px.iter().map(|p| opaque_color(p, o, gray)).collect()
|
||||
@@ -229,20 +321,20 @@ fn opaque_color(p: &[u8; 4], o: &PaletteOptions, gray: bool) -> [u8; 3] {
|
||||
if gray { [luma(c); 3] } else { c }
|
||||
}
|
||||
|
||||
/// Map the pixels `px` (their opaque `colors`) to `palette` with `dither`, then drop the entries
|
||||
/// no pixel uses and put the transparent entry first when a pixel is transparent.
|
||||
fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed {
|
||||
let clear = |p: &[u8; 4]| o.transparency && p[3] < 128;
|
||||
/// Map the pixels (their opaque `colors`, transparent where `clear` says) to `palette` with
|
||||
/// `dither`, then drop the entries no pixel uses and put the transparent entry first when a pixel
|
||||
/// is transparent.
|
||||
fn finish(clear: &[bool], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed {
|
||||
let clear = |i: usize| clear.get(i).copied().unwrap_or(false);
|
||||
let matte = o.matte.unwrap_or([255; 3]);
|
||||
let has_clear = px.iter().any(clear);
|
||||
let has_clear = (0..colors.len()).any(clear);
|
||||
let weights = o.reduction.weights();
|
||||
// (A width past the pixels there are would size the error rows from a number nothing checked.)
|
||||
let mut indices =
|
||||
map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, |i| clear(&px[i]));
|
||||
let mut indices = map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, clear);
|
||||
// Drop the entries no pixel uses (fixed palettes), keeping the order.
|
||||
let mut used = [false; 256];
|
||||
for (i, &ix) in indices.iter().enumerate() {
|
||||
if !clear(&px[i]) {
|
||||
if !clear(i) {
|
||||
used[ix as usize] = true;
|
||||
}
|
||||
}
|
||||
@@ -258,7 +350,7 @@ fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette:
|
||||
}
|
||||
}
|
||||
for (i, ix) in indices.iter_mut().enumerate() {
|
||||
*ix = if clear(&px[i]) { 0 } else { remap[*ix as usize] };
|
||||
*ix = if clear(i) { 0 } else { remap[*ix as usize] };
|
||||
}
|
||||
Indexed { width, height, palette: kept, transparent: has_clear.then_some(0), indices }
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use vectorcraft_doc::{Appearance, Node};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use super::png::{PngOptions, encode_indexed};
|
||||
use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to};
|
||||
use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, clear_mask, nearest_entries, quantize, quantize_to};
|
||||
use super::*;
|
||||
|
||||
/// A `w`×`h` opaque image of `f(x, y)` colours.
|
||||
@@ -71,7 +71,7 @@ fn colours_cap_the_palette() {
|
||||
let px = ramps(64, 48);
|
||||
for colors in [2, 16, 64, 256] {
|
||||
for dither in Dither::ALL {
|
||||
for reduction in [Reduction::Perceptual, Reduction::Selective, Reduction::Adaptive, Reduction::Web, Reduction::Gray] {
|
||||
for reduction in Reduction::ALL {
|
||||
let ix = quantize(&px, 64, 48, &PaletteOptions { colors, dither, reduction, ..Default::default() });
|
||||
assert!(ix.palette.len() <= colors as usize, "{colors} {dither:?} {reduction:?}: {}", ix.palette.len());
|
||||
assert!(ix.indices.iter().all(|&i| (i as usize) < ix.palette.len()));
|
||||
@@ -252,3 +252,104 @@ fn ids_round_trip() {
|
||||
assert_eq!(Dither::from_id(d.id()), Some(d));
|
||||
}
|
||||
}
|
||||
|
||||
/// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`.
|
||||
fn see_through(w: u32, h: u32, alpha: impl Fn(u32, u32) -> u8) -> Vec<u8> {
|
||||
(0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| [255, 0, 0, alpha(x, y)]).collect()
|
||||
}
|
||||
|
||||
/// The share of the pixels of `ix` that are not transparent.
|
||||
fn opaque_share(ix: &Indexed) -> f64 {
|
||||
ix.indices.iter().filter(|&&i| ix.transparent != Some(i)).count() as f64 / ix.indices.len() as f64
|
||||
}
|
||||
|
||||
fn alpha_dither(d: Dither, amount: u8) -> PaletteOptions {
|
||||
PaletteOptions { transparency_dither: d, transparency_dither_amount: amount, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_dither_keeps_about_as_many_pixels_as_their_opacity() {
|
||||
let (w, h) = (32, 32);
|
||||
for alpha in [64u8, 128, 191] {
|
||||
let px = see_through(w, h, |_, _| alpha);
|
||||
// No transparency dither cuts at half opacity, and so does Diffusion at 0.
|
||||
let none = quantize(&px, w, h, &alpha_dither(Dither::None, 100));
|
||||
assert_eq!(opaque_share(&none), if alpha < 128 { 0.0 } else { 1.0 }, "none at {alpha}");
|
||||
assert_eq!(quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 0)), none, "diffusion at 0, {alpha}");
|
||||
for d in [Dither::Diffusion, Dither::Pattern, Dither::Noise] {
|
||||
let ix = quantize(&px, w, h, &alpha_dither(d, 100));
|
||||
let share = opaque_share(&ix);
|
||||
assert!((share - f64::from(alpha) / 255.0).abs() < 0.08, "{d:?} at {alpha}: {share}");
|
||||
assert_eq!(ix.transparent, Some(0), "{d:?} at {alpha}");
|
||||
// The same pixels and options give the same image.
|
||||
assert_eq!(quantize(&px, w, h, &alpha_dither(d, 100)), ix, "{d:?} at {alpha}");
|
||||
// A fixed palette and the nearest entries make the same pixels transparent.
|
||||
let fixed = quantize_to(&px, w, h, &alpha_dither(d, 100), &[[255, 0, 0], [0, 0, 255]]);
|
||||
assert_eq!(opaque_share(&fixed), share, "{d:?} at {alpha}, fixed palette");
|
||||
let mut near = Vec::new();
|
||||
nearest_entries(&px, w, &alpha_dither(d, 100), &[[255, 0, 0]], |n| near.push(n));
|
||||
let mask = clear_mask(&px, w, &alpha_dither(d, 100));
|
||||
assert_eq!(near.iter().map(Option::is_none).collect::<Vec<_>>(), mask, "{d:?} at {alpha}");
|
||||
}
|
||||
// Diffusion at half strength keeps fewer pixels of a light area opaque than at full.
|
||||
if alpha < 128 {
|
||||
let half = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 50)));
|
||||
let full = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 100)));
|
||||
assert!(0.0 < half && half < full, "{alpha}: {half} {full}");
|
||||
}
|
||||
}
|
||||
// The methods arrange the pixels differently.
|
||||
let px = see_through(w, h, |_, _| 96);
|
||||
let masks: Vec<Vec<bool>> = [Dither::Diffusion, Dither::Pattern, Dither::Noise].map(|d| clear_mask(&px, w, &alpha_dither(d, 100))).into();
|
||||
assert!(masks[0] != masks[1] && masks[1] != masks[2] && masks[0] != masks[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() {
|
||||
let (w, h) = (16, 8);
|
||||
// Fully transparent on the left, opaque on the right: every method keeps them as they are.
|
||||
let hard = see_through(w, h, |x, _| if x < 8 { 0 } else { 255 });
|
||||
let none = clear_mask(&hard, w, &alpha_dither(Dither::None, 100));
|
||||
assert_eq!(none.iter().filter(|c| **c).count(), 64);
|
||||
for d in Dither::ALL {
|
||||
assert_eq!(clear_mask(&hard, w, &alpha_dither(d, 100)), none, "{d:?}");
|
||||
}
|
||||
// Without transparency nothing is transparent, whatever the transparency dither.
|
||||
let soft = see_through(w, h, |x, _| (x * 16) as u8);
|
||||
for d in Dither::ALL {
|
||||
let o = PaletteOptions { transparency: false, ..alpha_dither(d, 100) };
|
||||
assert!(!clear_mask(&soft, w, &o).contains(&true), "{d:?}");
|
||||
assert_eq!(quantize(&soft, w, h, &o).transparent, None, "{d:?}");
|
||||
}
|
||||
// A palette of two entries keeps one for the transparent pixels and one for the others.
|
||||
let o = PaletteOptions { colors: 2, ..alpha_dither(Dither::Pattern, 100) };
|
||||
let ix = quantize(&see_through(w, h, |_, _| 128), w, h, &o);
|
||||
assert_eq!((ix.palette.len(), ix.transparent), (2, Some(0)));
|
||||
// So does Black & White, with black and white pixels both left opaque.
|
||||
let bw = PaletteOptions { reduction: Reduction::BlackWhite, matte: None, ..o };
|
||||
let px: Vec<u8> = (0..64u32).flat_map(|i| if i % 8 < 4 { [0, 0, 0, 128] } else { [255, 255, 255, 128] }).collect();
|
||||
let ix = quantize(&px, 8, 8, &bw);
|
||||
assert_eq!(ix.transparent, Some(0));
|
||||
assert!(ix.palette.len() <= 2, "{:?}", ix.palette);
|
||||
// No pixels, and a width past the pixels there are.
|
||||
assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty());
|
||||
assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_diffusion_passes_error_through_clear_and_opaque_pixels() {
|
||||
// Half-opaque pixels between fully transparent or fully opaque ones, in one row and in a
|
||||
// checkerboard: about half of them stay opaque, and the others keep their state.
|
||||
for other in [0u8, 255] {
|
||||
for (w, h, half) in [(64, 1, (|x, _| x % 2 == 0) as fn(u32, u32) -> bool), (32, 32, |x, y| (x + y) % 2 == 0)] {
|
||||
let px = see_through(w, h, |x, y| if half(x, y) { 128 } else { other });
|
||||
let mask = clear_mask(&px, w, &alpha_dither(Dither::Diffusion, 100));
|
||||
let at = |x: u32, y: u32| mask[(y * w + x) as usize];
|
||||
let cells: Vec<(u32, u32)> = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).collect();
|
||||
assert!(cells.iter().filter(|&&(x, y)| !half(x, y)).all(|&(x, y)| at(x, y) == (other == 0)), "{other} {w}x{h}");
|
||||
let halves: Vec<_> = cells.iter().filter(|&&(x, y)| half(x, y)).collect();
|
||||
let share = halves.iter().filter(|&&&(x, y)| !at(x, y)).count() as f64 / halves.len() as f64;
|
||||
assert!((share - 128.0 / 255.0).abs() < 0.1, "{other} {w}x{h}: {share}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,15 @@ fn locked_colours_survive_a_reduction() {
|
||||
let ix = quantize_locked(&px, 64, 16, &o, &[rare]);
|
||||
assert!(ix.palette.contains(&rare) && ix.palette.len() <= 4, "{:?}", ix.palette);
|
||||
assert_eq!(colours(&ix)[0], rare);
|
||||
// Black & White with black locked and one entry left: white takes it, though most pixels are black.
|
||||
let px = image(8, 8, |x, _| if x == 7 { [255; 3] } else { [0; 3] });
|
||||
let o = PaletteOptions { colors: 2, dither: Dither::None, reduction: Reduction::BlackWhite, ..Default::default() };
|
||||
let ix = quantize_locked(&px, 8, 8, &o, &[[0; 3]]);
|
||||
assert_eq!(ix.palette, [[0; 3], [255; 3]]);
|
||||
// With a light gray locked, black takes the entry left, though most pixels are white.
|
||||
let px = image(10, 1, |x, _| if x < 4 { [0; 3] } else { [255; 3] });
|
||||
let ix = quantize_locked(&px, 10, 1, &o, &[[200; 3]]);
|
||||
assert_eq!(ix.palette, [[200; 3], [0; 3]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -49,6 +49,19 @@ pub(crate) struct WebExport {
|
||||
optimized: Option<Value>,
|
||||
/// The engine's `colorTable` value: the edits the colour table's buttons made.
|
||||
table: Value,
|
||||
/// The engine's settings the dialog has no option for ([`KEPT`]), as the dialog opened on them
|
||||
/// or Optimize to File Size found them: the previews, Save… and the presets use them. A preset
|
||||
/// picked in the dialog does not change them.
|
||||
kept: Value,
|
||||
}
|
||||
|
||||
/// The engine's settings keys the dialog does not show; they pass through it unchanged.
|
||||
const KEPT: [&str; 2] = ["transparencyDither", "transparencyDitherAmount"];
|
||||
|
||||
/// The [`KEPT`] keys of the engine's settings `s`.
|
||||
fn kept_of(s: &WebSettings) -> Value {
|
||||
let engine = s.to_json();
|
||||
Value::Object(KEPT.iter().filter_map(|k| engine.get(*k).map(|v| ((*k).to_string(), v.clone()))).collect())
|
||||
}
|
||||
|
||||
/// The key of the Original pane's texture in the pump's [`TextureStore`]; the panes use their index.
|
||||
@@ -129,11 +142,15 @@ pub(super) fn options_of(s: &WebSettings, natural: Option<PixelSize>) -> SaveFor
|
||||
serde_json::from_value(v).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The engine's settings JSON for the dialog's `options`, the edited colour `table` and an optional
|
||||
/// `path`: what `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read.
|
||||
fn settings_of(options: &SaveForWebOptions, table: &Value, path: Option<&str>) -> Value {
|
||||
/// The engine's settings JSON for the dialog's `options`, the edited colour `table`, the `kept`
|
||||
/// settings the dialog does not show ([`WebExport::kept`]) and an optional `path`: what
|
||||
/// `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read.
|
||||
fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: Option<&str>) -> Value {
|
||||
let mut v = serde_json::to_value(options).unwrap_or(Value::Null);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
if let Some(kept) = kept.as_object() {
|
||||
o.extend(kept.clone());
|
||||
}
|
||||
let [r, g, b] = options.matte;
|
||||
o.insert("matte".into(), json!(format!("#{r:02x}{g:02x}{b:02x}")));
|
||||
o.remove("colorTable");
|
||||
@@ -170,7 +187,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let host = app.dialogs().ok_or("no window")?;
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window")?;
|
||||
let s = remembered(app);
|
||||
app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), ..WebExport::default() };
|
||||
app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() };
|
||||
let (name, artboards, slices) = {
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let slices: Vec<WebSlice> = st
|
||||
@@ -472,7 +489,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
on_dialog(&host, |d| d.answer_optimize(answer.map_err(Into::into)));
|
||||
}
|
||||
if asked.browser {
|
||||
let p = settings_of(&asked.options, &app.web_export.table, None);
|
||||
let p = settings_of(&asked.options, &app.web_export.table, &app.web_export.kept, None);
|
||||
if let Err(e) = browser_preview(app, &p) {
|
||||
app.status(e);
|
||||
}
|
||||
@@ -488,11 +505,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
|
||||
/// The encodes the dialog wants, as pictures, and the Original pane's picture when the rendering is new.
|
||||
fn answer_variants(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::shell::WindowDialogs, wanted: &[WantedVariant]) {
|
||||
let table = app.web_export.table.clone();
|
||||
let (table, kept) = (app.web_export.table.clone(), app.web_export.kept.clone());
|
||||
let mut answers = Vec::with_capacity(wanted.len());
|
||||
for w in wanted {
|
||||
let (index, revision) = (w.index, w.request.revision);
|
||||
let settings = app.session.web_settings(&settings_of(&w.request.options, &table, None));
|
||||
let settings = app.session.web_settings(&settings_of(&w.request.options, &table, &kept, None));
|
||||
let rendered = settings.and_then(|s| render_for(app, &s).map(|(key, r)| (s, key, r)));
|
||||
answers.push(match (rendered, app.session.active()) {
|
||||
(Ok((s, key, r)), Some(st)) => optimise(ctx, &st.doc, &r, &key, &s, w),
|
||||
@@ -532,7 +549,7 @@ fn edit_table(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::s
|
||||
|
||||
/// The source colours of the palette the dialog's settings `options` show, with the table as it stands.
|
||||
fn shown_colors(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Result<Vec<[u8; 3]>, String> {
|
||||
let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, None))?;
|
||||
let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None))?;
|
||||
Ok(encoded(app, &settings)?.colors.iter().map(|c| c.source).collect())
|
||||
}
|
||||
|
||||
@@ -565,7 +582,7 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec<WebPresetEvent>) {
|
||||
for event in events {
|
||||
let r = match event {
|
||||
WebPresetEvent::Saved(p) => {
|
||||
let mut v = settings_of(&p.options, &app.web_export.table, None);
|
||||
let mut v = settings_of(&p.options, &app.web_export.table, &app.web_export.kept, None);
|
||||
v["name"] = json!(p.name);
|
||||
app.run("webExport.presets.save", v)
|
||||
}
|
||||
@@ -596,7 +613,7 @@ fn has_slices(app: &VectorcraftApp) -> bool {
|
||||
|
||||
/// The `webExport.optimizeToFileSize` params: `options`, the desired size and, with slices, what it covers.
|
||||
fn optimize_params(app: &VectorcraftApp, options: &SaveForWebOptions, desired_k: f64, start: Option<&str>, scope: &str) -> Value {
|
||||
let mut p = settings_of(options, &app.web_export.table, None);
|
||||
let mut p = settings_of(options, &app.web_export.table, &app.web_export.kept, None);
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.insert("desiredK".into(), json!(desired_k));
|
||||
if let Some(start) = start {
|
||||
@@ -617,7 +634,7 @@ fn optimize_start(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Opti
|
||||
let r = app.run("webExport.optimizeToFileSize", p).ok()?;
|
||||
return r["achieved"].as_bool().filter(|a| *a).and_then(|_| r["bytes"].as_u64());
|
||||
}
|
||||
let s = app.session.web_settings(&settings_of(options, &app.web_export.table, None)).ok()?;
|
||||
let s = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None)).ok()?;
|
||||
encoded(app, &s).ok().map(|o| o.bytes.len() as u64)
|
||||
}
|
||||
|
||||
@@ -637,6 +654,7 @@ fn run_optimize(app: &mut VectorcraftApp, req: &OptimizeRequest) -> Result<Optim
|
||||
let r = app.run("webExport.optimizeToFileSize", p)?;
|
||||
let found = app.session.web_settings(&r["settings"])?;
|
||||
app.web_export.table = serde_json::to_value(&found.color_table).unwrap_or_default();
|
||||
app.web_export.kept = kept_of(&found);
|
||||
app.web_export.optimized = Some(
|
||||
json!({ "settings": r["settings"], "bytes": r["bytes"], "targetBytes": r["targetBytes"], "achieved": r["achieved"], "art": art_key(app) }),
|
||||
);
|
||||
@@ -653,7 +671,7 @@ fn run_optimize(app: &mut VectorcraftApp, req: &OptimizeRequest) -> Result<Optim
|
||||
/// Answers Save…'s request for a path. Bad settings never open a save panel; the web downloads, so
|
||||
/// the suggested name stands in for the path.
|
||||
fn ask_path(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, id: DialogId, req: PathRequest, options: &SaveForWebOptions) {
|
||||
let settings = match app.session.web_settings(&settings_of(options, &app.web_export.table, None)) {
|
||||
let settings = match app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None)) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
on_dialog(host, HostedSaveForWeb::cancel_requests);
|
||||
@@ -698,8 +716,9 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) {
|
||||
/// written. Failures show in the status line; the dialog has closed.
|
||||
fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) {
|
||||
let table = std::mem::take(&mut app.web_export.table);
|
||||
let kept = std::mem::take(&mut app.web_export.kept);
|
||||
app.web_export = WebExport::default();
|
||||
let params = settings_of(&result.options, &table, None);
|
||||
let params = settings_of(&result.options, &table, &kept, None);
|
||||
if let Err(e) = app.run("webExport.settings", params.clone()) {
|
||||
return app.status(e);
|
||||
}
|
||||
|
||||
@@ -312,6 +312,31 @@ fn save_remembers_and_writes_and_done_only_remembers() {
|
||||
assert!(!dir.join("Untitled-1.png").exists());
|
||||
}
|
||||
|
||||
/// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes
|
||||
/// and stays remembered after Done.
|
||||
#[test]
|
||||
fn save_keeps_the_remembered_transparency_dither() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-tdither");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
let mut written = vec![];
|
||||
for method in ["none", "noise"] {
|
||||
app.run("webExport.settings", json!({"format": "gif", "transparency": true, "transparencyDither": method})).unwrap();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
save(&mut app);
|
||||
let path = dir.join("Untitled-1.gif");
|
||||
written.push(std::fs::read(&path).unwrap());
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(app.session.last_web_settings().transparency_dither.id(), method, "remembered");
|
||||
let expected = app.session.execute("document.exportForWeb", &json!({"format": "gif", "transparencyDither": method})).unwrap();
|
||||
assert_eq!(expected["files"][0]["dataBase64"].as_str().and_then(vectorcraft_format::base64_decode).as_ref(), written.last());
|
||||
}
|
||||
assert_ne!(written[0], written[1], "the partly transparent edge is dithered");
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
set(&mut app, "choice", json!("done"));
|
||||
confirm(&mut app);
|
||||
assert_eq!(app.session.last_web_settings().transparency_dither.id(), "noise");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_output_with_slices_saves_the_page_and_images() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-html");
|
||||
|
||||
+11
-2
@@ -10934,8 +10934,8 @@ every option.
|
||||
File → Export → Save for Web (Legacy) writes optimised web images: `document.exportForWeb {format: gif|jpg|png8|png24,
|
||||
…}` renders the artboard (`clipToArtboard`, the default; `artboard` picks one) or the visible art and the slices, at
|
||||
`width`, `height` or `percent`, and encodes it with the format's settings: for GIF and PNG-8 `reduction`, `colors`,
|
||||
`dither`, `ditherAmount`, `transparency`, `matte`, `interlaced`, `webSnap`, `lossy` (GIF) and `colorTable {locked,
|
||||
transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24
|
||||
`dither`, `ditherAmount`, `transparency`, `transparencyDither`, `transparencyDitherAmount`, `matte`, `interlaced`,
|
||||
`webSnap`, `lossy` (GIF) and `colorTable {locked, transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24
|
||||
`transparency`, `matte` and `interlaced`. `metadata` (none, copyright, contact, all) writes File Info as PNG text or a
|
||||
GIF/JPEG comment; `convertToSrgb` marks PNGs as sRGB. `<stem>` is the name of `path` without its extension, or
|
||||
without `path` the document's title with the characters Windows does not allow in a file name as `-` and a `-` after
|
||||
@@ -10946,6 +10946,15 @@ after a Windows device name such as `aux` (`slices: selected` writes the selecte
|
||||
Without `path` the files come back as `{name, dataBase64}`. As in the raster exports, `warnings` says when an image
|
||||
couldn't be decoded and is missing from the image; the files are written all the same.
|
||||
|
||||
With `transparency` on, `transparencyDither` sets how GIF and PNG-8 treat partly transparent pixels: `none` (the
|
||||
default) makes the pixels under half opacity transparent and keeps the others; `diffusion`, `pattern` and `noise` make
|
||||
some of them transparent and keep the rest in a diffusion pattern, an 8×8 ordered pattern or noise. With `pattern`,
|
||||
`noise`, or `diffusion` at amount 100, about as many are kept as their opacity says. `transparencyDitherAmount` (0 to
|
||||
100, default 100) sets the strength of `diffusion`: a lower amount comes closer to `none`, and 0 gives the same file as
|
||||
`none`. Fully transparent and fully opaque pixels do not change, the same art and settings
|
||||
always give the same file, and a kept pixel is blended over `matte` as before. Without `transparency` both keys are
|
||||
kept and do not change the file. An unknown method or an amount outside 0 to 100 is refused.
|
||||
|
||||
`document.exportForWeb.preview` returns what Save writes for the same settings without writing it: `bytes` (the exact
|
||||
file size), `seconds` to download at `kbps` (default 56.6), the size, and for palette formats the colour table
|
||||
(`colors: [{color, source, transparent, locked, webShifted, shifted, webSafe}]`). The colour table's lists name colours by
|
||||
|
||||
@@ -1015,6 +1015,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- SVG Options: Show in Browser opens the SVG in the default web browser, beside Show Code, which shows the code instead; the SVG export options on the help page (https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) list both. VectorCraft writes the SVG of the dialog's current choices for one page to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder, which is kept and cleaned up as Save for Web's previews are, and the dialog stays open without remembering the choices or writing the chosen file. The page is VectorCraft's own choice: under Export Selection the selection's crop, otherwise the first artboard the options choose, and a range the document does not have is an error. The web build disables the button, and control and MCP requests for `file.export.svg.browser` are refused. `crates/ui-egui/src/dialogs/svg_options.rs` (`show_in_browser_opens_what_ok_writes_without_confirming`, `show_in_browser_is_refused_on_the_web_and_for_automation`, `svg_preview_folders_leave_save_for_web_previews_alone`).
|
||||
- Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged.
|
||||
- Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`).
|
||||
- Save for Web: with Transparency on, GIF and PNG-8 exports take a Transparency Dither (none, diffusion, pattern and noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an amount for diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is none with amount 100; with pattern, noise, or diffusion at amount 100, about as many pixels stay opaque as their opacity says, and a lower diffusion amount comes closer to none; pattern uses an 8×8 ordered pattern and noise a fixed noise, so the same art always gives the same file; amount 0 gives the same file as none; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; without Transparency both settings are kept and do not change the file; presets and the remembered settings keep them (`document.exportForWeb`, `webExport.settings`: `transparencyDither`, `transparencyDitherAmount`). The Save for Web dialog does not show these settings yet; its previews and Save… use the remembered ones, and a preset picked in the dialog does not change them.
|
||||
- Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged.
|
||||
- Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged.
|
||||
- Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`).
|
||||
|
||||
Reference in New Issue
Block a user