mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 08:11:41 +00:00
Merge main into feat/stylus-wheel
This commit is contained in:
@@ -154,18 +154,8 @@ pub fn quantize(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions) -> Ind
|
||||
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 gray = matches!(o.reduction, Reduction::Gray | Reduction::BlackWhite);
|
||||
let matte = o.matte.unwrap_or([255; 3]);
|
||||
let blend = o.matte.is_some() || !o.transparency;
|
||||
// The opaque colours: blended over the matte, greys for the grey reductions.
|
||||
let colors: Vec<[u8; 3]> = px
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let a = if blend { p[3] as u32 } else { 255 };
|
||||
let c = [0, 1, 2].map(|i| ((p[i] as u32 * a + matte[i] as u32 * (255 - a) + 127) / 255) as u8);
|
||||
if gray { [luma(c); 3] } else { c }
|
||||
})
|
||||
.collect();
|
||||
let colors = opaque_colors(px, o, matches!(o.reduction, Reduction::Gray | Reduction::BlackWhite));
|
||||
let has_clear = px.iter().any(clear);
|
||||
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);
|
||||
@@ -195,11 +185,46 @@ 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 })
|
||||
}
|
||||
|
||||
/// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither,
|
||||
/// transparency and matte; `o.reduction` sets only the distance weights, and `o.colors` is not
|
||||
/// used. Only the first 255 colors of `palette` are used, leaving room for the transparent entry.
|
||||
/// Entries no pixel uses are left out.
|
||||
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 mut palette: Vec<[u8; 3]> = palette.iter().take(255).copied().collect();
|
||||
if palette.is_empty() {
|
||||
palette.push(o.matte.unwrap_or([255; 3]));
|
||||
}
|
||||
finish(px, &colors, width, height, &palette, o, o.dither)
|
||||
}
|
||||
|
||||
/// 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]> {
|
||||
let matte = o.matte.unwrap_or([255; 3]);
|
||||
let blend = o.matte.is_some() || !o.transparency;
|
||||
px.iter()
|
||||
.map(|p| {
|
||||
let a = if blend { p[3] as u32 } else { 255 };
|
||||
let c = [0, 1, 2].map(|i| ((p[i] as u32 * a + matte[i] as u32 * (255 - a) + 127) / 255) as u8);
|
||||
if gray { [luma(c); 3] } else { c }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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;
|
||||
let matte = o.matte.unwrap_or([255; 3]);
|
||||
let has_clear = px.iter().any(clear);
|
||||
let weights = o.reduction.weights();
|
||||
let dither = if exact { Dither::None } else { o.dither };
|
||||
// (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]));
|
||||
map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, |i| clear(&px[i]));
|
||||
// Drop the entries no pixel uses (fixed palettes), keeping the order.
|
||||
let mut used = [false; 256];
|
||||
for (i, &ix) in indices.iter().enumerate() {
|
||||
|
||||
@@ -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};
|
||||
use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to};
|
||||
use super::*;
|
||||
|
||||
/// A `w`×`h` opaque image of `f(x, y)` colours.
|
||||
@@ -93,6 +93,22 @@ fn fixed_palettes() {
|
||||
assert_eq!(bw.palette, [[0, 0, 0], [255, 255, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_palette_keeps_the_entries_pixels_use() {
|
||||
let px: Vec<u8> = [[250, 10, 10, 255], [10, 10, 240, 255], [0, 0, 0, 40], [240, 20, 30, 255]].concat();
|
||||
let given = [[0, 255, 0], [255, 0, 0], [0, 0, 255], [255, 255, 255]];
|
||||
let o = PaletteOptions { dither: Dither::None, matte: None, ..Default::default() };
|
||||
let ix = quantize_to(&px, 4, 1, &o, &given);
|
||||
assert_eq!(ix.transparent, Some(0));
|
||||
assert_eq!(ix.palette[1..], [[255, 0, 0], [0, 0, 255]], "unused entries left out, the order kept");
|
||||
assert_eq!(ix.indices, [1, 2, 0, 1]);
|
||||
// At most 255 of the given colors are used, leaving room for the transparent entry.
|
||||
let many: Vec<[u8; 3]> = (0..300u32).map(|i| [(i % 256) as u8, (i / 256) as u8, 0]).collect();
|
||||
let all = image(256, 2, |x, y| [x as u8, y as u8, 0]);
|
||||
let ix = quantize_to(&all, 256, 2, &o, &many);
|
||||
assert!(ix.palette.len() <= 255 && ix.palette.iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dithering_keeps_the_average_colour() {
|
||||
let px = image(64, 16, |x, _| [(x * 4) as u8; 3]);
|
||||
|
||||
@@ -69,12 +69,23 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
}
|
||||
let bp = node_bezpath(n)?;
|
||||
let ctx = GeomContext { doc: Some(symbols.document()), ..GeomContext::of(n) };
|
||||
let g = effected_path(symbols.document(), n, &bp);
|
||||
let (g, carry) = effected_path_carrying(symbols.document(), n, &bp);
|
||||
// The raster effects reach as far as they are drawn: following only the Transform effects
|
||||
// that moved the art ([`effects::Carry::hide_skipped`]).
|
||||
let mut ran = std::borrow::Cow::Borrowed(n);
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran.to_mut().appearance.effects);
|
||||
}
|
||||
let mut r: Option<Rect> = (!g.elements().is_empty()).then(|| g.bounding_box());
|
||||
for item in &n.appearance.items {
|
||||
for (j, item) in n.appearance.items.iter().enumerate() {
|
||||
let fx = item_effects(item);
|
||||
if effects::has_geometry(fx) {
|
||||
let ig = apply(fx, &g, &ctx.item(item));
|
||||
let (ig, c) = apply_carrying(fx, &g, &ctx.item(item));
|
||||
if c.skipped()
|
||||
&& let Some(it) = ran.to_mut().appearance.items.get_mut(j)
|
||||
{
|
||||
c.hide_skipped(it.effects_mut());
|
||||
}
|
||||
if !ig.elements().is_empty() {
|
||||
let b = ig.bounding_box();
|
||||
r = Some(r.map_or(b, |r| r.union(b)));
|
||||
@@ -82,7 +93,44 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
}
|
||||
}
|
||||
let s = n.appearance.outset();
|
||||
r.map(|r| with_raster_reach(symbols, n, r.inflate(s, s)))
|
||||
r.map(|r| with_raster_reach(symbols, &ran, r.inflate(s, s)))
|
||||
}
|
||||
|
||||
/// `n` with the Transform effects its geometry passes leave out (past the budget) hidden, in its
|
||||
/// own list and in its fills' and strokes' ([`effects::Carry::hide_skipped`]): the effects its
|
||||
/// raster effects are drawn from. Borrowed when it has no Transform effect or no raster effect, is
|
||||
/// not a path or compound path, or its art is made by [`effects::reshape`] or a 3D effect.
|
||||
fn ran<'a>(doc: &Document, n: &'a Node) -> std::borrow::Cow<'a, Node> {
|
||||
let transforms = |fx: &[Effect]| fx.iter().any(|e| e.visible && e.id == "distort.transform");
|
||||
let mut out = std::borrow::Cow::Borrowed(n);
|
||||
if (!transforms(&n.appearance.effects) && !n.appearance.items.iter().any(|i| transforms(item_effects(i))))
|
||||
|| (effects::raster_effects(&n.appearance.effects).is_empty()
|
||||
&& n.appearance.items.iter().all(|i| effects::raster_effects(item_effects(i)).is_empty()))
|
||||
|| effects::has_painted_effects(n)
|
||||
|| effects::has_revolve(n)
|
||||
|| effects::has_solid(n)
|
||||
{
|
||||
return out;
|
||||
}
|
||||
let Some(bp) = node_bezpath(n) else { return out };
|
||||
let ctx = GeomContext { doc: Some(doc), ..GeomContext::of(n) };
|
||||
let (g, carry) = apply_carrying(&n.appearance.effects, &bp, &ctx);
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut out.to_mut().appearance.effects);
|
||||
}
|
||||
for (j, item) in n.appearance.items.iter().enumerate() {
|
||||
let fx = item_effects(item);
|
||||
if !transforms(fx) || g.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (_, c) = apply_carrying(fx, &g, &ctx.item(item));
|
||||
if c.skipped()
|
||||
&& let Some(it) = out.to_mut().appearance.items.get_mut(j)
|
||||
{
|
||||
c.hide_skipped(it.effects_mut());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `r`, the art of `n` with its strokes, grown by how far the raster effects of `n`'s fills and
|
||||
@@ -176,13 +224,37 @@ fn paints(item: &AppearanceItem) -> bool {
|
||||
/// [`Node::visual_bounds_with`] measures them, without the reach of `n`'s own raster effects
|
||||
/// (symbol instances measured by their art from `symbols`): what Rasterize makes its image over.
|
||||
pub(crate) fn drawn_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
drawn_bounds_ran(symbols, n, None)
|
||||
}
|
||||
|
||||
/// [`drawn_bounds`], with `ran`, [`ran`] of `n`, when the caller has it.
|
||||
fn drawn_bounds_ran(symbols: &SymbolBoxes, n: &Node, ran: Option<&Node>) -> Option<Rect> {
|
||||
// A 3D effect's art holds its fills' and strokes' raster effects, measured with it.
|
||||
if let Some(b) = three_d_bounds(symbols, n) {
|
||||
return b;
|
||||
}
|
||||
let b = art_bounds(symbols, n)?;
|
||||
let items = n.appearance.items.iter().filter(|i| paints(i) && !effects::raster_effects(item_effects(i)).is_empty());
|
||||
Some(items.map(|i| spread(symbols, &item_raster(n, i), item_bounds(symbols.document(), n, i).unwrap_or(b))).fold(b, |acc, r| acc.union(r)))
|
||||
let mut items =
|
||||
n.appearance.items.iter().enumerate().filter(|(_, i)| paints(i) && !effects::raster_effects(item_effects(i)).is_empty()).peekable();
|
||||
if items.peek().is_none() {
|
||||
return Some(b);
|
||||
}
|
||||
let own;
|
||||
let ran = match ran {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
own = self::ran(symbols.document(), n);
|
||||
&*own
|
||||
}
|
||||
};
|
||||
Some(
|
||||
items
|
||||
.map(|(j, i)| {
|
||||
let r = ran.appearance.items.get(j).unwrap_or(i);
|
||||
spread(symbols, &item_raster(ran, r), item_bounds(symbols.document(), n, i).unwrap_or(b))
|
||||
})
|
||||
.fold(b, |acc, r| acc.union(r)),
|
||||
)
|
||||
}
|
||||
|
||||
/// The bounds of what `item`, a fill or stroke of the path or compound path `n`, paints: the path
|
||||
@@ -363,7 +435,9 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
if let Some(art) = effects::crop_marks_art(n) {
|
||||
return drawn_bounds(symbols, &art);
|
||||
}
|
||||
drawn_bounds(symbols, n).map(|b| spread(symbols, &n.appearance.effects, b))
|
||||
let ran = ran(symbols.document(), n);
|
||||
let b = drawn_bounds_ran(symbols, n, Some(&ran))?;
|
||||
Some(spread(symbols, &ran.appearance.effects, b))
|
||||
}
|
||||
|
||||
/// The outline the renderer clips `n`'s Feather, Inner Glow and Rasterize with Create Clipping
|
||||
|
||||
@@ -676,6 +676,13 @@ impl Renderer {
|
||||
ap.items.pop()
|
||||
});
|
||||
let item = carried.as_ref().and_then(Option::as_ref).unwrap_or(item);
|
||||
// Its raster effects follow only the Transform effects that moved it.
|
||||
let ran = carry.skipped().then(|| {
|
||||
let mut it = item.clone();
|
||||
carry.hide_skipped(it.effects_mut());
|
||||
it
|
||||
});
|
||||
let item = ran.as_ref().unwrap_or(item);
|
||||
let ib = if effects::has_geometry(item_effects(item)) && !ig.elements().is_empty() { ig.bounding_box() } else { bounds };
|
||||
let rfx = effects::raster_effects(&item_raster(n, item));
|
||||
if rfx.is_empty() {
|
||||
|
||||
@@ -381,7 +381,8 @@ impl Renderer {
|
||||
return;
|
||||
}
|
||||
let gctx = GeomContext { doc: Some(f.symbols.document()), ..GeomContext::of(paints) };
|
||||
let rfx = effects::raster_effects(&n.appearance.effects);
|
||||
// `paints` hides the Transform effects that did not move `g`.
|
||||
let rfx = effects::raster_effects(&paints.appearance.effects);
|
||||
// Document-space reach of the painted geometry (strokes, arrowheads…).
|
||||
let outset = n.appearance.outset();
|
||||
let reach = g.bounding_box().inflate(outset, outset);
|
||||
@@ -926,12 +927,18 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` with the gradients of its fills and strokes moved along with its effects by `carry`, or
|
||||
/// `None` when they stay where they are.
|
||||
/// `n` with the gradients of its fills and strokes moved along with its effects by `carry`, and
|
||||
/// the Transform effects the geometry pass left out hidden ([`effects::Carry::hide_skipped`]), so
|
||||
/// its raster effects and those of its fills and strokes stay with its art; `None` when it stays
|
||||
/// as it is.
|
||||
fn carried(n: &Node, carry: &effects::Carry) -> Option<Arc<Node>> {
|
||||
carry.moves(&n.appearance).then(|| {
|
||||
let moves = carry.moves(&n.appearance);
|
||||
(moves || carry.skipped()).then(|| {
|
||||
let mut m = n.clone();
|
||||
carry.apply(&mut m.appearance);
|
||||
if moves {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
carry.hide_skipped(&mut m.appearance.effects);
|
||||
Arc::new(m)
|
||||
})
|
||||
}
|
||||
@@ -943,6 +950,42 @@ mod tests {
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, color::BlendMode};
|
||||
|
||||
/// The node a path is painted from hides a Transform effect left out past the effect budget,
|
||||
/// so the drop shadow before it is drawn with its own offset and blur, as the art stays.
|
||||
#[test]
|
||||
fn a_path_paints_from_the_transforms_that_moved_it() {
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
let anchors = (0..=30_000)
|
||||
.map(|i| {
|
||||
let x = 2.0 * f64::from(i);
|
||||
Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0))
|
||||
})
|
||||
.collect();
|
||||
let path = PathData::single(SubPath::new(anchors, true));
|
||||
let mut n = Node::path(
|
||||
vectorcraft_doc::NodeId(1),
|
||||
path.clone(),
|
||||
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(Color::rgb(1.0, 0.0, 0.0)), vectorcraft_color::Paint::None, 0.0),
|
||||
);
|
||||
n.appearance.effects = vec![
|
||||
vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 10, "y": 5, "blur": 4}), visible: true },
|
||||
vectorcraft_doc::Effect {
|
||||
id: "distort.transform".into(),
|
||||
params: serde_json::json!({"scaleH": 100000, "scaleV": 100000}),
|
||||
visible: true,
|
||||
},
|
||||
];
|
||||
let doc = Document::new(100.0, 100.0);
|
||||
let bp = path.to_bezpath();
|
||||
let (g, carry) = effected_path_carrying(&doc, &n, &bp);
|
||||
assert_eq!(g.bounding_box(), bp.bounding_box(), "the art stays where it is");
|
||||
let paints = carried(&n, &carry).expect("the Transform effect is hidden");
|
||||
match effects::raster_effects(&paints.appearance.effects).first() {
|
||||
Some(RasterFx::DropShadow { dx, dy, blur, .. }) => assert!((*dx, *dy, *blur) == (10.0, 5.0, 4.0), "{dx} {dy} {blur}"),
|
||||
other => panic!("expected a drop shadow, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uncached_darkness_shadow_subtracts_before_separate_opacity() {
|
||||
let doc = Document::new(100.0, 100.0);
|
||||
|
||||
@@ -284,9 +284,20 @@ impl Renderer {
|
||||
ctx.push_layer(None, Some(BlendMode::new(Mix::Normal, compose)), None, None, None);
|
||||
self.nested += 1;
|
||||
let shape = compose != Compose::Plus && !c.knockout_shape;
|
||||
self.shape_of = if shape { Arc::as_ptr(c) as usize } else { 0 };
|
||||
self.draw_arc(ctx, f, c);
|
||||
self.shape_of = 0;
|
||||
// A piece of a mesh-warped image knocks out its whole triangle, where its neighbors
|
||||
// overlap it, at full coverage whatever the image's own alpha there.
|
||||
if shape && let Some(outline) = c.knockout_outline() {
|
||||
if let Some(region) = self.clip_of(outline) {
|
||||
ctx.set_transform(f.view);
|
||||
ctx.set_paint(f.ink.fixed([255, 255, 255, 255]));
|
||||
ctx.set_fill_rule(fill_rule(region.1));
|
||||
ctx.fill_path(®ion.0);
|
||||
}
|
||||
} else {
|
||||
self.shape_of = if shape { Arc::as_ptr(c) as usize } else { 0 };
|
||||
self.draw_arc(ctx, f, c);
|
||||
self.shape_of = 0;
|
||||
}
|
||||
self.nested -= 1;
|
||||
ctx.pop_layer();
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ mod knockout;
|
||||
mod layeropts;
|
||||
mod longstroke;
|
||||
mod memory;
|
||||
mod meshwarp;
|
||||
mod movedstroke;
|
||||
mod objectfx;
|
||||
mod paintedbrush;
|
||||
|
||||
@@ -210,6 +210,60 @@ fn a_documents_own_composite_font_draws_without_being_registered() {
|
||||
assert!(db.composite_font(NAME).is_none(), "given back after each render");
|
||||
}
|
||||
|
||||
/// A placed document draws its type in its own definition of a composite font that the document
|
||||
/// placing it defines differently.
|
||||
#[test]
|
||||
fn a_placed_document_draws_its_own_definition_of_a_name_the_page_defines() {
|
||||
use vectorcraft_doc::{CompositeFont, CompositePart, CompositeParts, ImageBlob, LinkInfo, PlacedDocument};
|
||||
let _adding = adding_fonts();
|
||||
const NAME: &str = "CF Placed Twice";
|
||||
let definition = |roman: &str| {
|
||||
let mut parts = CompositeParts::all(CompositePart::new("Source Sans 3", "Regular"));
|
||||
parts.roman = CompositePart::new(roman, "Regular");
|
||||
CompositeFont { name: NAME.into(), parts }
|
||||
};
|
||||
let typed = |family: &str| {
|
||||
let mut d = Document::new(300.0, 150.0);
|
||||
let style = CharStyle { size: 60.0, font_family: family.into(), ..Default::default() };
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 100.0), "Hamburg", style))));
|
||||
let l = d.layers[0].id;
|
||||
let id = d.insert(Some(l), 0, n).unwrap();
|
||||
(d, id)
|
||||
};
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
// A page placing `d` (drawn exactly), defining `fonts`.
|
||||
let page = |d: &Document, id: NodeId, key: &str, fonts: Vec<CompositeFont>| {
|
||||
let blob = ImageBlob::new("application/json", key.as_bytes().to_vec());
|
||||
let p = PlacedDocument {
|
||||
link: LinkInfo::new("/art/type.vectorcraft"),
|
||||
key: key.into(),
|
||||
bounding: false,
|
||||
page_box: Default::default(),
|
||||
width: 300.0,
|
||||
height: 150.0,
|
||||
xf: Affine::IDENTITY,
|
||||
placement: Default::default(),
|
||||
};
|
||||
let art = d.node(id).unwrap().clone();
|
||||
vectorcraft_doc::placed_document::prime(&p, blob.bytes.clone(), (d.clone(), art, Rect::new(0.0, 0.0, 300.0, 150.0)));
|
||||
let mut page = Document::new(300.0, 150.0);
|
||||
page.composite_fonts.extend(fonts);
|
||||
page.images.insert(key.into(), blob);
|
||||
let n = Node::new(page.alloc_id(), NodeKind::PlacedDocument(Box::new(p)));
|
||||
let l = page.layers[0].id;
|
||||
page.insert(Some(l), 0, n).unwrap();
|
||||
Renderer::new().render(&page, 300, 150, Affine::IDENTITY, &opts).pixels
|
||||
};
|
||||
let (mut placed, id) = typed(NAME);
|
||||
placed.composite_fonts.push(definition("JetBrains Mono"));
|
||||
let (plain, plain_id) = typed("JetBrains Mono");
|
||||
let (inter, inter_id) = typed("Inter");
|
||||
let own = page(&placed, id, "fontchange-placed-twice", vec![definition("Inter")]);
|
||||
assert!(own == page(&plain, plain_id, "fontchange-placed-twice-plain", vec![]), "drawn in the placed document's definition");
|
||||
assert!(own != page(&inter, inter_id, "fontchange-placed-twice-inter", vec![]), "not in the page's");
|
||||
assert!(vectorcraft_text::FontDb::global().composite_font(NAME).is_none());
|
||||
}
|
||||
|
||||
/// Type at 80% opacity, in Multiply and with a drop shadow redraws in a font that becomes
|
||||
/// available: the glyph geometry kept for it is laid out again.
|
||||
#[test]
|
||||
|
||||
@@ -931,6 +931,8 @@ fn brush_art_draws_edits_of_the_symbols_and_patterns_it_shows() {
|
||||
painted.transform(Affine::translate((0.0, 8.0)), true);
|
||||
let scatter = Node::group(d.alloc_id(), vec![Arc::new(instance), Arc::new(painted)]);
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
// The default library has its own `Dots`, which a stroke would draw with first.
|
||||
lib.retain(|b| b.name != "Dots");
|
||||
lib.push(Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art: scatter, spacing: (150.0, 150.0), ..Default::default() }) });
|
||||
vectorcraft_brush::store(&mut d, &lib);
|
||||
let mut ap = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
@@ -997,6 +999,8 @@ fn brush_art_draws_renamed_symbols_and_patterns_it_shows() {
|
||||
painted.transform(Affine::translate((0.0, 8.0)), true);
|
||||
let scatter = Node::group(d.alloc_id(), vec![Arc::new(instance), Arc::new(painted)]);
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
// The default library has its own `Dots`, which a stroke would draw with first.
|
||||
lib.retain(|b| b.name != "Dots");
|
||||
lib.push(Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art: scatter, spacing: (150.0, 150.0), ..Default::default() }) });
|
||||
vectorcraft_brush::store(&mut d, &lib);
|
||||
let mut ap = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//! The pieces a raster mesh warp cuts an image into (envelopes, Effect › Warp) overlap their
|
||||
//! neighbors: a partly transparent image keeps its own alpha where they do.
|
||||
|
||||
use crate::*;
|
||||
use vectorcraft_doc::live::mesh_warp_image;
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
/// A 4 × 4 px red PNG, every pixel `alpha` opaque.
|
||||
fn png(alpha: u8) -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, alpha]));
|
||||
let mut out = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// The image of [`png`] over (10, 10)–(90, 90), pushed through `f` as 4 × 4 cells (with `masked`,
|
||||
/// as Preserve Shape Using Transparency cuts it), on a page of 100 × 100 pt, after `tweak`
|
||||
/// adjusts the warped group.
|
||||
fn warped(f: &dyn Fn(Point) -> Point, masked: bool, pixelated: bool, tweak: impl FnOnce(&mut Node)) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.images.insert("pic".into(), ImageBlob::png(png(128)));
|
||||
let im = ImageObject {
|
||||
key: "pic".into(),
|
||||
width: 4,
|
||||
height: 4,
|
||||
xf: Affine::translate((10.0, 10.0)) * Affine::scale(20.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im.clone())));
|
||||
let mut g = mesh_warp_image(&n, &im, f, 4, pixelated, masked);
|
||||
tweak(&mut g);
|
||||
d.insert(Some(d.layers[0].id), 0, g).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// `d` at 4 px a point over transparency.
|
||||
fn drawn(d: &Document) -> Rendered {
|
||||
Renderer::new().render(d, 400, 400, Affine::scale(4.0), &RenderOptions { background: None, ..Default::default() })
|
||||
}
|
||||
|
||||
/// The pixels of `r` inside (x0, y0)–(x1, y1) (points) whose alpha is more than 4 off `want`, with
|
||||
/// that alpha: the first few.
|
||||
fn uneven(r: &Rendered, (x0, y0, x1, y1): (u32, u32, u32, u32), want: u8) -> Vec<(u32, u32, u8)> {
|
||||
let mut out = vec![];
|
||||
for y in y0 * 4..y1 * 4 {
|
||||
for x in x0 * 4..x1 * 4 {
|
||||
let a = r.pixel(x, y)[3];
|
||||
if (i32::from(a) - i32::from(want)).abs() > 4 && out.len() < 8 {
|
||||
out.push((x, y, a));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Inside the image, away from its outer edges.
|
||||
const INSIDE: (u32, u32, u32, u32) = (12, 12, 88, 88);
|
||||
|
||||
#[test]
|
||||
fn a_half_transparent_image_is_half_transparent_where_its_warp_pieces_overlap() {
|
||||
let same = |p: Point| p;
|
||||
for masked in [false, true] {
|
||||
for pixelated in [false, true] {
|
||||
let r = drawn(&warped(&same, masked, pixelated, |_| {}));
|
||||
// The cells meet at x and y = 30, 50 and 70, and each cell's diagonal crosses it.
|
||||
assert_eq!(uneven(&r, INSIDE, 128), vec![], "masked {masked}, pixelated {pixelated}");
|
||||
}
|
||||
}
|
||||
// A wave bends every edge between the pieces.
|
||||
let wave = |p: Point| Point::new(p.x + 3.0 * (p.y / 7.0).sin(), p.y + 2.0 * (p.x / 9.0).cos());
|
||||
for masked in [false, true] {
|
||||
let r = drawn(&warped(&wave, masked, false, |_| {}));
|
||||
assert_eq!(uneven(&r, (16, 16, 84, 84), 128), vec![], "waved, masked {masked}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_images_opacity_applies_once_over_the_warp_pieces() {
|
||||
let same = |p: Point| p;
|
||||
for masked in [false, true] {
|
||||
let r = drawn(&warped(&same, masked, false, |g| g.opacity = 0.5));
|
||||
assert_eq!(uneven(&r, INSIDE, 64), vec![], "masked {masked}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A clip group of a half transparent image made by hand, in a knockout group, knocks out by
|
||||
/// where its image is opaque: only the pieces of a warp knock out by their whole triangle.
|
||||
#[test]
|
||||
fn other_clip_groups_in_a_knockout_group_knock_out_by_their_alpha() {
|
||||
let same = |p: Point| p;
|
||||
let d = warped(&same, false, false, |g| {
|
||||
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("a group") };
|
||||
for c in children {
|
||||
Arc::make_mut(c).extras_mut().warp_piece = false;
|
||||
}
|
||||
});
|
||||
let r = drawn(&d);
|
||||
// On the shared edge at x = 30, y = 20: the neighbors' alphas add up there.
|
||||
let a = r.pixel(120, 80)[3];
|
||||
assert!(a > 160, "{a}");
|
||||
}
|
||||
@@ -1178,3 +1178,44 @@ fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() {
|
||||
assert!(!r.charge_fx_instance(&d, &inst), "the next does not");
|
||||
assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES);
|
||||
}
|
||||
|
||||
/// A closed path of 30,000 curves along the x axis, 2 pt apart: drawn with about 420,000 lines,
|
||||
/// and with more than the effect budget's 8 million once scaled 1000 times.
|
||||
fn wavy() -> vectorcraft_geom::PathData {
|
||||
use vectorcraft_geom::{Anchor, PathData, SubPath};
|
||||
let anchors = (0..=30_000)
|
||||
.map(|i| {
|
||||
let x = 2.0 * f64::from(i);
|
||||
Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0))
|
||||
})
|
||||
.collect();
|
||||
PathData::single(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// A Transform effect left out past the effect budget leaves the art where it is, and the drop
|
||||
/// shadow before it (the object's, or the fill's before the fill's own Transform effect) reaches
|
||||
/// as far as it is drawn: by its own offset, not by a thousand times it.
|
||||
#[test]
|
||||
fn a_shadow_before_a_skipped_transform_reaches_as_far_as_it_is_drawn() {
|
||||
let shadow = fx("stylize.dropShadow", json!({"x": 10, "y": 5, "blur": 0}));
|
||||
let big = fx("distort.transform", json!({"scaleH": 100000, "scaleV": 100000}));
|
||||
let path = wavy();
|
||||
let art = path.bounds().unwrap();
|
||||
let mut object = Node::path(NodeId(1), path.clone(), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0));
|
||||
let mut fill = object.clone();
|
||||
object.appearance.effects = vec![shadow.clone(), big.clone()];
|
||||
if let Some(item) = fill.appearance.items.first_mut() {
|
||||
*item.effects_mut() = vec![shadow, big];
|
||||
}
|
||||
let d = Document::new(100.0, 100.0);
|
||||
let symbols = d.symbol_boxes();
|
||||
// Within the shadow's 10 pt on every side (the visual bounds grow each side by the most any
|
||||
// side reaches).
|
||||
let within = |b: Rect| b.x0 >= art.x0 - 11.0 && b.y0 >= art.y0 - 11.0 && b.x1 <= art.x1 + 11.0 && b.y1 <= art.y1 + 11.0;
|
||||
for (what, n) in [("object", &object), ("fill", &fill)] {
|
||||
let b = crate::fx::visual_bounds(&symbols, n).unwrap();
|
||||
assert!(within(b), "{what}: visual {b:?} for art {art:?}");
|
||||
let b = crate::fx::painted_reach(&symbols, n).unwrap();
|
||||
assert!(within(b), "{what}: painted {b:?} for art {art:?}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user