Merge upstream main to resolve PR #6601 documentation conflicts

This commit is contained in:
yoriswind
2026-11-18 02:41:17 -08:00
638 changed files with 58595 additions and 3760 deletions
+5 -9
View File
@@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
use crate::distort::{transform_move, transform_offsets};
use crate::group::{has_own_paint, paints};
use crate::reshape::{
as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves,
as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text,
paint_type_clip, reshape_leaves,
};
use crate::{
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
@@ -502,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
{
return None;
}
let (bp, rule) = crate::clip_outline(first)?;
let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default());
if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind {
(*r, *clipping) = (rule, true);
}
clip.name = first.name.clone();
clip.visible = first.visible;
let clip = clip_region_path(first)?;
let paint = first.clip_paint();
// The type's fills and strokes as art: baked with the type's id, as the renderer draws them,
// then given ids of their own.
@@ -532,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
return Some(m);
};
// `n` keeps its id, name and transparency, and holds the clip group and the strokes over it.
let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
knockout_inside(&mut m, &mut inner);
match &mut m.kind {
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => {
*children = vec![Arc::new(inner), stroke];
+5 -2
View File
@@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
let mut shadowed = type_node(55);
shadowed.opacity = 0.5;
shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({})));
// Type that clips a group is outlined as the plain outlines it clips by.
// Type that clips a group is outlined as a plain path of the region it clips by.
let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true });
g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]);
@@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
let b = o.geometric_bounds().unwrap();
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap();
assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}");
assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}");
// The region is copied with the type.
let b = clipped.geometric_bounds().unwrap();
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
}
#[test]
+8 -2
View File
@@ -189,7 +189,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
@@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}",
json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}),
),
g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})),
g(
"distort.twist",
"Twist…",
DT,
"{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.",
json!({"angle": 10.0}),
),
g(
"distort.zigZag",
"Zig Zag…",
+34 -4
View File
@@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat
use vectorcraft_pathops::addons::pathtools::insert_at;
use crate::util::{
catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
};
fn diag(b: Rect) -> f64 {
@@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
/// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow
/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069).
/// the rotation's directional derivative, including each side of the outer circle.
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
if ang == 0.0 {
@@ -336,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
}
let c = b.center();
let r = diag(b) / 2.0;
let half = Vec2::new(b.width() * 0.5, b.height() * 0.5);
let boundary = move |p: Point, length: f64| {
if length == r {
return true;
}
if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r {
return false;
}
// A bounds-relative distance identifies boundary points affected by center rounding.
(Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r
};
let f = move |q: Point| {
let d = q - c;
let t = (1.0 - d.hypot() / r).max(0.0);
let length = d.hypot();
let t = (1.0 - length / r).max(0.0);
// y runs down, so a positive turn is clockwise on the page.
let a = ang * t;
if a == 0.0 {
return q;
}
let (s, co) = a.sin_cos();
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
};
let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
map_smooth_within(path, piece, max, f)
map_handles_within(path, piece, max, f, |p, h| {
let v = h - p;
if !v.hypot().is_finite() {
return f(p);
}
let d = p - c;
let length = d.hypot();
let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 };
// The clamped rotation has different inward and outward derivatives at the circle.
let inside = if boundary(p, length) { radial < 0.0 } else { length < r };
let gradient = if inside { -ang / r * radial } else { 0.0 };
let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient };
let a = ang * (1.0 - length / r).max(0.0);
let (s, co) = a.sin_cos();
f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co)
})
}
const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4;
+34 -8
View File
@@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &S
// Every path of the outline art, at any depth, is drawn inside the object's opacity
// and blend mode. A symbol's art comes with the live objects and the instances of
// other symbols inside it given as their art, and the type inside it outlined, so the
// art has nothing left for `hook` to give.
// art has nothing left for `hook` to give. Its fills and strokes carry the geometry
// effects of the instance's active fill and stroke, as the canvas draws them.
if let Some(h) = hook
&& let Some(art) = h(n)
{
let art = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => {
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::add_instance_row_effects(doc, n, &mut art);
crate::reshape::outline_nested_text(doc, &mut art, false);
transparency_into_members(&mut art);
art
@@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &S
}
}
/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and
/// the instances of other symbols inside it given as their art
/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry
/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]).
fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node {
let drawn = |m: &Node| {
let mut a = hook(m)?;
crate::reshape::add_instance_row_effects(doc, m, &mut a);
Some(a)
};
crate::reshape::symbol_art_with(art, &drawn, nodes, symbol)
}
/// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is
/// not Normal.
fn within(l: &mut Node, n: &Node) {
@@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
}
},
// A symbol instance with a warp: its symbol's art placed by the instance, with the type
// inside it outlined, reshaped as one piece, as the renderer draws it.
// inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes
// of the art then carry the geometry effects of the instance's active fill and stroke.
NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => {
let h = hook?;
let art = h(n).filter(|art| nodes.charge(art))?;
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::outline_nested_text(doc, &mut art, false);
members_as_drawn(doc, &mut art);
crate::reshape::add_instance_row_effects(doc, n, &mut art);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
// The art's own fills and strokes follow the effects as its members do.
if carry.moves(&art.appearance) {
@@ -703,6 +720,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
}
}
fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) {
// A clip group whose clipping type's strokes paint around it is outlined as that clip
// group: the strokes outside the clip add nothing.
if let Some(inner) = crate::reshape::painted_clip_inner(n) {
return members(doc, inner, out);
}
// A clip group shows its members only inside its clipping path: its outline is that
// region, not the clipped members' own shapes, which may reach far outside it (#7289).
if n.clips() {
@@ -902,14 +924,18 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?;
if paint {
let shapes = member_shapes(doc, &m);
let bounds = m.geometric_bounds();
// A clip group whose clipping type paints strokes is now a group of a clip group and those
// strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
// that clip group. Such groups among the members are measured as their clip groups.
let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some();
let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m));
let art =
|items: &[AppearanceItem]| -> Vec<Arc<Node>> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() };
let (below, above) = m.appearance.split_contents();
let (below, above) = (art(below), art(above));
let at = usize::from(m.clips());
if let Some(ch) = m.children_mut() {
let at = usize::from(wrapped || m.clips());
let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) };
if let Some(ch) = target.and_then(Node::children_mut) {
let at = at.min(ch.len());
ch.splice(at..at, below);
ch.extend(above);
+2 -2
View File
@@ -105,8 +105,8 @@ pub use solids::{
validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
graphics_reshaped_after, rename_appearance_graphic_symbol,
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale,
graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
+194 -44
View File
@@ -387,7 +387,7 @@ fn row_effects_of(fx: &[Effect]) -> Vec<Effect> {
/// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its
/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no
/// instance in the art takes them.
fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects));
let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects));
@@ -613,32 +613,101 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced {
/// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`]
/// makes along its frame or, for those whose first effect is Outline Object, along the outline of
/// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the
/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches
/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and
/// the image's pixels in `doc` when the image does not hold them.
/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry
/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint
/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect
/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when
/// the image does not hold them.
pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return vec![];
}
let Some(art) = reshape(doc, n, None) else { return vec![] };
let mut out = vec![];
art.walk(&mut |c| {
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
let Some(g) = c.stroke_path() else { return };
let ctx = GeomContext { doc, ..GeomContext::of(c) };
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
let fx = item.effects();
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
} else {
g.clone()
};
out.push((shape, *rule, item.clone()));
}
});
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
let mut budget = SYMBOL_ART_MAX_NODES;
instance_paint(doc, n, 1, &mut budget, &mut out);
return out;
}
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return out;
}
let Some(art) = reshape(doc, n, None) else { return out };
art.walk(&mut |c| push_painted(doc, c, &mut out));
out
}
/// The shapes that the fills and strokes of path or compound path `c` paint, each with the
/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects.
fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
let Some(g) = c.stroke_path() else { return };
let ctx = GeomContext { doc, ..GeomContext::of(c) };
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
let fx = item.effects();
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
} else {
g.clone()
};
out.push((shape, *rule, item.clone()));
}
}
/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of
/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it,
/// each with its own geometry effects and those of each fill and stroke applied
/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of
/// the groups and layers in the art paint and the results of their Pathfinder effects
/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the
/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn.
/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of
/// Shaper groups add nothing, and neither does an instance more than
/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured
/// so far past `budget`.
fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) {
return;
}
let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return };
let count = sym.art.count() as u64;
if count > *budget {
return;
}
*budget -= count;
let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return };
painted_in(doc, &art, depth, budget, out);
}
/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep.
fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
if !n.visible {
return;
}
match &n.kind {
NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) {
// One path for each fill and stroke, its effects applied.
Some(pieces) => painted_in(doc, &pieces, depth, budget, out),
None => push_painted(doc, n, out),
},
NodeKind::Path { .. } => {}
NodeKind::Image(_) => out.extend(image_paint(doc, n)),
NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out),
_ if n.clips() => {}
_ => {
// A Pathfinder effect paints its result, not the members it combines.
let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten();
let g = evaluated.as_ref().unwrap_or(n);
if g.clips() {
return;
}
// A Shaper group's first member holds its original shapes, which are not drawn. The
// group's own fills and strokes can be painted before it, so it is found by its id.
let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten();
for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) {
painted_in(doc, c, depth, budget, out);
}
}
}
}
/// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one
/// path per run, and all of them as one.
pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::BezPath) {
@@ -954,6 +1023,74 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option<Node> {
Some(Node { visible: t.visible, ..o })
}
/// Clipping path `clip` of a clip group as a clipping path of the region it clips to
/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry
/// effects of its fills and strokes reshape what they paint and leave that region as it is.
/// `None` when it has nothing to clip by.
pub(crate) fn clip_region_path(clip: &Node) -> Option<Node> {
let (bp, rule) = crate::clip_outline(clip)?;
let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default());
if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind {
(*r, *clipping) = (rule, true);
}
p.name = clip.name.clone();
p.visible = clip.visible;
Some(p)
}
/// Knockout Group for clip group `m` turned into a group around `inner`, a clip group of its
/// members, and its clipping path's strokes: `inner` takes `m`'s setting, so the clipped art knocks
/// out as before, and `m` is set Off so the strokes paint over it, as the renderer draws them. A
/// neutral `m` stays neutral, so both take the setting of the groups around them.
pub(crate) fn knockout_inside(m: &mut Node, inner: &mut Node) {
inner.knockout = m.knockout;
if m.knockout != vectorcraft_doc::Knockout::Neutral {
m.knockout = vectorcraft_doc::Knockout::Off;
}
}
/// The clip group in `n` when `n` is a group or layer that [`paint_type_clip`] made of a clip
/// group and its clipping type's strokes: a group that does not clip whose first member is a clip
/// group with `n`'s id and whose second member has the id of that clip group's clipping path. The
/// clip group's region is what `n` stands for, as the clip group it was made from: the strokes
/// paint outside it and add nothing to its outline ([`crate::member_shapes`]) or its bounds
/// ([`clip_bounds`]).
pub(crate) fn painted_clip_inner(n: &Node) -> Option<&Node> {
if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
return None;
}
let [inner, stroke, ..] = n.children()?.as_slice() else { return None };
let clip = inner.children()?.first()?;
(inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner)
}
/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that
/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type
/// outside the clip do not widen them.
pub(crate) fn clip_bounds(n: &Node) -> Option<Rect> {
fn holds(n: &Node) -> bool {
painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c))
}
fn unwrap(n: &mut Node) {
if let Some(inner) = painted_clip_inner(n) {
let mut inner = inner.clone();
inner.visible = n.visible;
*n = inner;
}
for c in n.children_mut().into_iter().flatten() {
if holds(c) {
unwrap(Arc::make_mut(c));
}
}
}
if !holds(n) {
return n.geometric_bounds();
}
let mut probe = n.clone();
unwrap(&mut probe);
probe.geometric_bounds()
}
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
/// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes
/// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and
@@ -981,32 +1118,41 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
}
/// When `n` is a clip group or clipping layer whose clipping path is type that paints
/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip
/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside
/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes
/// (keeping its id, name and transparency) with the clip group inside. The other members stay as
/// they are. Hidden type paints nothing.
/// ([`Node::clip_paint`]), make it the art the canvas draws for it: a path of the region the type
/// clips to clips ([`clip_region_path`]), its fills as art ([`as_art`]) paint behind the clipped
/// art inside the clip, and its strokes as art paint over it, outside the clip. Each part is the
/// type's art with only those fills or strokes, their own geometry effects applied. With strokes,
/// `n` becomes a group (keeping its id, name, visibility and transparency) that holds a clip group
/// of the clipping path, the fills and the other members, with `n`'s id, then the strokes; a
/// clipping layer keeps its ruler guides last. [`knockout_inside`] sets the Knockout Group of both,
/// and [`painted_clip_inner`] finds that clip group. The other members stay as they are. Hidden
/// type paints nothing.
pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) {
let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return };
if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
let Some(first) = n.children().and_then(|ch| ch.first()).filter(|_| n.clips()) else { return };
if !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
return;
}
let paint = first.clip_paint();
if paint.fill.is_none() && paint.stroke.is_none() {
return;
}
let Some(clip) = clipping_text_outline(first) else { return };
let Some(clip) = clip_region_path(first) else { return };
let art = |part: Option<Node>| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new);
let members: Vec<Arc<Node>> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect();
let stroke = art(paint.stroke);
let (fill, stroke) = (art(paint.fill), art(paint.stroke));
let id = n.id;
match (&mut n.kind, stroke) {
(NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members,
(NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => {
*children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke];
*clip = false;
}
_ => {}
let Some(ch) = n.children_mut() else { return };
let Some(slot) = ch.first_mut() else { return };
*slot = Arc::new(clip);
if let Some(fill) = fill {
ch.insert(1, fill);
}
let Some(stroke) = stroke else { return };
let guides = ch.split_off(Node::guide_run_start(ch));
let mut inner = Node::new(id, NodeKind::Group { children: std::mem::take(ch), clip: true });
knockout_inside(n, &mut inner);
if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut n.kind {
*children = [Arc::new(inner), stroke].into_iter().chain(guides).collect();
*clip = false;
}
}
@@ -1822,7 +1968,7 @@ impl Step<'_> {
if !groups.is_empty() {
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed));
}
let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art));
let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art));
let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed));
Ran { kept: !kept_ids.is_empty(), took, masks, short, whole }
}
@@ -3247,6 +3393,9 @@ fn group_marks(
NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false),
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => {
let layer = matches!(n.kind, NodeKind::Layer { .. });
// A clip group whose clipping type's strokes paint around it is measured as that clip
// group: the strokes outside the clip do not widen it ([`clip_bounds`]).
let clip = *clip || painted_clip_inner(n).is_some();
let skip = children.len().saturating_sub(n.editing_children().len());
let (mut bounds, mut held) = (None, false);
for (i, c) in children.iter().enumerate() {
@@ -3257,7 +3406,7 @@ fn group_marks(
}
at.pop();
// Only members measured in the bounds hold the group's gradients in place.
let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) };
let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) };
if counts {
bounds = vectorcraft_geom::union_opt(bounds, b);
held |= h;
@@ -3473,16 +3622,17 @@ impl WarpedImages {
/// The geometric bounds of `art` as it draws after the effects so far: each image this table
/// lists measured by the pieces the warps and moves it took would cut it into, when the art
/// has room for them ([`cut_warped_images`]).
/// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip
/// are left out ([`clip_bounds`]).
pub(crate) fn bounds(&self, art: &Node) -> Option<Rect> {
if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) {
return art.geometric_bounds();
return clip_bounds(art);
}
// The pieces the images would be cut into now: each group of pieces is shown or hidden as
// its image is, and hidden objects are left out of a layer's bounds.
let mut probe = art.clone();
restore_warped_images(&mut probe, self, true);
probe.geometric_bounds()
clip_bounds(&probe)
}
/// The geometric bounds of image `n`: when this table lists it, measured by the pieces the
+5 -5
View File
@@ -6,7 +6,7 @@ use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces};
use crate::solids::wireframe::{WireFace, wireframe_params};
use crate::solids::{
@@ -168,7 +168,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
// With no member to carry them, the graphics' art must still fit its limits.
None => {
crate::solids::graphics::validate_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?;
}
}
}
@@ -201,10 +201,10 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op
let graphics = crate::solids::mapped_graphics(p);
let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) };
crate::solids::graphics::validate_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?;
let faces = vectorcraft_three_d::revolve(path, b, options)?;
let mut used = *copies;
match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) {
match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), &mut used) {
Some(_) => {
*copies = used;
Ok(())
@@ -523,7 +523,7 @@ fn surface(
let mut parts = if graphics.is_empty() {
vec![]
} else {
match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) {
match crate::solids::graphics::surface_parts(doc, n.id, (&graphics, PlanarFace::Front), &faces, &shade, &mut used) {
Some(parts) => {
copies.graphics = used;
parts
+2 -1
View File
@@ -520,7 +520,8 @@ fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() {
let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap();
let parts_of = |symbol: &str, copies: &mut usize| {
let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]}));
crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len())
crate::solids::graphics::surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), copies)
.map(|p| p.concat().len())
};
// Each opaque part copies the paint into its fill and its seam stroke; a part with
// transparent stops takes no seam stroke and copies it once.
+181 -17
View File
@@ -30,7 +30,7 @@ pub use graphics::{
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
rename_appearance_graphic_symbol,
fitting as graphic_fitting_scale, rename_appearance_graphic_symbol,
};
pub(crate) mod shadow;
@@ -84,11 +84,14 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
}
}
// A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics
// on the back cap are dropped.
// on the back cap and on Extrude & Bevel's side are dropped.
if (to == ROTATE || to == crate::REVOLVE)
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
{
list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id()));
list.retain(|g| {
let face = g.get("face").and_then(Value::as_str);
face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id())
});
}
Value::Object(out)
}
@@ -177,6 +180,7 @@ pub fn extrude_options(p: &Value) -> Extrude {
both_sides: flag(p, "bevelBothSides", false),
}),
hidden: false,
map_surface: false,
}
}
@@ -253,6 +257,56 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
}
}
/// [`facets`] of Extrude & Bevel with parameters `p`, with the pieces of the side of its longest
/// contour carrying where they lie on it unrolled ([`Facet::surface`]), for its side's graphics.
fn side_facets(path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result<Vec<Facet>, String> {
#[cfg(test)]
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
vectorcraft_three_d::extrude(path, rule, bounds, Extrude { map_surface: true, ..extrude_options(p) }, view_options(p))
}
/// [`side_facets`], and with `cast` the faces the solid's shadow is cast from, from the same build
/// ([`facets_and_faces`]).
fn side_facets_and_faces(path: &PathData, rule: FillRule, bounds: Rect, p: &Value, cast: bool) -> Result<CastingSolid, String> {
if !cast {
return side_facets(path, rule, bounds, p).map(|f| (f, None));
}
#[cfg(test)]
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
let options = Extrude { map_surface: true, ..extrude_options(p) };
vectorcraft_three_d::extrude_shadowed(path, rule, bounds, options, view_options(p)).map(|(f, faces)| (f, Some(faces)))
}
/// The part of `parts` ([`solid_parts`]) whose solid takes the graphics on Extrude & Bevel's side,
/// with parameters `p` and built about `bounds`: the first of those with the longest outline
/// ([`vectorcraft_three_d::extrude_side_size`]). `None` when the effect `id` is not Extrude & Bevel
/// or has no graphic on its side, or when no part has a side.
fn side_carrier(id: &str, p: &Value, parts: &[Part<'_>], bounds: Rect) -> Option<usize> {
if id != EXTRUDE || !mapped_graphics(p).iter().any(|g| g.face == PlanarFace::Side) {
return None;
}
let options = extrude_options(p);
parts
.iter()
.enumerate()
.filter_map(|(k, (_, _, area, rule, _, _))| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options).map(|(w, ..)| (k, w)))
.fold(None, |best: Option<(usize, f64)>, (k, w)| if best.is_some_and(|(_, top)| top >= w) { best } else { Some((k, w)) })
.map(|(k, _)| k)
}
/// The size of Extrude & Bevel's side unrolled for the graphics on it: the side of the part of
/// `shapes` that [`side_carrier`] picks, with parameters `p`, as wide as the part of it about x = 0
/// that does not reach its cut and as tall as the length across its bevels and walls.
fn side_size(p: &Value, shapes: &[Profile]) -> Option<(f64, f64)> {
let (parts, bounds) = solid_parts(shapes, union_bounds(shapes)?);
let options = extrude_options(p);
parts
.iter()
.filter_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options))
.fold(None, |best: Option<(f64, f64, f64)>, size| if best.is_some_and(|top| top.0 >= size.0) { best } else { Some(size) })
.map(|(_, height, span)| (span, height))
}
/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast
/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the
/// classic effects cast no shadow: they keep no faces.
@@ -339,7 +393,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
reshape_members(n, before, &mut shapes);
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
check_profiles(id, p, &shapes, b)?;
return check_solids(id, p, &shapes);
check_solids(id, p, &shapes)?;
return check_side_graphics(doc, n, id, p, &shapes);
}
let (path, rule) = object_profile(n, label)?;
let anchors = || format!("{label} requires a shape with at least two anchors");
@@ -356,7 +411,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
let b = path.bounds().ok_or_else(anchors)?;
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
check_profiles(id, p, &shapes, b)?;
check_solids(id, p, &shapes)
check_solids(id, p, &shapes)?;
check_side_graphics(doc, n, id, p, &shapes)
}
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
@@ -370,6 +426,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool {
paint_of(item, member).1 > 0.0
}
/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the
/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them
/// ([`side_carrier`]): their art, or the parts they draw on its pieces
/// ([`graphics::surface_parts`]), or when the object `n`'s surfaces can't be built at all. They are
/// built as the art builds them ([`surfaces_with`]), so its pieces are the ones the art draws, cuts
/// included. Without `doc` nothing is drawn, and nothing is checked.
fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
let Some(doc) = doc else { return Ok(()) };
let Some(b) = union_bounds(shapes) else { return Ok(()) };
let (parts, bounds) = solid_parts(shapes, b);
if side_carrier(id, p, &parts, bounds).is_none() {
return Ok(());
}
graphics::validate_surface_symbols(doc, p, PlanarFace::Side)?;
let fx = Effect { id: id.into(), params: p.clone(), visible: true };
let mut dropped = false;
// Art that can't be built draws the source path, without the side's graphics.
let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped);
if dropped || built.is_none() {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
Ok(())
}
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate
/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is
@@ -414,7 +494,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
if !cast {
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
}
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true)
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None)
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
.collect::<Result<Vec<_>, String>>()?;
cast_built(id, p, shapes, built).map(|_| ())
@@ -688,6 +768,30 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by
/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]):
/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it
/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group.
fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec<Vec<Arc<Node>>>) -> Node {
if parts.iter().all(Vec::is_empty) {
return surface;
}
let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface };
if children.len() != parts.len() {
return surface;
}
for (child, extra) in children.iter_mut().zip(parts) {
if extra.is_empty() {
continue;
}
let mut list = Vec::with_capacity(extra.len() + 1);
list.push(child.clone());
list.extend(extra);
*child = Arc::new(Node::group(id, list));
}
surface
}
/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any).
pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect {
facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO)
@@ -802,7 +906,7 @@ fn built_solids<'a>(
bounds: Rect,
limit: usize,
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f)))
built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f)))
}
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
@@ -813,7 +917,9 @@ type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
/// is cast from, from the same build ([`SolidFaces`]).
/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one,
/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics
/// on Extrude & Bevel's side ([`side_carrier`]).
fn built_solids_cast<'a>(
id: &'a str,
p: &'a Value,
@@ -821,6 +927,7 @@ fn built_solids_cast<'a>(
bounds: Rect,
limit: usize,
cast: bool,
side: Option<usize>,
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
// Inflate's eye is placed for every puff together, as far away as the highest needs.
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
@@ -834,7 +941,7 @@ fn built_solids_cast<'a>(
});
let mut kept = 0usize;
let mut ended = false;
parts.iter().map_while(move |(item, _, area, rule, _, _)| {
parts.iter().enumerate().map_while(move |(k, (item, _, area, rule, _, _))| {
if ended {
return None;
}
@@ -846,6 +953,7 @@ fn built_solids_cast<'a>(
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
each.next().unwrap_or_else(|| Ok((vec![], None)))
}
None if side == Some(k) => side_facets_and_faces(area, *rule, bounds, p, cast),
None => facets_and_faces(id, area, *rule, bounds, p, cast),
};
let result = match built {
@@ -1098,6 +1206,8 @@ fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Op
f.depth = s.depth_at(mid).unwrap_or(s.depth);
f.contours = vec![points];
f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign));
// A piece keeps where the whole face lies on the side: the parts of the side's graphics
// drawn on it are cut to its own outline ([`graphics::SurfaceFace::curved`]).
Some(f)
};
Some((piece(1.0)?, piece(-1.0)?))
@@ -1776,6 +1886,12 @@ fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option<SurfacesAndFaces> {
surfaces_with(doc, n, fx, shapes, cast, &mut false)
}
/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past
/// their limits on the pieces drawn, and the solid that takes them draws without them.
fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option<SurfacesAndFaces> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
@@ -1818,9 +1934,13 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built));
}
let (parts, bounds) = solid_parts(shapes, b);
// The graphics on Extrude & Bevel's side go once, on the side of the solid with the longest
// outline, whose pieces are built carrying where they lie on it.
let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None };
let mut solids = vec![];
let mut built = vec![];
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) {
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier);
for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() {
let item: &AppearanceItem = item;
match f {
Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
@@ -1830,8 +1950,12 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
solids.push((item, *opacity, *scopes, f, *member));
built.push(faces);
}
// A stroke's outline past the limits is left out; the fill's solid still draws.
Ok(None) => built.push(None),
// A stroke's outline past the limits is left out; the fill's solid still draws, and
// the side's graphics on that outline are not drawn.
Ok(None) => {
built.push(None);
*side_dropped |= carrier == Some(k);
}
// A loaded file or a shape edited past the limits (its own, or those of the object's
// solids together) keeps drawing its source path instead of failing the frame;
// commands validate the same evaluator and report its errors.
@@ -1915,6 +2039,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
// ([`in_one_order`], [`underlaid_surface`]).
let seals: Vec<bool> = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect();
let seal = |range: std::ops::Range<usize>| seals.get(range).is_some_and(|s| s.iter().any(|s| *s));
let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default();
// The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve.
let mut graphic_copies = 0usize;
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
.map(|(item, member, scopes, f, shape)| {
@@ -1922,10 +2049,22 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
// The carrier's pieces draw the parts of the side's graphics that fall on them; past
// the graphics' limits the solid draws without them.
let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) {
vec![]
} else {
let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination));
let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies);
*side_dropped |= parts.is_none();
parts.unwrap_or_default()
};
let drawn = parts.iter().any(|p| !p.is_empty());
let art = if classic {
classic::surface(n, f, &paint, opacity, blend, &p)
} else {
surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false))
let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false));
with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts)
};
(depths, art, scopes, ends)
})
@@ -2239,8 +2378,18 @@ pub fn graphics_reshaped_after(n: &Node, item: Option<usize>, index: usize) -> b
/// Finds a 3D effect in a list of effects, with its index there.
type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p;
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
/// The size of the side unrolled of the Extrude & Bevel at `index` of the effects of `n` (on the
/// object itself with `item` `None`, else on its fill or stroke `item`), that a new graphic on it
/// fits: on the side of its solid with the longest outline, as wide as the part about x = 0 that
/// does not reach the side's cut, and as tall as the length across its bevels and walls. `None` when that effect is not a visible Extrude & Bevel with a
/// depth, or its art can't be built.
pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<(f64, f64)> {
let (fx, shapes) = frame_shapes(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && e.id == EXTRUDE).map(|e| (index, e)))?;
side_size(&crate::merged_params(&fx.id, &fx.params), &shapes)
}
/// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from.
fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<(Effect, Vec<Profile>)> {
let n = &*resolve(doc, n, "").ok()?;
let (fx, shapes) = if is_container(n) {
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
@@ -2264,6 +2413,12 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
}
}
};
Some((fx.clone(), shapes))
}
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
let (fx, shapes) = frame_shapes(doc, n, item, pick)?;
if !takes_graphics(&fx.id) {
return None;
}
@@ -2289,10 +2444,19 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
let plane = vectorcraft_three_d::plane_face_map(b, view);
return Some(graphics::GraphicFrame::new(b, plane, None));
}
let (_, bounds) = solid_parts(&shapes, b);
let (parts, bounds) = solid_parts(&shapes, b);
let options = extrude_options(&p);
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)))
let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back));
// With graphics on the side, the part of it the viewer sees places their handles.
let side = side_carrier(&fx.id, &p, &parts, bounds)
.and_then(|k| parts.get(k))
.and_then(|(_, _, area, rule, _, _)| side_facets(area, *rule, bounds, &p).ok())
.map(|facets| graphics::SideFrame::of(&facets));
Some(match side {
Some(side) => frame.with_side(side),
None => frame,
})
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
+220 -54
View File
@@ -1,6 +1,6 @@
//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials ›
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a
//! plane, turned, foreshortened and shaded with that face and clipped to it.
//! Graphics mapped onto a 3D object's faces (Window › 3D and Materials › Materials ›
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap or on its
//! side, or on a plane, turned, foreshortened and shaded with that face and clipped to it.
//!
//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale,
//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of
@@ -12,7 +12,10 @@
//! On Revolve the graphics lie on the swept side surface, unrolled flat
//! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the
//! middle of that surface, x around the axis and y along the profile, and each face of the side
//! draws the part of the graphics that falls on it ([`surface_parts`]).
//! draws the part of the graphics that falls on it ([`surface_parts`]). Graphics on Extrude &
//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the
//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with
//! the longest outline.
use std::sync::Arc;
@@ -110,7 +113,7 @@ impl MappedGraphic {
};
let face = match m.get("face") {
None => PlanarFace::Front,
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?,
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front, back or side"))?,
};
let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> {
match m.get(key) {
@@ -139,7 +142,7 @@ impl MappedGraphic {
* Affine::scale(self.scale / 100.0)
* Affine::translate(-art.center().to_vec2());
match self.face {
PlanarFace::Front => place,
PlanarFace::Front | PlanarFace::Side => place,
// Seen from behind, the back's right is the front's left.
PlanarFace::Back => {
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
@@ -148,8 +151,8 @@ impl MappedGraphic {
}
}
/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve
/// (its swept side).
/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane)
/// and Revolve (its swept side).
pub fn takes_graphics(id: &str) -> bool {
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE
}
@@ -165,7 +168,7 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and
/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named
/// the front.
/// the front. Only Extrude & Bevel takes graphics on its side.
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
let list = match p.get(GRAPHICS) {
None => return Ok(()),
@@ -183,10 +186,10 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
}
for v in list {
let g = MappedGraphic::from_value(v)?;
if id == super::ROTATE && g.face == PlanarFace::Back {
if id == super::ROTATE && g.face != PlanarFace::Front {
return Err("A plane has one face: map its graphics onto the front".into());
}
if id == crate::REVOLVE && g.face == PlanarFace::Back {
if id == crate::REVOLVE && g.face != PlanarFace::Front {
return Err("Revolve maps graphics onto its side: map them onto the front".into());
}
}
@@ -598,14 +601,14 @@ struct Unrolled {
place: Affine,
}
/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side
/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is
/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than
/// [`MAX_ELEMENTS`] points together.
fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option<Vec<Unrolled>> {
/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side)
/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does
/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces
/// take more than [`MAX_ELEMENTS`] points together.
fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option<Vec<Unrolled>> {
let mut pieces = vec![];
let mut points = 0usize;
for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) {
for g in graphics.iter().filter(|g| g.face == face) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let Ok(art) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
@@ -682,38 +685,96 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option<Vec<Vec<Point>>
(*points <= MAX_ELEMENTS).then_some(polygons)
}
/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art,
/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together.
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> {
/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit
/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface,
/// may take up to [`MAX_ELEMENTS`] points together.
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> {
let list = mapped_graphics(p);
if list.is_empty() || unrolled(doc, &list).is_some() {
if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() {
return Ok(());
}
Err("The graphics are too complex: simplify the symbols' art".into())
}
/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing
/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces
/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows
/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it.
/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the
/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol
/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past
/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`]
/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take
/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for
/// them: commands refuse such graphics, and a loaded file draws the surface without them.
pub(crate) fn surface_parts(
/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's
/// swept side, or a piece of Extrude & Bevel's walls and bevels.
pub(crate) trait SurfaceFace {
/// Where the face lies on the side unrolled, when it is a face of the side that shows its
/// outside to the viewer.
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>;
/// The outline the face's parts are cut to, when it is not the polygon of its cell's corners:
/// its curved outline, when its edges along an end are curved, or the outline of a piece cut
/// from a larger face.
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>>;
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient>;
fn light(&self) -> [f64; 3];
fn outline_path(&self) -> PathData;
}
impl SurfaceFace for vectorcraft_three_d::Face {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.surface.as_ref().filter(|c| c.outward && !self.cap)
}
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
self.outline.as_ref().map(std::borrow::Cow::Borrowed)
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.rgb_gradient
}
fn light(&self) -> [f64; 3] {
self.illumination
}
fn outline_path(&self) -> PathData {
self.path()
}
}
impl SurfaceFace for Facet {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.surface.as_ref().filter(|c| c.outward)
}
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
if let Some(outline) = &self.outline {
return Some(std::borrow::Cow::Borrowed(outline));
}
// A piece of a stroke's face cut where it passes through a wall keeps its face's cell.
let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page));
cut.then(|| std::borrow::Cow::Owned(self.path()))
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.rgb_gradient
}
fn light(&self) -> [f64; 3] {
self.illumination
}
fn outline_path(&self) -> PathData {
self.path()
}
}
/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side)
/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id
/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their
/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past
/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color
/// on a face, as the surface under it is shaded; the colors of gradients and patterns are
/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the
/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are
/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the
/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's
/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded
/// file draws the surface without them.
pub(crate) fn surface_parts<F: SurfaceFace>(
doc: Option<&Document>,
id: NodeId,
graphics: &[MappedGraphic],
faces: &[vectorcraft_three_d::Face],
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
(graphics, face): (&[MappedGraphic], PlanarFace),
faces: &[F],
shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint,
copies: &mut usize,
) -> Option<Vec<Vec<Arc<Node>>>> {
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; faces.len()];
let Some(doc) = doc else { return Some(out) };
let pieces = unrolled(doc, graphics)?;
let pieces = unrolled(doc, graphics, face)?;
let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) };
// Each piece listed in the buckets of the surface's x its bounds reach across.
let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9);
@@ -729,11 +790,12 @@ pub(crate) fn surface_parts(
let mut cut_points = 0usize;
let mut triangle_id = 0usize;
for (face, parts) in faces.iter().zip(out.iter_mut()) {
let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue };
let Some(cell) = face.outer_cell() else { continue };
if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) {
continue;
}
let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
let curved = face.curved();
for corners in triangles {
triangle_id += 1;
let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::<Option<Vec<Point>>>();
@@ -744,7 +806,7 @@ pub(crate) fn surface_parts(
// where the graphic runs past the end of the profile. A four-cornered face is cut into
// two triangles along its diagonal from corner 0 to corner 2: each takes the part of
// the outline on its own side of it.
let window = if face.outline.is_some() { grown(window, 3.0) } else { window };
let window = if curved.is_some() { grown(window, 3.0) } else { window };
// The pieces are looked up over the whole of the window they are cut to.
let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue };
if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 {
@@ -771,7 +833,7 @@ pub(crate) fn surface_parts(
}
near.sort_unstable();
let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2);
let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) {
let rim = curved.as_deref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) {
(Some(&toward), Some(&a), Some(&b)) => {
let side = side_of(a, b, toward);
vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect)
@@ -834,21 +896,21 @@ pub(crate) fn surface_parts(
/// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes
/// from the unrolled surface onto `face`.
fn surface_piece(
fn surface_piece<F: SurfaceFace>(
id: NodeId,
piece: &Unrolled,
(path, rule): (BezPath, FillRule),
map: Affine,
face: &vectorcraft_three_d::Face,
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
face: &F,
shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint,
) -> Node {
let gradient_map = map * piece.place;
// Under several lights a face's light varies across it in each channel: a solid color draws
// as the face's own lit art in that color, clipped to the part. An opaque part also draws that
// art clipped to a band of the seam stroke's width around its edges, as the other parts take
// a stroke over their seams.
if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) {
let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light));
if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_light()) {
let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.outline_path(), &Paint::solid(c), light));
let clipped = |area: &BezPath, rule: FillRule| {
let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default());
if let NodeKind::Path { rule: r, .. } = &mut clip.kind {
@@ -881,7 +943,7 @@ fn surface_piece(
match solid {
Some(c) => f.paint = shade(face, c),
None => {
vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination));
vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.light()));
}
}
}
@@ -996,23 +1058,106 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
}
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
/// offsets are from their center) and the maps of its front and back faces, when it has them.
#[derive(Clone, Copy, Debug, PartialEq)]
/// offsets are from their center), the maps of its front and back faces, when it has them, and
/// the visible part of its side unrolled, when it has graphics there.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphicFrame {
pub bounds: Rect,
front: Option<FaceMap>,
back: Option<FaceMap>,
side: Option<SideFrame>,
}
/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are
/// drawn on them ([`surface_parts`]): each piece's corners on the side unrolled and on the page, the
/// outline its parts are cut to when that is not the polygon of its corners, and its depth (larger
/// is nearer).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SideFrame {
pieces: Vec<SidePiece>,
}
#[derive(Clone, Debug, PartialEq)]
struct SidePiece {
uv: Vec<Point>,
page: Vec<Point>,
outline: Option<BezPath>,
depth: f64,
}
impl SideFrame {
/// The pieces of `facets` that carry where they lie on the side unrolled and show its outside.
pub(super) fn of(facets: &[Facet]) -> Self {
let pieces = facets
.iter()
.filter_map(|f| {
let cell = f.outer_cell().filter(|c| c.uv.len() == c.page.len() && (3..=4).contains(&c.uv.len()))?;
let outline = f.curved().map(|o| o.to_bezpath());
Some(SidePiece { uv: cell.uv.clone(), page: cell.page.clone(), outline, depth: f.depth })
})
.collect();
Self { pieces }
}
/// Point `p` of the side unrolled mapped onto the page, or with `from_page` a page point mapped
/// onto the side unrolled, through the nearest piece whose drawn part holds it: within the
/// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and
/// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it.
fn map(&self, p: Point, from_page: bool) -> Option<Point> {
let inside = |t: &[Point; 3], q: Point| {
let side = |a: Point, b: Point| (b - a).cross(q - a);
let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9)
};
let mut best: Option<(Point, f64)> = None;
for piece in &self.pieces {
let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) };
let triangles: &[[usize; 3]] = if from.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
for corners in triangles {
let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]);
let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue };
let window = if piece.outline.is_some() { grown(a, 3.0) } else { a };
if !inside(&window, p) {
continue;
}
// A four-cornered piece's two triangles meet along its diagonal: each holds its side.
if triangles.len() == 2
&& let (Some(&d0), Some(&d2), Some(&own)) = (from.first(), from.get(2), from.get(if corners[1] == 1 { 1 } else { 3 }))
{
let across = |q: Point| (d2 - d0).cross(q - d0);
if across(p) * across(own) < 0.0 {
continue;
}
}
let Some(q) = triangle_map(&a, &b).map(|m| m * p).filter(|q| q.is_finite()) else { continue };
let on_page = if from_page { p } else { q };
if piece.outline.as_ref().is_some_and(|o| !o.contains(on_page)) {
continue;
}
if best.is_none_or(|(_, depth)| piece.depth > depth) {
best = Some((q, piece.depth));
}
}
}
best.map(|(q, _)| q)
}
}
impl GraphicFrame {
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
Self { bounds, front, back }
Self { bounds, front, back, side: None }
}
/// The frame with the visible part of the side `side`, for its graphics' handles.
pub(super) fn with_side(self, side: SideFrame) -> Self {
Self { side: Some(side), ..self }
}
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
match face {
PlanarFace::Front => self.front.as_ref(),
PlanarFace::Back => self.back.as_ref(),
PlanarFace::Side => None,
}
}
@@ -1023,23 +1168,34 @@ impl GraphicFrame {
match face {
PlanarFace::Front => Point::new(c.x + x, c.y + y),
PlanarFace::Back => Point::new(c.x - x, c.y + y),
PlanarFace::Side => Point::new(x, y),
}
}
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
/// viewer. `None` when the object has no such face or the point has no page point.
/// viewer. `None` when the object has no such face or the point has no page point. A graphic on
/// the side lands where its center is on the part of the side the viewer sees, and is `None`
/// elsewhere.
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
if g.face == PlanarFace::Side {
return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true));
}
let map = self.map(g.face)?;
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
}
/// The offset of a graphic on `face` whose center lands on page point `page`.
/// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only
/// a point on the part of the side the viewer sees has one.
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
let art = self.map(face)?.to_art(page)?;
let art = match face {
PlanarFace::Side => self.side.as_ref()?.map(page, true)?,
_ => self.map(face)?.to_art(page)?,
};
let c = self.bounds.center();
let (x, y) = match face {
PlanarFace::Front => (art.x - c.x, art.y - c.y),
PlanarFace::Back => (c.x - art.x, art.y - c.y),
PlanarFace::Side => (art.x, art.y),
};
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
}
@@ -1047,11 +1203,17 @@ impl GraphicFrame {
/// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most
/// 100: where a newly mapped graphic starts.
pub fn fitting_scale(&self, art: Rect) -> f64 {
let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9));
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
fitting(self.bounds.width(), self.bounds.height(), art)
}
}
/// The scale (percent) at which art with bounds `art` fits inside a `width` × `height` area, at
/// most 100.
pub fn fitting(width: f64, height: f64, art: Rect) -> f64 {
let fit = (width / art.width().max(1e-9)).min(height / art.height().max(1e-9));
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
}
/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes').
pub fn graphic_symbols(n: &Node) -> Vec<String> {
appearance_graphic_symbols(&n.appearance)
@@ -1135,3 +1297,7 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
#[cfg(test)]
#[path = "tests_graphics.rs"]
mod tests;
#[cfg(test)]
#[path = "tests_graphics_side.rs"]
mod tests_side;
+1
View File
@@ -774,6 +774,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
side: true,
away: false,
end: None,
surface: None,
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
};
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
+8 -2
View File
@@ -531,12 +531,13 @@ fn graphics_are_checked() {
let n = object(EXTRUDE, json!({}));
let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics}));
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok());
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "side", "x": -40.0, "y": 5.0}])).is_ok());
assert!(check(EXTRUDE, json!([])).is_ok());
for bad in [
json!("Mark"),
json!([{"face": "front"}]),
json!([{"symbol": ""}]),
json!([{"symbol": "Mark", "face": "side"}]),
json!([{"symbol": "Mark", "face": "top"}]),
json!([{"symbol": "Mark", "scale": 0.0}]),
json!([{"symbol": "Mark", "rotation": 400.0}]),
json!([{"symbol": "Mark", "x": "1"}]),
@@ -546,10 +547,12 @@ fn graphics_are_checked() {
assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}");
}
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err());
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
// Revolve takes graphics on its side, named the front; Revolve (Classic) takes none.
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_err());
assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
// A loaded file's invalid entries are left out when drawn.
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
@@ -569,10 +572,13 @@ fn the_frame_at_an_index_is_that_effects() {
#[test]
fn a_change_to_a_plane_drops_the_back_caps_graphics() {
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]});
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}, {"symbol": "Mark", "face": "side"}]});
let plane = three_d_params_as(EXTRUDE, &p, ROTATE);
assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert!(validate_three_d_params(ROTATE, &plane).is_ok());
// Revolve drops the side's graphics too; Extrude & Bevel keeps every face's.
assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]);
// Back to Extrude & Bevel, the front's graphic stays.
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
}
@@ -0,0 +1,255 @@
//! Graphics on Extrude & Bevel's side: its walls and bevels unrolled flat.
use serde_json::json;
use vectorcraft_doc::color::Color;
use vectorcraft_doc::{StrokeLayer, Symbol};
use vectorcraft_geom::shapes;
use super::super::{EXTRUDE, graphic_frame, graphic_side_size, solid_art_in, validate_three_d_in};
use super::*;
fn red() -> Color {
Color::rgb(1.0, 0.0, 0.0)
}
fn square(id: u64, r: Rect, paint: Paint) -> Node {
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0))
}
/// A document with symbol "Mark": a red 10 × 10 square.
fn document() -> Document {
let mut d = Document::new(1000.0, 1000.0);
d.symbols.push(Symbol {
dynamic: false,
name: "Mark".into(),
art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))),
});
d
}
/// A gray 100 × 100 square at (0, 0), extruded 50 pt, seen from above (its top wall faces the
/// viewer, its front edge at the bottom of the page), with `params` over that.
fn object(params: Value) -> Node {
let mut p = json!({"rotationX": -90.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) {
p.extend(extra.clone());
}
let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
n
}
fn is_red(p: &Paint) -> bool {
p.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1)
}
/// The groups of a face and the parts of the side's graphics drawn on it, each part's outline.
fn faces_with_parts(art: &Node) -> Vec<Vec<PathData>> {
let mut out = vec![];
art.walk(&mut |n| {
if let NodeKind::Group { children, clip: false } = &n.kind
&& let Some((face, parts)) = children.split_first()
&& matches!(face.kind, NodeKind::Path { .. })
&& !parts.is_empty()
{
let red: Vec<PathData> = parts
.iter()
.filter(|p| p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if is_red(&f.paint))))
.filter_map(|p| p.path_data().cloned())
.collect();
if red.len() == parts.len() {
out.push(red);
}
}
});
out
}
fn bounds(parts: &[Vec<PathData>]) -> Rect {
parts.iter().flatten().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
}
fn near(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6)
}
/// x runs along the outline from the top's middle, clockwise as the front is seen, and y from the
/// middle of the side toward the back.
#[test]
fn a_side_graphic_lies_on_the_wall_at_its_offset() {
let d = document();
let n = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
let found = faces_with_parts(&art);
assert_eq!(found.len(), 1, "drawn once, on the top wall");
// Seen from above, the top wall runs from its front edge (page y 75) to its back (page y 25).
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
let moved = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 20.0, "y": 10.0, "scale": 200.0}]}));
let found = faces_with_parts(&solid_art_in(Some(&d), &moved).unwrap());
assert!(near(bounds(&found), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds(&found));
// Without the document nothing is drawn; a graphic on the side leaves the caps without one.
assert!(faces_with_parts(&solid_art_in(None, &n).unwrap()).is_empty());
}
/// A graphic that reaches past a corner runs on around it onto the next wall.
#[test]
fn a_side_graphic_runs_around_a_corner() {
let d = document();
// x = 50 is the top's right end.
let from_above = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]}));
let found = faces_with_parts(&solid_art_in(Some(&d), &from_above).unwrap());
assert!(near(bounds(&found), Rect::new(95.0, 45.0, 100.0, 55.0)), "only the top's part shows: {:?}", bounds(&found));
// Turned to show the top and the right, both walls draw their part.
let turned = object(json!({"rotationX": -30.0, "rotationY": -40.0, "graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]}));
assert_eq!(faces_with_parts(&solid_art_in(Some(&d), &turned).unwrap()).len(), 2);
// Twist and taper carry the graphic; it stays on the side.
let twisted =
object(json!({"rotationX": -30.0, "rotationY": -40.0, "twist": 60.0, "taper": 50.0, "graphics": [{"symbol": "Mark", "face": "side"}]}));
let found = faces_with_parts(&solid_art_in(Some(&d), &twisted).unwrap());
assert!(!found.is_empty() && found.iter().flatten().all(|p| p.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))));
}
/// The handle lands where the graphic's center is on the visible side, and a page point there
/// gives back its offset; a graphic on a hidden wall has no handle.
#[test]
fn the_sides_handle_moves_the_graphic_on_its_visible_part() {
let d = document();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 10.0, "y": -5.0})).unwrap();
let n = object(json!({"graphics": [g.to_value()]}));
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let (at, visible) = frame.handle(&g).unwrap();
assert!(visible && at.distance(Point::new(60.0, 55.0)) < 1e-6, "{at:?}");
let (x, y) = frame.offset_at(PlanarFace::Side, Point::new(40.0, 45.0)).unwrap();
assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}");
// The bottom's middle, half way around, is hidden from above; so is a page point off the top.
let hidden = MappedGraphic { x: 200.0, ..g.clone() };
assert!(frame.handle(&hidden).is_none());
assert!(frame.offset_at(PlanarFace::Side, Point::new(50.0, 90.0)).is_none());
// Without a graphic on the side, the frame places no handle there.
let caps = graphic_frame(Some(&d), &object(json!({"graphics": [{"symbol": "Mark"}]})), None).unwrap();
assert!(caps.handle(&g).is_none());
}
/// On a curved wall, whose pieces are cut to its curved outline, the handle sits on the graphic's
/// center and a page point there gives back its offset.
#[test]
fn the_handle_follows_a_curved_side() {
let d = document();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 6.0, "y": 3.0})).unwrap();
let mut n = object(json!({"rotationX": -60.0, "graphics": [g.to_value()]}));
if let NodeKind::Path { path, .. } = &mut n.kind {
*path = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
}
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let (at, visible) = frame.handle(&g).unwrap();
assert!(visible);
let (x, y) = frame.offset_at(PlanarFace::Side, at).unwrap();
assert!((x - 6.0).abs() < 1e-6 && (y - 3.0).abs() < 1e-6, "{x} {y}");
}
/// A hollow object has no caps but takes graphics on its side; a stroke's solid, whose outline is
/// the longest, takes them once.
#[test]
fn a_hollow_or_stroked_object_takes_a_side_graphic() {
let d = document();
let hollow = object(json!({"cap": false, "graphics": [{"symbol": "Mark", "face": "side"}, {"symbol": "Mark"}]}));
let art = solid_art_in(Some(&d), &hollow).unwrap();
assert!(near(bounds(&faces_with_parts(&art)), Rect::new(45.0, 45.0, 55.0, 55.0)));
let mut stroked = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]}));
stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)), 10.0)));
let found = faces_with_parts(&solid_art_in(Some(&d), &stroked).unwrap());
assert_eq!(found.len(), 1, "on the stroke's outer wall only");
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
// The stroke's outer outline is 440 pt long, cut at a bottom corner 165 pt each way from the
// top's middle: a new graphic fits the 330 pt about x = 0 and the depth.
assert_eq!(graphic_side_size(Some(&d), &stroked, None, 0), Some((330.0, 50.0)));
}
/// A stroke's face cut where it passes through a wall keeps the whole face's place on the side, and
/// each piece draws only the part of the graphic within its own outline.
#[test]
fn a_piece_cut_from_a_face_draws_its_own_part() {
let d = document();
let facet = |x: f64, normal: [f64; 3], offset: f64| {
let square = vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
let uv = square.iter().map(|p| Point::new(p.x - x, p.y)).collect();
Facet {
contours: vec![square.clone()],
depth: 0.0,
brightness: 1.0,
illumination: [1.0; 3],
normal,
rgb_gradient: None,
outline: None,
side: true,
away: false,
end: None,
surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }),
plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
}
};
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
// z = x - 8: behind the wall left of x = 8, in front of it right of it.
let r = std::f64::consts::FRAC_1_SQRT_2;
let mut stroke = vec![facet(5.0, [-r, 0.0, r], -8.0 * r)];
super::super::cut_through(std::slice::from_ref(&wall), &mut stroke, &mut 10, &mut 0);
assert_eq!(stroke.len(), 2, "cut where it passes through the wall");
// The graphic covers the whole face, x 5 to 15 on the page.
let graphics = mapped_graphics(&json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 5.0, "y": 5.0}]}));
let shade = |_: &Facet, c: Color| Paint::solid(c);
let parts = surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Side), &stroke, &shade, &mut 0).unwrap();
let drawn: Vec<Rect> =
parts.iter().map(|on| on.iter().filter_map(|n| n.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)).unwrap()).collect();
// Each piece draws its own side of x = 8 (where the wall cuts it), together the whole graphic.
let (left, right) = (drawn[0].x0.min(drawn[1].x0), drawn[0].x1.max(drawn[1].x1));
assert!((left - 5.0).abs() < 1e-6 && (right - 15.0).abs() < 1e-6, "{drawn:?}");
assert!(drawn.iter().all(|b| (b.x0 - 8.0).abs() < 1e-6 || (b.x1 - 8.0).abs() < 1e-6), "{drawn:?}");
}
/// Commands refuse a side graphic whose curves, cut into straight pieces on the side, pass the
/// limit of points, though its own path elements are few; on a cap it is accepted.
#[test]
fn a_side_graphic_past_its_limits_is_refused() {
let mut d = document();
// 200 circles 200,000 pt across: a few elements each, hundreds of thousands of points cut.
let mut subpaths = vec![];
for k in 0..200 {
let x = f64::from(k);
subpaths.extend(shapes::ellipse(Rect::new(x, 0.0, x + 2e5, 2e5)).subpaths);
}
let rings = Node::path(NodeId(0), PathData::new(subpaths), Appearance::basic(Paint::solid(red()), Paint::None, 0.0));
d.symbols.push(Symbol { dynamic: false, name: "Rings".into(), art: Arc::new(rings) });
let n = object(json!({}));
let side = json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings", "face": "side"}]});
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &side).is_err());
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings"}]})).is_ok());
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_ok());
}
/// With the shadow on, the solid that carries the side's graphics is built once, for both its faces
/// and its shadow: the graphic keeps its place on the wall, and the shadow is the one the object
/// casts without a graphic.
#[test]
fn a_side_graphic_keeps_its_place_with_the_shadow_on() {
let d = document();
let shadow = |art: &Node| {
let first = &art.children().unwrap()[0];
let [AppearanceItem::Fill(fill)] = first.appearance.items.as_slice() else { panic!("no shadow first: {first:?}") };
assert!(fill.paint.color() == Some(Color::BLACK) && (fill.opacity - 0.5).abs() < 1e-6, "{fill:?}");
first.path_data().and_then(PathData::bounds).unwrap()
};
let lit = json!({"shade": true, "lightHeight": 90.0, "shadow": true, "shadowDistance": 50.0});
let mut with_graphic = lit.clone();
with_graphic["graphics"] = json!([{"symbol": "Mark", "face": "side"}]);
let n = object(with_graphic);
super::super::SOLID_GEOMETRY_BUILT.with(|b| b.set(0));
super::super::SOLIDS_BUILT.with(|b| b.set(0));
let art = solid_art_in(Some(&d), &n).unwrap();
let builds = (super::super::SOLID_GEOMETRY_BUILT.with(std::cell::Cell::get), super::super::SOLIDS_BUILT.with(std::cell::Cell::get));
assert_eq!(builds, (1, 1), "one build for the faces and the shadow");
let found = faces_with_parts(&art);
assert_eq!(found.len(), 1, "drawn once, on the top wall");
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
let without = solid_art_in(Some(&d), &object(lit)).unwrap();
assert!(near(shadow(&art), shadow(&without)), "{:?} {:?}", shadow(&art), shadow(&without));
}
+1 -1
View File
@@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() {
let p = crate::merged_params(id, &json!({"shadow": true}));
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let mut built: Vec<Option<SolidFaces>> =
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
+109
View File
@@ -1708,6 +1708,115 @@ fn twist_joins_its_pieces_smoothly() {
}
}
#[test]
fn twist_boundary_handles_follow_the_inward_tangent() {
let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false));
let bounds = Rect::new(40.0, 30.0, 60.0, 30.0);
for angle in [90.0_f64, 400.0, -720.0] {
let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds);
let anchors = &out.subpaths[0].anchors;
let start = anchors.first().unwrap();
let end = anchors.last().unwrap();
assert_eq!(start.p, Point::new(40.0, 30.0));
assert_eq!(end.p, Point::new(60.0, 30.0));
for (actual, expected) in [
(start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())),
(end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())),
] {
assert!(actual.hypot() > 1e-9);
let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs();
assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees");
}
}
}
#[test]
fn twist_large_coordinate_joins_preserve_boundary_sides() {
use vectorcraft_geom::Anchor;
let center = 1e16;
for offset in [32.0, 64.0] {
let p = Point::new(center + offset, 0.0);
let line = PathData::single(SubPath::new(
vec![
Anchor::corner(Point::new(p.x - 18.0, 0.0)),
Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)),
Anchor::corner(Point::new(p.x + 18.0, 0.0)),
],
false,
));
let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3);
let join = &out.subpaths[0].anchors[1];
if offset == 64.0 {
assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0));
let actual = join.h_in - join.p;
let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2);
let error = actual.cross(expected).atan2(actual.dot(expected)).abs();
assert!(error < 1e-9, "{actual:?}");
} else {
let incoming = join.p - join.h_in;
let outgoing = join.h_out - join.p;
assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
assert!(incoming.dot(outgoing) > 0.0);
}
}
}
#[test]
fn twist_fractional_boundary_handles_use_each_sides_derivative() {
use vectorcraft_geom::Anchor;
for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] {
for x in [bounds.x0, bounds.x1] {
for angle in [90.0_f64, 400.0, -720.0] {
let p = Point::new(x, 30.0);
let line = PathData::single(SubPath::new(
vec![
Anchor::corner(Point::new(x - 3.0 * step, 30.0)),
Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)),
Anchor::corner(Point::new(x + 3.0 * step, 30.0)),
],
false,
));
let out = crate::distort::twist(&line, bounds, angle, 3);
assert!(
out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()),
"x={x} angle={angle}: {:?}",
out.subpaths[0].anchors
);
let join = &out.subpaths[0].anchors[1];
assert!(join.p.distance(p) < 1e-10, "{:?}", join.p);
let a = angle.to_radians();
let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] };
for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) {
let expected = vectorcraft_geom::Vec2::new(dx, dy);
let error = actual.cross(expected).atan2(actual.dot(expected)).abs();
assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]);
}
}
}
}
let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0);
let center = bounds.center();
let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false));
let out = crate::distort::twist(&line, bounds, 90.0, 3);
assert_eq!(out.subpaths[0].anchors[1].p, center);
let bounds = Rect::new(0.0, 30.0, 2e16, 30.0);
let p = Point::new(bounds.x1 - 8.0, 30.0);
let line = PathData::single(SubPath::new(
vec![
Anchor::corner(Point::new(p.x - 12.0, p.y)),
Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)),
Anchor::corner(Point::new(p.x + 12.0, p.y)),
],
false,
));
let out = crate::distort::twist(&line, bounds, 90.0, 3);
let join = &out.subpaths[0].anchors[1];
assert!(join.p.y - p.y > 10.0, "{:?}", join.p);
assert!(join.h_out.y - join.p.y < -4.0, "{join:?}");
}
#[test]
fn twist_fixes_the_outer_circle_and_rotates_inside() {
let out = run("distort.twist", json!({"angle": 0}), &square());
+334
View File
@@ -543,3 +543,337 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() {
assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0));
}
}
fn blue() -> Paint {
Paint::solid(Color::rgb(0.0, 0.0, 1.0))
}
fn green() -> Paint {
Paint::solid(Color::rgb(0.0, 1.0, 0.0))
}
/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3
/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and
/// stroked green 2 pt wide when `stroke`.
fn painted_type(id: u64, fill: bool, stroke: bool) -> Node {
use vectorcraft_doc::text::{CharStyle, TextObject};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
static FONT: std::sync::Once = std::sync::Once::new();
FONT.call_once(|| {
vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds"));
});
let style = CharStyle {
font_family: HEIGHT_FAMILY.into(),
size: 40.0,
fill: if fill { blue() } else { Paint::None },
stroke: if stroke { green() } else { Paint::None },
stroke_width: 2.0,
..Default::default()
};
Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style))))
}
/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke?
fn paints(n: &Node, fill: bool) -> bool {
use vectorcraft_doc::AppearanceItem;
let own = n.appearance.items.iter().any(|i| match i {
AppearanceItem::Fill(f) => fill && f.paint == blue(),
AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0,
});
own || n.children().into_iter().flatten().any(|c| paints(c, fill))
}
/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of
/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the
/// green stroke art right after the clip group (over it, outside the clip), and whether a green
/// stroke paints inside the clip group.
type Painted = (Rect, Option<Rect>, Option<Rect>, bool);
fn painted_clip(n: &Node) -> Option<Painted> {
let ch = n.children()?;
for (i, c) in ch.iter().enumerate() {
if let NodeKind::Group { children, clip: true } = &c.kind {
let region = clip_outline(children.first()?)?.0.bounding_box();
let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds());
let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds());
let inside = children.iter().skip(1).any(|m| paints(m, false));
return Some((region, fill, stroke, inside));
}
if let Some(found) = painted_clip(c) {
return Some(found);
}
}
None
}
fn near_rect(a: Rect, b: Rect) -> bool {
(a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5
}
#[test]
fn painted_clipping_type_survives_enclosing_geometry_effect() {
// Type that paints a fill, a stroke, both or neither clips a red square, in a group whose
// Transform (moving everything 10 pt down, beside other type that stays type in the export) or
// Offset Path reshapes its members: the canvas and the export keep the type's fill as art
// behind the square inside the clip and its stroke as art over the clip group, both reshaped
// with the clip.
let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box();
assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}");
let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))];
for effect in effects {
for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] {
let clipped = clip_group(2, painted_type(3, fill, stroke));
let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]);
outer.appearance.effects.push(effect.clone());
let canvas = crate::evaluate_container(None, &outer).unwrap();
let mut d = Document::new(400.0, 400.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, outer).unwrap();
let baked = bake_document(&d).unwrap();
let exported = baked.layers.iter().find_map(|l| painted_clip(l));
for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] {
let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id);
let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group"));
if effect.id == "distort.transform" {
assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}");
} else {
let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0);
assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt");
}
assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}");
assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}");
assert!(!inside, "{case}: the stroke paints outside the clip");
for art in fills.into_iter().chain(strokes) {
assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}");
}
}
}
}
}
/// The group in `n` that holds a clip group and then the green stroke art of its clipping type,
/// with that clip group.
fn stroke_wrapper(n: &Node) -> Option<(&Node, &Node)> {
let ch = n.children()?;
if let [inner, stroke, ..] = ch.as_slice()
&& matches!(inner.kind, NodeKind::Group { clip: true, .. })
&& !n.clips()
&& paints(stroke, false)
{
return Some((n, inner));
}
ch.iter().find_map(|c| stroke_wrapper(c))
}
#[test]
fn clipping_type_strokes_paint_over_a_knockout_clip_group() {
// A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its
// clipped art knocks out as the clip group says, and the type's stroke paints over it without
// knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's
// Transform around it, or by its own Offset Path.
use vectorcraft_doc::Knockout;
for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] {
for own in [false, true] {
let mut ty = painted_type(3, true, true);
if own {
ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1})));
}
let mut clipped = clip_group(2, ty);
clipped.knockout = knockout;
let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]);
if !own {
outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10})));
}
let mut d = Document::new(400.0, 400.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, outer.clone()).unwrap();
let baked = bake_document(&d).unwrap();
let canvas = if own { None } else { crate::evaluate_container(None, &outer) };
let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l));
for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] {
if own && what == "canvas" {
continue;
}
let case = format!("{what}, own effect {own}, knockout {knockout:?}");
let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip"));
assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before");
assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art");
}
}
}
}
#[test]
fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() {
// A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that
// strokes: the group's fill still paints inside the clip, and the type's stroke over it.
let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0));
let mut group = clip_group(2, painted_type(3, false, true));
group.appearance =
Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into();
let canvas = crate::evaluate_container(None, &group).unwrap();
let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap();
assert!(strokes.is_some() && !inside, "{canvas:?}");
let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") };
let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") };
let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow));
assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}");
assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}");
}
#[test]
fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() {
// A clip group with an unplaced linear gradient fill of its own and an Offset Path effect,
// clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient
// spans the region the clipping path clips to.
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut ty = painted_type(3, false, false);
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
for item in &mut ty.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
}
}
let mut group = clip_group(2, ty);
group.appearance =
Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into();
let canvas = crate::evaluate_container(None, &group).unwrap();
let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") };
let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") };
let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box();
let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() {
Paint::Gradient(g) => g.geom,
_ => None,
});
let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}"));
let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x));
assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}");
}
#[test]
fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() {
// A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect
// (moving everything 10 pt down, or scaling it to half its width around its middle) holds a
// clip group clipped by type whose stroke has a Transform effect moving it 60 pt right,
// outside the clip. On the canvas and in the export, the clip region is the type's glyphs
// reshaped by the group's effect, and the group's fill paints that region alone, its gradient
// spanning it: the moved stroke adds nothing to the region, the fill or the box the group's
// effect scales around.
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0));
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut ty = painted_type(3, false, false);
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
for item in &mut ty.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
}
}
let live = clip_outline(&ty).expect("the type clips").0.bounding_box();
let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0);
// Scaled to half its width around the middle of the clip, which the stroke does not move.
let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0);
let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1);
// The group's own fill art: every object outside the clip groups whose own fill is `paint`.
fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) {
let mine = n.appearance.items.iter().any(|i| match (i, paint) {
(vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)),
(vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p,
_ => false,
});
if mine {
out.push(n);
}
for c in n.children().into_iter().flatten().filter(|c| !c.clips()) {
own_fills(c, paint, out);
}
}
let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)];
for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) {
let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]);
outer.appearance =
Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into();
let canvas = crate::evaluate_container(None, &outer).unwrap();
let mut d = Document::new(400.0, 400.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, outer).unwrap();
let baked = bake_document(&d).unwrap();
let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group");
for (what, art) in [("canvas", &canvas), ("export", &*exported)] {
let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" });
let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}"));
assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}");
let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art"));
assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}");
let mut fills = vec![];
own_fills(art, &paint, &mut fills);
assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}");
let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap();
assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}");
if let Paint::Gradient(_) = paint {
for fill in fills {
let geom = match fill.appearance.fill_paint() {
Paint::Gradient(g) => g.geom,
_ => None,
};
let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}"));
let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x));
assert!(
(left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5,
"{case}: the gradient {geom:?} spans the clip {region:?}"
);
}
}
}
}
}
#[test]
fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() {
// A clip group with a placed linear gradient fill of its own, in a group with Free Distort,
// clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip:
// the gradient moves and scales from the clip's bounds, as for the same clip group whose type
// does not stroke. The moved stroke adds nothing to those bounds.
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
fn placed_geom(n: &Node) -> Option<vectorcraft_color::GradientGeom> {
if let Paint::Gradient(g) = n.appearance.fill_paint()
&& g.geom.is_some()
{
return g.geom;
}
n.children().into_iter().flatten().find_map(|c| placed_geom(c))
}
let ends = |stroke: bool| {
let mut ty = painted_type(3, false, false);
if stroke {
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
for item in &mut ty.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
}
}
}
let mut group = clip_group(2, ty);
group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into();
let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]);
let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
outer.appearance.effects.push(fx("distort.freeDistort", corners));
let canvas = crate::evaluate_container(None, &outer).unwrap();
if stroke {
assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}");
}
placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}"))
};
let (plain, stroked) = (ends(false), ends(true));
assert!(
plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5,
"the gradient {stroked:?} follows the clip as {plain:?} does"
);
}
+1 -1
View File
@@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of
/// segments into pieces within an anchor budget.
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces};
pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces};
/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight
/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px,