mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 17:46:59 +00:00
Merge pull request #7839 from dotCooCoo/fix/expand-appearance-nested-instance-effects
Expand Appearance: raster effects on a symbol instance's fill or stroke expand to art, nested instances included
This commit is contained in:
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Expand Appearance",
|
||||
["Object"],
|
||||
None,
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
|
||||
can_expand,
|
||||
expand_appearance
|
||||
),
|
||||
@@ -963,16 +963,74 @@ fn is_container(n: &Node) -> bool {
|
||||
|
||||
/// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at
|
||||
/// the document's raster effects resolution or a Rasterize effect's finer one, with whether they
|
||||
/// all paint below it (shadows and outer glows: the image then holds just them). A group's or
|
||||
/// layer's image leaves out its members' raster effects, which are expanded with them. `None`
|
||||
/// when it has none.
|
||||
fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// all paint below it (shadows and outer glows: the image then holds just them, and paints with
|
||||
/// their blend mode when they all use one). A group's or layer's image leaves out its members'
|
||||
/// raster effects, which are expanded with them. `None` when it has none.
|
||||
/// `Err` when that image would take `budget` past its limits: the object then stays as it is.
|
||||
fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result<Option<(Node, bool)>, OverBudget> {
|
||||
let fx = rasterfx::raster_fx(n);
|
||||
if fx.is_empty() {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
let below = fx.iter().all(effects::RasterFx::is_below);
|
||||
Some((rasterfx::raster_image(d, n, below, true)?, below))
|
||||
let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?;
|
||||
let mut image = rasterfx::raster_image(d, n, below, true);
|
||||
if image.is_none() {
|
||||
// No image was made: it takes nothing from the budget.
|
||||
budget.images += 1;
|
||||
budget.pixels += pixels;
|
||||
}
|
||||
// Rendered alone, over nothing, the shadows and glows can't blend with the art below the
|
||||
// object, so the image does, as the canvas draws them.
|
||||
let mut modes = fx.iter().filter_map(effects::RasterFx::mode);
|
||||
if below
|
||||
&& let (Some(mode), Some(image)) = (modes.next(), image.as_mut())
|
||||
&& modes.all(|m| m == mode)
|
||||
{
|
||||
image.blend = mode;
|
||||
}
|
||||
Ok(image.map(|image| (image, below)))
|
||||
}
|
||||
|
||||
/// The most images of raster effects one Expand Appearance makes.
|
||||
const MAX_RASTER_IMAGES: u32 = 1_024;
|
||||
|
||||
/// The most pixels the images of raster effects one Expand Appearance makes hold in all.
|
||||
const MAX_RASTER_PIXELS: u64 = 256_000_000;
|
||||
|
||||
/// The note when objects keep their raster effects because their images would take an Expand
|
||||
/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`].
|
||||
pub(crate) const RASTER_EFFECTS_LEFT: &str =
|
||||
"some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all";
|
||||
|
||||
/// An image of raster effects that would take a [`RasterBudget`] past its limits.
|
||||
#[derive(Debug)]
|
||||
struct OverBudget;
|
||||
|
||||
/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the
|
||||
/// objects whose raster effects it left as they are because their images would go past them.
|
||||
pub(crate) struct RasterBudget {
|
||||
images: u32,
|
||||
pixels: u64,
|
||||
pub(crate) left: usize,
|
||||
}
|
||||
|
||||
impl RasterBudget {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 }
|
||||
}
|
||||
|
||||
/// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return
|
||||
/// them; `Err`, with its object counted in `left`, when it would go past what is left.
|
||||
fn take(&mut self, pixels: u64) -> std::result::Result<u64, OverBudget> {
|
||||
if self.images == 0 || pixels > self.pixels {
|
||||
self.left += 1;
|
||||
return Err(OverBudget);
|
||||
}
|
||||
self.images -= 1;
|
||||
self.pixels -= pixels;
|
||||
Ok(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
|
||||
@@ -983,6 +1041,7 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
m: &mut Node,
|
||||
@@ -991,6 +1050,7 @@ fn expand_pieces(
|
||||
skip: &[NodeId],
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
let id = m.id;
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
@@ -1005,7 +1065,7 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes, skip));
|
||||
listed = Some(expand_in_place(d, c, brushes, skip, raster));
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
@@ -1030,37 +1090,65 @@ fn expand_pieces(
|
||||
}
|
||||
|
||||
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
|
||||
/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as
|
||||
/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so
|
||||
/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more
|
||||
/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art
|
||||
/// would take the objects placed so far past `budget`.
|
||||
fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) {
|
||||
/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`],
|
||||
/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in
|
||||
/// that art in turn, so [`expand_pieces`] bakes their effects with the rest.
|
||||
fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) {
|
||||
for c in m.children_mut().into_iter().flatten() {
|
||||
if !matches!(c.kind, NodeKind::SymbolInstance { .. }) {
|
||||
if c.children().is_some() {
|
||||
expand_nested_instances(d, Arc::make_mut(c), depth, budget);
|
||||
expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue };
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) {
|
||||
continue;
|
||||
}
|
||||
let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue };
|
||||
let count = sym.art.count() as u64;
|
||||
if count > *budget {
|
||||
continue;
|
||||
}
|
||||
*budget -= count;
|
||||
let art = vectorcraft_render::instance_art(&sym.art, c);
|
||||
if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) {
|
||||
expand_nested_instances(d, &mut a, depth + 1, budget);
|
||||
if let Some(a) = expanded_instance(d, c, depth, budget, raster) {
|
||||
*c = Arc::new(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster
|
||||
/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art
|
||||
/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as
|
||||
/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when
|
||||
/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance
|
||||
/// staying as it is, when its active fill and stroke have no such effect, it is more than
|
||||
/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would
|
||||
/// take the objects placed so far past `budget`, or the image of its raster effects would take
|
||||
/// `raster` past its limits. When that image can't be made, they stay on the art its geometry
|
||||
/// effects make, and without one it stays as it is.
|
||||
fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None };
|
||||
let has_raster = effects::has_instance_row_raster(c);
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) {
|
||||
return None;
|
||||
}
|
||||
let sym = d.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let count = sym.art.count() as u64;
|
||||
if count > *budget {
|
||||
return None;
|
||||
}
|
||||
let art = vectorcraft_render::instance_art(&sym.art, c);
|
||||
let image = if has_raster { raster_image(d, c, raster).ok()? } else { None };
|
||||
*budget -= count;
|
||||
let mut v = c.clone();
|
||||
if image.is_some() {
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
}
|
||||
let below = match image {
|
||||
Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)),
|
||||
Some((image, true)) => Some(image),
|
||||
None => None,
|
||||
};
|
||||
let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art))
|
||||
.or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?;
|
||||
expand_nested_instances(d, &mut a, depth + 1, budget, raster);
|
||||
if let Some(image) = below {
|
||||
rasterfx::put_below(d, &mut a, image);
|
||||
}
|
||||
Some(a)
|
||||
}
|
||||
|
||||
/// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids?
|
||||
fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
@@ -1075,9 +1163,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
type Listed = (NodeId, usize);
|
||||
|
||||
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Vec<Listed> {
|
||||
let mut listed = vec![];
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed, raster) {
|
||||
*c = e;
|
||||
}
|
||||
listed
|
||||
@@ -1099,18 +1187,26 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
|
||||
/// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and
|
||||
/// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art),
|
||||
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
|
||||
/// transparency.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
|
||||
expand_node_except(d, id, brushes, &[], out);
|
||||
/// transparency. An object whose raster effects' image would take `raster` past its limits stays
|
||||
/// as it is, with what is inside it.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>, raster: &mut RasterBudget) {
|
||||
expand_node_except(d, id, brushes, &[], out, raster);
|
||||
}
|
||||
|
||||
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
|
||||
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
|
||||
/// copies of it that such an effect makes are left as they are too.
|
||||
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
|
||||
fn expand_node_except(
|
||||
d: &mut Document,
|
||||
id: NodeId,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
out: &mut Vec<NodeId>,
|
||||
raster: &mut RasterBudget,
|
||||
) {
|
||||
let Some(n) = d.node(id).cloned() else { return };
|
||||
let mut listed = vec![];
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed);
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed, raster);
|
||||
out.extend(listed.into_iter().map(|(id, _)| id));
|
||||
if let Some(mut m) = m {
|
||||
// Art made from type takes its emoji's pixels into the document.
|
||||
@@ -1124,11 +1220,20 @@ fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
|
||||
fn expanded_node(
|
||||
d: &mut Document,
|
||||
mut n: Node,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
out: &mut Vec<Listed>,
|
||||
raster: &mut RasterBudget,
|
||||
) -> Option<Node> {
|
||||
let id = n.id;
|
||||
if skip.contains(&id) || !expandable(&n) {
|
||||
return None;
|
||||
}
|
||||
// What `out` held before `n`: an object left by the raster budget lists nothing.
|
||||
let listed_before = out.len();
|
||||
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
|
||||
// recoloured copy), then the rest of the appearance expands.
|
||||
let mut changed = false;
|
||||
@@ -1141,6 +1246,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
|
||||
// is: the recolored copies the adjustment adds then go again.
|
||||
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
|
||||
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
|
||||
if effects::has_adjustment(&n)
|
||||
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
|
||||
{
|
||||
@@ -1163,7 +1272,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
expanded = expand_in_place(d, c, brushes, skip);
|
||||
expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1186,7 +1295,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
return Some(m);
|
||||
}
|
||||
let image = raster_image(d, &n);
|
||||
// Raster effects whose image would go past the budget stay: so does the object, with what is
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
|
||||
let Ok(image) = raster_image(d, &n, raster) else {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
return None;
|
||||
};
|
||||
let mut v = n.clone();
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
let mut stroke_art =
|
||||
@@ -1206,7 +1323,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
@@ -1224,10 +1341,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
|
||||
// A symbol instance whose active fill or stroke has only effects that paint below it
|
||||
// (now in the image) becomes its art as well.
|
||||
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
|
||||
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
|
||||
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
|
||||
outlined.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
};
|
||||
@@ -1262,7 +1384,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
match members.remove(&c.id) {
|
||||
Some(listed) => out.extend(listed),
|
||||
None => {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out, raster) {
|
||||
*c = Arc::new(e);
|
||||
changed = true;
|
||||
}
|
||||
@@ -1336,6 +1458,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let mut raster = RasterBudget::new();
|
||||
let ids = s.edit("Expand Appearance", |d, _| {
|
||||
let before = d.clone();
|
||||
// The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose
|
||||
@@ -1351,7 +1474,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = vec![];
|
||||
let threaded = super::threads::frames(d);
|
||||
for id in &roots {
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out);
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out, &mut raster);
|
||||
}
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was replaced stays where it was, no longer linked.
|
||||
@@ -1360,6 +1483,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// stays type under a new id takes its frame's place.
|
||||
super::threads::leave_threads(d, &threaded);
|
||||
if out.is_empty() || (kept && d.layers == before.layers) {
|
||||
if raster.left > 0 {
|
||||
return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into()));
|
||||
}
|
||||
return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into()));
|
||||
}
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?;
|
||||
@@ -1367,8 +1493,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
let mut out = json!({ "ids": ids_json(&ids) });
|
||||
// Raster effects become images rendered from the art.
|
||||
if let Some(w) = rasterfx::undecoded_warning(failed) {
|
||||
out["warning"] = json!(w);
|
||||
let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect();
|
||||
if !warnings.is_empty() {
|
||||
out["warning"] = json!(warnings.join("; "));
|
||||
}
|
||||
if raster.left > 0 {
|
||||
out["rasterLeft"] = json!(raster.left);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -1082,3 +1082,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
|
||||
let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
|
||||
assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
|
||||
}
|
||||
|
||||
/// The raster budget charges each image its pixels before it is made: an image past what is left
|
||||
/// is refused and counted, and the object keeps its blur.
|
||||
#[test]
|
||||
fn an_image_past_the_pixels_left_stays_unmade() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap();
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let n = d.node(id).cloned().unwrap();
|
||||
let pixels = super::rasterfx::raster_pixels(&d, &n, false, true);
|
||||
assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}");
|
||||
|
||||
let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err());
|
||||
assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken");
|
||||
|
||||
let mut budget = super::RasterBudget { images: 10, pixels, left: 0 };
|
||||
let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made");
|
||||
let NodeKind::Image(img) = &image.kind else { panic!("not an image") };
|
||||
assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size");
|
||||
assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0));
|
||||
|
||||
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
|
||||
}
|
||||
|
||||
@@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
let one = super::save::artboard_doc(doc, b);
|
||||
let (full, placed) = crate::cmd::place::document::full_documents(&one);
|
||||
let mut d = full.into_owned();
|
||||
expand_appearances(&mut d);
|
||||
if expand_appearances(&mut d) {
|
||||
note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT);
|
||||
}
|
||||
if mode == SeeThrough::Flatten {
|
||||
expand_image_patterns(&mut d)?;
|
||||
}
|
||||
@@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// Expand Appearance of every layer's art whose appearance the format can't hold.
|
||||
fn expand_appearances(d: &mut Document) {
|
||||
/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether
|
||||
/// objects kept raster effects whose images would go past Expand Appearance's limits.
|
||||
fn expand_appearances(d: &mut Document) -> bool {
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
|
||||
let mut out = vec![];
|
||||
let mut raster = super::super::effectcmd::RasterBudget::new();
|
||||
for id in layers {
|
||||
super::super::effectcmd::expand_node(d, id, &brushes, &mut out);
|
||||
super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster);
|
||||
}
|
||||
raster.left > 0
|
||||
}
|
||||
|
||||
/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint,
|
||||
|
||||
@@ -174,19 +174,14 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 {
|
||||
(doc.raster_effects_ppi / 72.0).clamp(1.0 / 72.0, 2400.0 / 72.0)
|
||||
}
|
||||
|
||||
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
|
||||
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
|
||||
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
|
||||
/// of the image, which then only holds what the effects add around it (a shadow to go under the
|
||||
/// vector object). The document's raster effects settings add room around it and finish its pixels.
|
||||
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
|
||||
/// positive, or when its PNG can't be encoded.
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
/// The region [`effect_image`] renders `whole` over in `d`, and the scale it renders at (`scale`, or
|
||||
/// less for an image past 64 Mpx or a side the renderer can't address). `None` when it paints
|
||||
/// nothing, when the area it covers overflows `f64` or the scale is not positive.
|
||||
fn effect_region(d: &Document, whole: &Node, scale: f64) -> Option<(Rect, f64)> {
|
||||
// What it paints (its members' effects included), and how far its fills' and strokes' raster
|
||||
// effects reach beyond that.
|
||||
let b = vectorcraft_render::painted_bounds(out, whole)?;
|
||||
let look = out.raster_effects.clone();
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around;
|
||||
let b = vectorcraft_render::painted_bounds(d, whole)?;
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + d.raster_effects.add_around;
|
||||
let b = b.inflate(reach, reach);
|
||||
// An area too large for f64 gives a zero scale and an image transform that is not finite.
|
||||
let area = b.width() * b.height();
|
||||
@@ -201,6 +196,19 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N
|
||||
return None;
|
||||
}
|
||||
let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale);
|
||||
Some((region, scale))
|
||||
}
|
||||
|
||||
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
|
||||
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
|
||||
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
|
||||
/// of the image, which then only holds what the effects add around it (a shadow to go under the
|
||||
/// vector object). The document's raster effects settings add room around it and finish its pixels.
|
||||
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
|
||||
/// positive, or when its PNG can't be encoded.
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
let (region, scale) = effect_region(out, whole, scale)?;
|
||||
let look = out.raster_effects.clone();
|
||||
// Anti-alias off: hard edges (the effects themselves stay smooth).
|
||||
let anti_alias = if look.anti_alias { AntiAlias::Art } else { AntiAlias::None };
|
||||
let mut img = render(out, vec![whole.clone()], region, scale, anti_alias);
|
||||
@@ -311,6 +319,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
if !below && let Some(image) = rasterize_effect_image(d, n) {
|
||||
return Some(image);
|
||||
}
|
||||
let whole = effect_art(n, below, members);
|
||||
let bare = below.then(|| {
|
||||
let mut b = whole.clone();
|
||||
strip_raster(&mut b, false);
|
||||
b
|
||||
});
|
||||
effect_image(d, &whole, bare.as_ref(), image_scale(d, n))
|
||||
}
|
||||
|
||||
/// The art [`raster_image`] renders the raster effects of `n` from with `below` and `members`:
|
||||
/// `n` without its transparency, a group's or layer's members without their raster effects when
|
||||
/// both are set.
|
||||
fn effect_art(n: &Node, below: bool, members: bool) -> Node {
|
||||
let mut whole = n.clone();
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
@@ -319,17 +340,39 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
strip_raster(Arc::make_mut(c), true);
|
||||
}
|
||||
}
|
||||
let bare = below.then(|| {
|
||||
let mut b = whole.clone();
|
||||
strip_raster(&mut b, false);
|
||||
b
|
||||
});
|
||||
// A Rasterize effect at a finer resolution than the document's is rendered at its own.
|
||||
let scale = raster_fx(n)
|
||||
.iter()
|
||||
.filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None })
|
||||
.fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0));
|
||||
effect_image(d, &whole, bare.as_ref(), scale)
|
||||
whole
|
||||
}
|
||||
|
||||
/// Pixels per point of the image of the raster effects of `n`: the document's raster effects
|
||||
/// resolution, or a Rasterize effect's finer one, which is rendered at its own.
|
||||
fn image_scale(d: &Document, n: &Node) -> f64 {
|
||||
raster_fx(n).iter().filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }).fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0))
|
||||
}
|
||||
|
||||
/// The pixels of the image [`raster_image`] makes of the raster effects of `n` in `d` with `below`
|
||||
/// and `members`, as [`effect_image`] sizes it, or at the resolution and with the room around the
|
||||
/// art of the object's own Rasterize effect when that is its only one ([`rasterize_effect_image`]);
|
||||
/// 0 when it paints nothing.
|
||||
pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool) -> u64 {
|
||||
if !below && let Some((art, r, _)) = rasterize_effect_art(d, n) {
|
||||
// Measured as Object › Rasterize measures it.
|
||||
let scale = r.ppi.unwrap_or(d.raster_effects_ppi) / 72.0;
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
let size = vectorcraft_render::drawn_bounds(d, &art).map(|b| {
|
||||
let b = b.inflate(r.add_around, r.add_around);
|
||||
((b.width() * scale).ceil().max(1.0), (b.height() * scale).ceil().max(1.0))
|
||||
});
|
||||
// Past Object › Rasterize's limits that image is not made, and the effect's image is.
|
||||
if let Some((w, h)) = size
|
||||
&& w * h <= super::menucmds::MAX_PIXELS
|
||||
&& w <= side
|
||||
&& h <= side
|
||||
{
|
||||
return (w * h) as u64;
|
||||
}
|
||||
}
|
||||
effect_region(d, &effect_art(n, below, members), image_scale(d, n))
|
||||
.map_or(0, |(r, scale)| ((r.width() * scale).round() * (r.height() * scale).round()) as u64)
|
||||
}
|
||||
|
||||
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
|
||||
@@ -339,15 +382,7 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
|
||||
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
|
||||
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let n = staged.as_ref().map_or(n, |(stage, _)| stage);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let (whole, r, map) = rasterize_effect_art(d, n)?;
|
||||
let p = json!({
|
||||
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
|
||||
"colorModel": r.color_model.id(),
|
||||
@@ -356,20 +391,39 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
"clippingMask": r.clipping_mask,
|
||||
"addAround": r.add_around,
|
||||
});
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
// shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the
|
||||
// image's transparency would need one too; upgrade when CMYK images carry alpha.
|
||||
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
|
||||
let mut image = image.into_node(d);
|
||||
if let Some((_, map)) = staged {
|
||||
if let Some(map) = map {
|
||||
image.transform(map, false);
|
||||
}
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
|
||||
/// that move the image, without the Rasterize effect and without its transparency; that effect's
|
||||
/// options; and the map those Transform effects move the image by. `None` when `n` has another
|
||||
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
|
||||
/// flatten the image.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
|
||||
let n = stage.as_ref().unwrap_or(n);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
Some((whole, r, map))
|
||||
}
|
||||
|
||||
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
|
||||
/// image takes its place with its id, name and transparency (a layer keeps the image as its only
|
||||
/// member).
|
||||
|
||||
@@ -455,10 +455,11 @@ fn a_symbol_instance_fill_shadow_shadows_its_filled_art() {
|
||||
|
||||
assert!(expandable(&s), "the fill's shadow can be expanded");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let ch = node(&s, id).children().cloned().expect("the instance becomes a group");
|
||||
let n = node(&s, id);
|
||||
let ch = n.children().cloned().expect("the instance becomes a group");
|
||||
assert!(matches!(ch[0].kind, NodeKind::Image(_)), "the shadow is an image under the art: {}", ch[0].kind_label());
|
||||
assert!(matches!(ch[1].kind, NodeKind::SymbolInstance { .. }), "the art stays an instance: {}", ch[1].kind_label());
|
||||
no_effects_left(&ch[1]);
|
||||
n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the art is no longer an instance"));
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
@@ -508,6 +509,311 @@ fn a_nested_symbol_instance_takes_the_outer_fill_shadow() {
|
||||
assert!(dark(render(&s).pixel(165, 100)), "the inner art casts the shadow: {:?}", render(&s).pixel(165, 100));
|
||||
}
|
||||
|
||||
/// An instance of an Inner symbol of the square, with a new fill without paint on top that `inner`
|
||||
/// gives effects, placed in the art of an Outer symbol; the Outer instance is selected, with a new
|
||||
/// fill without paint on top. Returns the Outer instance and its new row's index.
|
||||
fn nested_with_row(s: &mut Session, inner: impl FnOnce(&mut Session, NodeId, usize)) -> (NodeId, usize) {
|
||||
let (inner_id, inner_row) = instance_with_row(s, "Inner", true);
|
||||
inner(s, inner_id, inner_row);
|
||||
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
|
||||
run(s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(s, id).appearance.items.len() - 1;
|
||||
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
|
||||
(id, row)
|
||||
}
|
||||
|
||||
/// The symbol instances and the images in `n`.
|
||||
fn instances_and_images(n: &Node) -> (usize, usize) {
|
||||
let mut found = (0, 0);
|
||||
n.walk(&mut |part| match part.kind {
|
||||
NodeKind::SymbolInstance { .. } => found.0 += 1,
|
||||
NodeKind::Image(_) => found.1 += 1,
|
||||
_ => {}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Replace the art of every symbol with an empty group.
|
||||
fn empty_symbols(s: &mut Session) {
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
for (i, sym) in d.symbols.iter_mut().enumerate() {
|
||||
sym.art = std::sync::Arc::new(Node::group(NodeId(91_000 + i as u64), vec![]));
|
||||
}
|
||||
}
|
||||
|
||||
/// When the outer instance's art expands, an instance in it whose own fill has a shadow becomes art
|
||||
/// too, the shadow an image under it: no instance or effect is left, the look stays, and the result
|
||||
/// no longer follows either symbol.
|
||||
#[test]
|
||||
fn a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(175, 100)), "the inner art casts its shadow: {:?}", before.pixel(175, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert!(images >= 1, "the inner shadow is an image");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
empty_symbols(&mut s);
|
||||
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
|
||||
}
|
||||
|
||||
/// A shadow on the outer instance's fill alone: the instance becomes its art over the shadow's
|
||||
/// image, and an instance in that art with a shadow of its own becomes art and an image in turn, in
|
||||
/// one undo step.
|
||||
#[test]
|
||||
fn an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
shadow_row(&mut s, id, row);
|
||||
let before = render(&s);
|
||||
assert!(expandable(&s));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert!(images >= 2, "the outer and inner shadows are images: {images}");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back");
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
empty_symbols(&mut s);
|
||||
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
|
||||
}
|
||||
|
||||
/// A blur on the nested instance's fill: the nested instance becomes the image.
|
||||
#[test]
|
||||
fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() {
|
||||
let mut s = session();
|
||||
let blur = |s: &mut Session, id: NodeId, row: usize| {
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, blur);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert_eq!(images, 1, "the blurred inner art is one image");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A blue rectangle from x 140 to 200, drawn first, so a shadow right of the square falls on it.
|
||||
fn blue_backdrop(s: &mut Session) {
|
||||
run(s, "shape.rectangle", json!({"x": 140, "y": 0, "width": 60, "height": 200}));
|
||||
run(s, "paint.setFill", json!({"color": "#0000ff"}));
|
||||
}
|
||||
|
||||
/// A red Drop Shadow 20 pt to the right on row `row` of instance `id`, with no blur, painting with `mode`.
|
||||
fn red_shadow_row(s: &mut Session, id: NodeId, row: usize, mode: &str) {
|
||||
let params = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": mode, "color": "#ff0000"});
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "stylize.dropShadow", "params": params}));
|
||||
}
|
||||
|
||||
/// The blend modes of the images in `n`, in the order the walk visits them.
|
||||
fn image_modes(n: &Node) -> Vec<BlendMode> {
|
||||
let mut modes = vec![];
|
||||
n.walk(&mut |part| {
|
||||
if matches!(part.kind, NodeKind::Image(_)) {
|
||||
modes.push(part.blend);
|
||||
}
|
||||
});
|
||||
modes
|
||||
}
|
||||
|
||||
/// A Multiply shadow on the nested instance's fill: its image multiplies with the blue art below
|
||||
/// as the shadow did, rather than painting red over it.
|
||||
#[test]
|
||||
fn a_nested_instance_multiply_shadow_image_keeps_its_mode() {
|
||||
let mut s = session();
|
||||
blue_backdrop(&mut s);
|
||||
let (id, row) = nested_with_row(&mut s, |s, id, row| red_shadow_row(s, id, row, "multiply"));
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(170, 100)), "red multiplied with blue is dark: {:?}", before.pixel(170, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n).0, 0, "the outer and inner instances become art");
|
||||
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(dark(after.pixel(170, 100)), "the image multiplies with the blue art: {:?}", after.pixel(170, 100));
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A Multiply shadow on an instance's own fill: the image under its art paints with Multiply.
|
||||
#[test]
|
||||
fn an_instance_multiply_shadow_image_keeps_its_mode() {
|
||||
let mut s = session();
|
||||
blue_backdrop(&mut s);
|
||||
let (id, row) = instance_with_row(&mut s, "Square", true);
|
||||
red_shadow_row(&mut s, id, row, "multiply");
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(160, 100)), "red multiplied with blue is dark: {:?}", before.pixel(160, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
|
||||
let after = render(&s);
|
||||
assert!(dark(after.pixel(160, 100)), "the image multiplies with the blue art: {:?}", after.pixel(160, 100));
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it.
|
||||
#[test]
|
||||
fn a_hidden_nested_instance_fill_shadow_makes_no_image() {
|
||||
let mut s = session();
|
||||
let hidden = |s: &mut Session, id: NodeId, row: usize| {
|
||||
shadow_row(s, id, row);
|
||||
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "visible": false}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, hidden);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert!(!dark(render(&s).pixel(175, 100)), "the hidden fill casts no shadow");
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (0, 0), "the instances become art without an image");
|
||||
no_effects_left(&n);
|
||||
}
|
||||
|
||||
/// A nested instance with a shadow whose symbol is missing stays as it is while the outer art
|
||||
/// expands around it.
|
||||
#[test]
|
||||
fn a_nested_instance_of_a_missing_symbol_stays_an_instance() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.symbols.retain(|sym| sym.name != "Inner");
|
||||
}
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image");
|
||||
}
|
||||
|
||||
/// 1,100 blurred instances in the outer art, far fewer objects than the symbol limit: one Expand
|
||||
/// Appearance makes 1,024 images of them, and the other 76 stay instances with their blur, which
|
||||
/// the result reports.
|
||||
#[test]
|
||||
fn nested_instance_raster_effects_stop_at_the_image_limit() {
|
||||
let mut s = session();
|
||||
// Images of a pixel or two each.
|
||||
run(&mut s, "document.rasterEffectsSettings", json!({"resolution": 1}));
|
||||
let blur = |s: &mut Session, id: NodeId, row: usize| {
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, blur);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let outer = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap();
|
||||
let inner = (*d.symbols[outer].art).clone();
|
||||
assert!(matches!(inner.kind, NodeKind::SymbolInstance { .. }), "the outer art is the inner instance");
|
||||
let copies = (0..1_100)
|
||||
.map(|_| {
|
||||
let mut copy = inner.clone();
|
||||
copy.id = d.alloc_id();
|
||||
std::sync::Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
d.symbols[outer].art = std::sync::Arc::new(Node::group(d.alloc_id(), copies));
|
||||
}
|
||||
|
||||
let r = run(&mut s, "effect.expandAppearance", json!({}));
|
||||
assert_eq!(r["rasterLeft"], 76, "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("1,024 images")), "{r}");
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (76, 1_024), "1,024 instances become images and the rest stay");
|
||||
n.walk(&mut |part| {
|
||||
if matches!(part.kind, NodeKind::SymbolInstance { .. }) {
|
||||
assert!(part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "blur.gaussian")), "a left instance keeps its blur");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Gives `id` a color adjustment and a blur, puts it in a group above 1,024 blurred squares, which
|
||||
/// take every image one Expand Appearance makes, and expands the group. Returns `id` as it was
|
||||
/// before expanding.
|
||||
fn adjusted_and_left_by_the_image_limit(s: &mut Session, id: NodeId) -> Node {
|
||||
// Images of a pixel or two each.
|
||||
run(s, "document.rasterEffectsSettings", json!({"resolution": 1}));
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}}));
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
let sq = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap());
|
||||
run(s, "effect.apply", json!({"ids": [sq.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
let before = node(s, id);
|
||||
let group = {
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let blurred = d.node(sq).unwrap().clone();
|
||||
d.remove(sq).unwrap();
|
||||
let mut members: Vec<_> = (0..1_024)
|
||||
.map(|_| {
|
||||
let mut copy = blurred.clone();
|
||||
copy.id = d.alloc_id();
|
||||
std::sync::Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
members.push(std::sync::Arc::new(before.clone()));
|
||||
let group = d.alloc_id();
|
||||
*d.node_mut(id).unwrap() = Node::group(group, members);
|
||||
group
|
||||
};
|
||||
|
||||
let r = run(s, "effect.expandAppearance", json!({"ids": [group.0]}));
|
||||
assert_eq!(r["rasterLeft"], 1, "{r}");
|
||||
before
|
||||
}
|
||||
|
||||
/// A symbol instance with a color adjustment and a blur, left by the image limit, stays an instance
|
||||
/// of its symbol, with both effects.
|
||||
#[test]
|
||||
fn a_color_adjusted_instance_left_by_the_image_limit_stays_an_instance() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Adjusted Square"}))["id"].as_u64().unwrap());
|
||||
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
|
||||
assert!(matches!(before.kind, NodeKind::SymbolInstance { .. }));
|
||||
assert_eq!(node(&s, id), before, "the instance stays as it is, with its adjustment and blur");
|
||||
}
|
||||
|
||||
/// An embedded image with a color adjustment and a blur, left by the image limit, stays as it is,
|
||||
/// and the document keeps no recolored copy of its pixels.
|
||||
#[test]
|
||||
fn a_color_adjusted_image_left_by_the_image_limit_adds_no_pixels() {
|
||||
let mut s = session();
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let images: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect();
|
||||
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
|
||||
assert!(matches!(before.kind, NodeKind::Image(_)));
|
||||
assert_eq!(node(&s, id), before, "the image stays as it is, with its adjustment and blur");
|
||||
// Besides the squares' images, the document holds the image's pixels alone.
|
||||
let after: Vec<String> = s.doc().unwrap().doc.images.keys().filter(|k| !k.starts_with("raster-effect-")).cloned().collect();
|
||||
assert_eq!(after, images, "no recolored copy stays in the document");
|
||||
}
|
||||
|
||||
/// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the
|
||||
/// shadow on the art's fill, not its stroke, and PDF export makes an image of it.
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user