mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 21:42:59 -05:00
- Rendered eligibility reads only the top fill and strokes, the same items the solids are built from, so a lower gradient fill no longer blocks it. - A later Pathfinder effect falls back to shaded faces with the paths-only warning, as geometry effects do. - Live 3D edits show the fallback warning for one or several objects. - Raster Settings shows the resolution field as mixed when the selected objects' effective resolutions differ. - A curved highlight edge that crosses its neighbor keeps the outline.
982 lines
48 KiB
Rust
982 lines
48 KiB
Rust
//! Shared conversion and vector paint shading for the 3D effects' directional lights.
|
|
use serde_json::Value;
|
|
use vectorcraft_doc::color::{Color, Paint};
|
|
use vectorcraft_doc::{AppearanceItem, FillLayer};
|
|
|
|
fn parse(v: &Value) -> Option<Color> {
|
|
let s = v.as_str()?;
|
|
// Match the command's opaque RGB contract, before any parsing or allocation.
|
|
(s.len() == 7 && s.starts_with('#') && s.as_bytes().iter().skip(1).all(u8::is_ascii_hexdigit)).then(|| Color::from_hex(s)).flatten()
|
|
}
|
|
|
|
pub(crate) fn light_color(p: &Value) -> [f64; 3] {
|
|
p.get("lightColor").and_then(parse).unwrap_or(Color::WHITE).to_rgb_uncalibrated().map(f64::from)
|
|
}
|
|
|
|
pub(crate) fn validate(p: &Value) -> Result<(), String> {
|
|
if p.get("lightColor").is_some_and(|v| parse(v).is_none()) {
|
|
return Err("lightColor must be an opaque RGB color in #rrggbb form".into());
|
|
}
|
|
if let Some(list) = p.get("lights").filter(|v| !v.is_null()) {
|
|
parse_lights(list)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) fn lights(p: &Value) -> Option<vectorcraft_three_d::Lights> {
|
|
p.get("lights").filter(|v| !v.is_null()).and_then(|v| parse_lights(v).ok())
|
|
}
|
|
|
|
fn parse_lights(v: &Value) -> Result<vectorcraft_three_d::Lights, String> {
|
|
use vectorcraft_three_d::{Light, Lights, MAX_LIGHTS};
|
|
let list = v.as_array().filter(|v| !v.is_empty() && v.len() <= MAX_LIGHTS).ok_or("lights must contain one to ten lights")?;
|
|
let mut out = Vec::with_capacity(list.len());
|
|
for item in list {
|
|
let item = item.as_object().ok_or("each light must be an object")?;
|
|
if item.keys().any(|key| !["color", "intensity", "rotation", "height", "softness", "behind"].contains(&key.as_str())) {
|
|
return Err("unknown light setting: use color, intensity, rotation, height, softness or behind".into());
|
|
}
|
|
let defaults = Light::default();
|
|
let number = |key: &str, default: f64, min: f64, max: f64| -> Result<f64, String> {
|
|
match item.get(key) {
|
|
None => Ok(default),
|
|
Some(v) => v
|
|
.as_f64()
|
|
.filter(|n| n.is_finite() && *n >= min && *n <= max)
|
|
.ok_or_else(|| format!("light {key} must be a number from {min} to {max}")),
|
|
}
|
|
};
|
|
let color = match item.get("color") {
|
|
None => [1.0; 3],
|
|
Some(v) => parse(v).ok_or("light color must use opaque #rrggbb")?.to_rgb_uncalibrated().map(f64::from),
|
|
};
|
|
let behind = item.get("behind").map_or(Ok(false), |v| v.as_bool().ok_or("light behind must be true or false"))?;
|
|
out.push(Light {
|
|
color,
|
|
behind,
|
|
intensity: number("intensity", defaults.intensity * 100.0, 0.0, 100.0)? / 100.0,
|
|
rotation: number("rotation", defaults.rotation, -180.0, 180.0)?,
|
|
height: number("height", defaults.height, 0.0, 90.0)?,
|
|
softness: number("softness", defaults.softness * 100.0, 0.0, 100.0)? / 100.0,
|
|
});
|
|
}
|
|
Lights::new(&out)
|
|
}
|
|
|
|
pub(crate) fn shade(c: Color, rgb: [f64; 3]) -> Color {
|
|
let [r, g, b] = c.to_rgb();
|
|
Color::rgb(r * rgb[0] as f32, g * rgb[1] as f32, b * rgb[2] as f32)
|
|
}
|
|
|
|
pub(crate) fn smooth_paint(g: vectorcraft_three_d::LightGradient, color: Color) -> Paint {
|
|
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
|
let stops = g.stops().into_iter().map(|(at, rgb)| GradientStop::new(at, shade(color, rgb))).collect();
|
|
let mut p = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
|
p.geom = Some(GradientGeom { start: g.diffuse.start, end: g.diffuse.end, aspect: 1.0, focal: None });
|
|
Paint::Gradient(Box::new(p))
|
|
}
|
|
|
|
/// Multiply two independently placed vector gradients before applying the face's coverage
|
|
/// once. Separately antialiasing the source and light along each triangle edge leaves seams.
|
|
pub(crate) fn gradient_art(
|
|
id: vectorcraft_doc::NodeId,
|
|
path: &vectorcraft_geom::PathData,
|
|
paint: &Paint,
|
|
light: vectorcraft_three_d::LightGradient,
|
|
) -> vectorcraft_doc::Node {
|
|
composed_art(id, path, paint, Ramp::Single(light), 0.75)
|
|
}
|
|
|
|
pub(crate) fn rgb_gradient_art(
|
|
id: vectorcraft_doc::NodeId,
|
|
path: &vectorcraft_geom::PathData,
|
|
paint: &Paint,
|
|
light: vectorcraft_three_d::RgbGradient,
|
|
) -> vectorcraft_doc::Node {
|
|
composed_art(id, path, paint, Ramp::Rgb(light), 0.75)
|
|
}
|
|
|
|
/// The narrow stroke of a facet's own `paint`, `width` wide, that closes the hairline seam between
|
|
/// it and its neighbors where each is antialiased alone. Its joins are round: a facet seen almost
|
|
/// edge-on is a sharp sliver, and a mitered seam would reach far past its tip as a thorn, where a
|
|
/// round one reaches no more than half its width past the facet. Revolve's meets() counts on a
|
|
/// stroked seam reaching no more than half its width; faces drawn as clipped groups (whose clip,
|
|
/// in `composed_art`, already outlines the seam with round joins) are measured by their box.
|
|
pub(crate) fn seam_stroke(paint: Paint, width: f64) -> vectorcraft_doc::StrokeLayer {
|
|
let mut edge = vectorcraft_doc::StrokeLayer::new(paint, width);
|
|
edge.join = vectorcraft_doc::LineJoin::Round;
|
|
edge
|
|
}
|
|
|
|
/// Smooth Inflate triangles keep the seam within their narrow projected footprint.
|
|
pub(crate) fn facet_art(
|
|
id: vectorcraft_doc::NodeId,
|
|
path: &vectorcraft_geom::PathData,
|
|
paint: &Paint,
|
|
light: vectorcraft_three_d::RgbGradient,
|
|
seam: f64,
|
|
) -> vectorcraft_doc::Node {
|
|
let [r, g, b] = light.channels;
|
|
if r == g && g == b {
|
|
let light = vectorcraft_three_d::LightGradient { diffuse: r, ambient: 0.0, color: [1.0; 3] };
|
|
if let Some(color) = paint.color() {
|
|
let paint = smooth_paint(light, color);
|
|
let edge = seam_stroke(paint.clone(), seam);
|
|
return vectorcraft_doc::Node::path(
|
|
id,
|
|
path.clone(),
|
|
vectorcraft_doc::Appearance {
|
|
items: vec![AppearanceItem::Fill(FillLayer::new(paint)), AppearanceItem::Stroke(edge)],
|
|
..Default::default()
|
|
},
|
|
);
|
|
}
|
|
return composed_art(id, path, paint, Ramp::Single(light), seam);
|
|
}
|
|
composed_art(id, path, paint, Ramp::Rgb(light), seam)
|
|
}
|
|
|
|
/// The fills that screen `highlight`, the light a material reflects over a face's paint, over that
|
|
/// paint: one gray ramp when its three channels match, else one ramp per channel in that channel's
|
|
/// primary (Screen of disjoint primaries adds each channel on its own), or one flat color without
|
|
/// a ramp. A channel with no light anywhere on the face takes no fill.
|
|
fn highlight_fills(highlight: vectorcraft_three_d::Highlight) -> Vec<AppearanceItem> {
|
|
use vectorcraft_doc::color::BlendMode;
|
|
let screen = |paint: Paint| {
|
|
let mut fill = FillLayer::new(paint);
|
|
fill.blend = BlendMode::Screen;
|
|
AppearanceItem::Fill(fill)
|
|
};
|
|
let lit = |g: &vectorcraft_three_d::ShadeGradient| g.brightness.iter().any(|b| *b > 0.0);
|
|
let Some(ramp) = highlight.ramp else {
|
|
let [r, g, b] = highlight.flat.map(|v| v.clamp(0.0, 1.0) as f32);
|
|
return if r > 0.0 || g > 0.0 || b > 0.0 { vec![screen(Paint::solid(Color::rgb(r, g, b)))] } else { vec![] };
|
|
};
|
|
let [r, g, b] = ramp.channels;
|
|
if r == g && g == b {
|
|
let light = vectorcraft_three_d::LightGradient { diffuse: r, ambient: 0.0, color: [1.0; 3] };
|
|
return if lit(&r) { vec![screen(smooth_paint(light, Color::WHITE))] } else { vec![] };
|
|
}
|
|
ramp.channels
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, g)| lit(g))
|
|
.map(|(channel, g)| {
|
|
let mut color = [0.0; 3];
|
|
if let Some(value) = color.get_mut(channel) {
|
|
*value = 1.0;
|
|
}
|
|
screen(smooth_paint(vectorcraft_three_d::LightGradient { diffuse: *g, ambient: 0.0, color }, Color::WHITE))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// The path that screens `highlight` over a face of outline `path` closed by a seam `seam` wide:
|
|
/// the highlight's fills ([`highlight_fills`]) on the face and its seam ([`seamed_fill`], or for a
|
|
/// curved face [`curved_seamed_fill`]; else the outline alone). Each fill covers the face and its
|
|
/// seam once. `None` without a highlight or when it holds no light.
|
|
pub(crate) fn highlight_over(
|
|
id: vectorcraft_doc::NodeId,
|
|
path: &vectorcraft_geom::PathData,
|
|
seam: f64,
|
|
highlight: Option<vectorcraft_three_d::Highlight>,
|
|
) -> Option<vectorcraft_doc::Node> {
|
|
let items = highlight.map(highlight_fills).unwrap_or_default();
|
|
if items.is_empty() {
|
|
return None;
|
|
}
|
|
let shape = seamed_fill(path, seam).or_else(|| curved_seamed_fill(path, seam)).unwrap_or_else(|| path.clone());
|
|
Some(vectorcraft_doc::Node::path(id, shape, vectorcraft_doc::Appearance { items, ..Default::default() }))
|
|
}
|
|
|
|
/// How far, in points, a curved face's flattened outline may stray from its curves when
|
|
/// [`curved_seamed_fill`] tests it.
|
|
const HIGHLIGHT_FLATNESS: f64 = 0.05;
|
|
|
|
/// Curved face `path` and its round seam `seam` wide as one path to fill: the [`footprint`] of the
|
|
/// curves themselves, as the face's clip is. `None` unless `path` has curves and its outline,
|
|
/// flattened to within [`HIGHLIGHT_FLATNESS`], is a polygon [`seamed_fill`] takes: one closed
|
|
/// contour of up to [`SEAMED_FILL_EDGES`] edges that does not fold over itself. Flattening stops
|
|
/// once the outline passes that many edges.
|
|
fn curved_seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
|
|
use kurbo::{ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Shape};
|
|
let bez = path.to_bezpath();
|
|
let elements = bez.elements();
|
|
if elements.len() > SEAMED_FILL_EDGES + 2 || !elements.iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))) {
|
|
return None;
|
|
}
|
|
let segments: Vec<PathSeg> = bez.segments().collect();
|
|
for (i, a) in segments.iter().enumerate() {
|
|
let b = &segments[(i + 1) % segments.len()];
|
|
if matches!((a, b), (PathSeg::Line(_), PathSeg::Line(_))) {
|
|
continue;
|
|
}
|
|
let controls = |s: &PathSeg| match s {
|
|
PathSeg::Line(s) => vec![s.p0, s.p1],
|
|
PathSeg::Quad(s) => vec![s.p0, s.p1, s.p2],
|
|
PathSeg::Cubic(s) => vec![s.p0, s.p1, s.p2, s.p3],
|
|
};
|
|
let seam = a.end();
|
|
let directions: Vec<_> = controls(a)
|
|
.into_iter()
|
|
.map(|p| p - seam)
|
|
.chain(controls(b).into_iter().map(|p| seam - p))
|
|
.filter(|v| v.hypot() > 0.0)
|
|
.map(|v| v / v.hypot())
|
|
.collect();
|
|
let separated = directions.iter().any(|a| {
|
|
directions.iter().any(|b| {
|
|
let axis = *a + *b;
|
|
directions.iter().all(|v| axis.dot(*v) > 1e-12)
|
|
})
|
|
});
|
|
if !separated {
|
|
return None;
|
|
}
|
|
}
|
|
let mut flat = vectorcraft_geom::BezPath::new();
|
|
let mut overflow = false;
|
|
let mut last = kurbo::Point::ZERO;
|
|
for el in elements {
|
|
if overflow {
|
|
break;
|
|
}
|
|
let from = last;
|
|
let controls = match el {
|
|
PathEl::QuadTo(a, b) => Some([from, *a, *b, *b]),
|
|
PathEl::CurveTo(a, b, c) => Some([from, *a, *b, *c]),
|
|
_ => None,
|
|
};
|
|
if let Some(controls) = controls {
|
|
let length: f64 = controls.windows(2).map(|pair| pair[0].distance(pair[1])).sum();
|
|
if !length.is_finite()
|
|
|| length > HIGHLIGHT_FLATNESS * vectorcraft_geom::MAX_FLATTEN_PER_CURVE.powi(2)
|
|
|| controls.iter().any(|p| !(p.x.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH && p.y.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH))
|
|
{
|
|
return None;
|
|
}
|
|
}
|
|
last = match el {
|
|
PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => *p,
|
|
PathEl::ClosePath => last,
|
|
};
|
|
let curve = match el {
|
|
PathEl::QuadTo(a, b) => Some(PathSeg::Quad(kurbo::QuadBez::new(from, *a, *b))),
|
|
PathEl::CurveTo(a, b, c) => Some(PathSeg::Cubic(kurbo::CubicBez::new(from, *a, *b, *c))),
|
|
_ => None,
|
|
};
|
|
// Each curve piece is monotonic in both coordinates before flattening.
|
|
let pieces = curve.map_or_else(
|
|
|| vec![(from, *el)],
|
|
|curve| {
|
|
curve
|
|
.extrema_ranges()
|
|
.into_iter()
|
|
.map(|range| {
|
|
let piece = curve.subsegment(range);
|
|
(piece.start(), piece.as_path_el())
|
|
})
|
|
.collect()
|
|
},
|
|
);
|
|
for (from, el) in pieces {
|
|
if overflow {
|
|
break;
|
|
}
|
|
let start = [PathEl::MoveTo(from)].into_iter().filter(|_| !matches!(el, PathEl::MoveTo(_)));
|
|
let mut skip = usize::from(!matches!(el, PathEl::MoveTo(_)));
|
|
vectorcraft_geom::flatten(start.chain([el]), HIGHLIGHT_FLATNESS, |e| {
|
|
if skip > 0 {
|
|
skip -= 1;
|
|
} else if flat.elements().len() > SEAMED_FILL_EDGES + 2 {
|
|
overflow = true;
|
|
} else {
|
|
flat.push(e);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
if overflow {
|
|
return None;
|
|
}
|
|
// Each flattened edge may be HIGHLIGHT_FLATNESS away from its curve.
|
|
seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), seam, 2.0 * HIGHLIGHT_FLATNESS)?;
|
|
let fill = footprint(&bez, seam);
|
|
(fill.bounding_box().is_finite() && fill.area().abs() >= bez.area().abs()).then(|| vectorcraft_geom::PathData::from_bezpath(&fill))
|
|
}
|
|
|
|
/// `face`, the art of a face of outline `path` closed by a seam `seam` wide, with `highlight`
|
|
/// screened over it: a group of the face and the highlight's path on the face and its seam
|
|
/// ([`highlight_over`]). An opacity mask on the face moves to the group, so it covers the
|
|
/// highlight too. `face` may hold the parts of graphics drawn on it: the highlight then lies over
|
|
/// them too. `face` as it is without a highlight or when it holds no light. The face is drawn
|
|
/// opaque: a transparent paint's coverage is a mask over the whole surface
|
|
/// ([`opaque_surface_paint`]), so the highlight and the face take it once.
|
|
pub(crate) fn highlighted(
|
|
id: vectorcraft_doc::NodeId,
|
|
mut face: vectorcraft_doc::Node,
|
|
path: &vectorcraft_geom::PathData,
|
|
seam: f64,
|
|
highlight: Option<vectorcraft_three_d::Highlight>,
|
|
) -> vectorcraft_doc::Node {
|
|
use std::sync::Arc;
|
|
let Some(over) = highlight_over(id, path, seam, highlight) else { return face };
|
|
let mask = if face.extras().mask.is_some() { face.extras_mut().mask.take() } else { None };
|
|
let mut group = vectorcraft_doc::Node::group(id, vec![Arc::new(face), Arc::new(over)]);
|
|
if mask.is_some() {
|
|
group.extras_mut().mask = mask;
|
|
}
|
|
group
|
|
}
|
|
|
|
/// The width of the seam stroke of a facet's underlay: a round stroke that reaches 1 pt past each
|
|
/// edge, over the pixels that the antialiased edges of two neighboring facets each cover only in
|
|
/// part at 1:1. A clip to the surface's outline removes what it paints past the surface.
|
|
pub(crate) const UNDERLAY_SEAM: f64 = 2.0;
|
|
|
|
/// The area facet `path` and its round seam stroke `seam` wide paint together: the stroke's outer
|
|
/// contours and the facet, all wound one way with a positive area. The stroke's inner contours,
|
|
/// wound the other way, are left out: the facet covers them, and contours that cancel each other
|
|
/// leave partial coverage where a union of footprints meets at a pixel.
|
|
pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcraft_geom::BezPath {
|
|
use kurbo::{PathEl, Shape};
|
|
let stroke = kurbo::stroke(path.iter(), &kurbo::Stroke::new(seam).with_join(kurbo::Join::Round), &kurbo::StrokeOpts::default(), 0.05);
|
|
let sign = if stroke.area() < 0.0 { -1.0 } else { 1.0 };
|
|
let mut footprint = vectorcraft_geom::BezPath::new();
|
|
let mut contour = vectorcraft_geom::BezPath::new();
|
|
for el in stroke.elements().iter().chain(std::iter::once(&PathEl::MoveTo(kurbo::Point::ZERO))) {
|
|
if matches!(el, PathEl::MoveTo(_)) && !contour.elements().is_empty() {
|
|
if contour.area() * sign >= 0.0 {
|
|
footprint.extend(contour.iter());
|
|
}
|
|
contour = vectorcraft_geom::BezPath::new();
|
|
}
|
|
contour.push(*el);
|
|
}
|
|
let mut boundary = path.clone();
|
|
if boundary.area() * sign < 0.0 {
|
|
boundary = boundary.reverse_subpaths();
|
|
}
|
|
footprint.extend(boundary.iter());
|
|
if sign < 0.0 { footprint.reverse_subpaths() } else { footprint }
|
|
}
|
|
|
|
/// The most edges a facet may have for [`seamed_fill`] to test it for crossing edges.
|
|
const SEAMED_FILL_EDGES: usize = 256;
|
|
|
|
/// Facet `path` and its round seam `seam` wide as one path to fill ([`footprint`]), so that at an
|
|
/// edge pixel the facet and its seam cover it once between them, not a fill's coverage and then a
|
|
/// stroke's over it. `None` unless `path` is one closed polygon of up to [`SEAMED_FILL_EDGES`]
|
|
/// finite edges, with an area, and with no two edges that are not neighbors touching: only there
|
|
/// does the footprint's nonzero fill cover the facet and its seam and nothing more. `None` too for
|
|
/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area
|
|
/// than the facet.
|
|
pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
|
|
seamed_fill_with_clearance(path, seam, 0.0)
|
|
}
|
|
|
|
/// [`seamed_fill`], also `None` when two edges that are not neighbors come within `clearance` of
|
|
/// each other.
|
|
fn seamed_fill_with_clearance(path: &vectorcraft_geom::PathData, seam: f64, clearance: f64) -> Option<vectorcraft_geom::PathData> {
|
|
use kurbo::{Line, ParamCurveNearest, PathEl, Point, Shape};
|
|
if !(seam.is_finite() && seam > 0.0) {
|
|
return None;
|
|
}
|
|
let bez = path.to_bezpath();
|
|
let mut elements = bez.elements().iter();
|
|
let Some(PathEl::MoveTo(first)) = elements.next() else { return None };
|
|
let mut points = vec![*first];
|
|
let mut closed = false;
|
|
for el in elements {
|
|
match el {
|
|
PathEl::LineTo(p) if !closed => points.push(*p),
|
|
PathEl::ClosePath if !closed => closed = true,
|
|
_ => return None,
|
|
}
|
|
}
|
|
if points.len() > 1 && points.first() == points.last() {
|
|
points.pop();
|
|
}
|
|
let area = bez.area().abs();
|
|
if !closed || !(3..=SEAMED_FILL_EDGES).contains(&points.len()) || points.iter().any(|p| !p.is_finite()) || !area.is_finite() || area <= 1e-9 {
|
|
return None;
|
|
}
|
|
let side = |a: Point, b: Point, c: Point| (b - a).cross(c - a);
|
|
let touch = |a: Point, b: Point, c: Point, d: Point| {
|
|
let boxes = a.x.min(b.x) <= c.x.max(d.x) && c.x.min(d.x) <= a.x.max(b.x) && a.y.min(b.y) <= c.y.max(d.y) && c.y.min(d.y) <= a.y.max(b.y);
|
|
boxes && side(a, b, c) * side(a, b, d) <= 0.0 && side(c, d, a) * side(c, d, b) <= 0.0
|
|
};
|
|
let n = points.len();
|
|
let edge = |i: usize| (points[i], points[(i + 1) % n]);
|
|
for i in 0..n {
|
|
for j in i + 2..n {
|
|
if i == 0 && j == n - 1 {
|
|
continue;
|
|
}
|
|
let ((a, b), (c, d)) = (edge(i), edge(j));
|
|
if touch(a, b, c, d) {
|
|
return None;
|
|
}
|
|
if clearance > 0.0 {
|
|
let ab = Line::new(a, b);
|
|
let cd = Line::new(c, d);
|
|
let distance_sq = ab
|
|
.nearest(c, 1e-6)
|
|
.distance_sq
|
|
.min(ab.nearest(d, 1e-6).distance_sq)
|
|
.min(cd.nearest(a, 1e-6).distance_sq)
|
|
.min(cd.nearest(b, 1e-6).distance_sq);
|
|
if distance_sq <= clearance * clearance {
|
|
return None;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let fill = footprint(&bez, seam);
|
|
(fill.bounding_box().is_finite() && fill.area().abs() >= area).then(|| vectorcraft_geom::PathData::from_bezpath(&fill))
|
|
}
|
|
|
|
/// Colored-light facets `faces` (in drawing order) drawn over an underlay of themselves, the same
|
|
/// facets grown to seams [`UNDERLAY_SEAM`] wide, all clipped once to the union of the facets'
|
|
/// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave
|
|
/// uncovered with the neighbors' own colors, so the background does not show through. `None` unless
|
|
/// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed
|
|
/// in a clip of its footprint, neither with an opacity mask. A face drawn with the parts of Inflate's
|
|
/// graphics on it, a group of the facet and those parts, takes its facet's underlay and stays in the
|
|
/// order with its parts, which are cut to the facet's outline, so the clip keeps them. So does a
|
|
/// facet with a material's highlight screened over it ([`highlighted`]), which lies on the facet
|
|
/// and its seam.
|
|
pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
|
|
use std::sync::Arc;
|
|
use vectorcraft_doc::{Node, NodeKind};
|
|
let facet = |face: &Arc<Node>| {
|
|
let mut facet = face.clone();
|
|
while let NodeKind::Group { children, clip: false } = &facet.kind
|
|
&& facet.extras().mask.is_none()
|
|
{
|
|
facet = children.first()?.clone();
|
|
}
|
|
Some(facet)
|
|
};
|
|
let facets: Vec<Arc<Node>> = faces.iter().map(facet).collect::<Option<_>>()?;
|
|
let (clip, mut underlay) = underlay(id, &facets)?;
|
|
underlay.extend(faces.iter().cloned());
|
|
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
|
|
}
|
|
|
|
/// The parts of [`sealed`] for `faces`: a path of the union of the facets' footprints, to clip to,
|
|
/// and the facets grown to seams [`UNDERLAY_SEAM`] wide, in the same order. `None` under the same
|
|
/// conditions as [`sealed`].
|
|
pub(crate) fn underlay(
|
|
id: vectorcraft_doc::NodeId,
|
|
faces: &[std::sync::Arc<vectorcraft_doc::Node>],
|
|
) -> Option<(vectorcraft_doc::Node, Vec<std::sync::Arc<vectorcraft_doc::Node>>)> {
|
|
use std::sync::Arc;
|
|
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
|
let mut outline = vectorcraft_geom::BezPath::new();
|
|
let mut underlay = Vec::with_capacity(faces.len());
|
|
for face in faces {
|
|
if face.extras().mask.is_some() {
|
|
return None;
|
|
}
|
|
match &face.kind {
|
|
NodeKind::Path { clipping: false, .. } => {
|
|
let path = face.path_data()?.to_bezpath();
|
|
let mut seam = None;
|
|
let mut grown = (**face).clone();
|
|
for item in &mut grown.appearance.items {
|
|
if let AppearanceItem::Stroke(s) = item {
|
|
seam = Some(seam.map_or(s.width, |w: f64| w.max(s.width)));
|
|
s.width = UNDERLAY_SEAM;
|
|
}
|
|
}
|
|
outline.extend(footprint(&path, seam?).iter());
|
|
underlay.push(Arc::new(grown));
|
|
}
|
|
NodeKind::Group { children, clip: true } if children.len() == 2 => {
|
|
let clip = children.first()?.path_data()?.to_bezpath();
|
|
let wider = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint(&clip, UNDERLAY_SEAM)), Appearance::default());
|
|
let colors = children.get(1)?.clone();
|
|
outline.extend(clip.iter());
|
|
underlay.push(Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(wider), colors], clip: true })));
|
|
}
|
|
_ => return None,
|
|
}
|
|
}
|
|
Some((Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()), underlay))
|
|
}
|
|
|
|
/// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each
|
|
/// channel, an underlay of the facets with wide seams lies under the facets themselves, so a
|
|
/// shared edge is opaque in that channel's own light before the channels are screened together;
|
|
/// the black backdrop shows only outside the surface, which the clip removes. Each facet over the
|
|
/// underlay is one fill of the facet and its seam together ([`seamed_fill`]), or a fill and a seam
|
|
/// stroke where that is `None`.
|
|
pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_three_d::Facet], paint: &Paint) -> vectorcraft_doc::Node {
|
|
use kurbo::Shape;
|
|
use std::sync::Arc;
|
|
use vectorcraft_doc::color::BlendMode;
|
|
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
|
use vectorcraft_geom::{BezPath, PathData, Rect, shapes};
|
|
|
|
let mut boundary = BezPath::new();
|
|
let mut bounds = None;
|
|
for face in facets {
|
|
let path = face.path();
|
|
if let Some(b) = path.bounds() {
|
|
bounds = Some(bounds.map_or(b, |r: Rect| r.union(b)));
|
|
}
|
|
let mut contour = path.to_bezpath();
|
|
if contour.area() < 0.0 {
|
|
contour = contour.reverse_subpaths();
|
|
}
|
|
boundary.extend(contour.iter());
|
|
}
|
|
let clip = Node::path(id, PathData::from_bezpath(&boundary), Appearance::default());
|
|
let bounds = bounds.unwrap_or(Rect::ZERO).inflate(1.0, 1.0);
|
|
let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0));
|
|
let seam = |face: &vectorcraft_three_d::Facet| (face.thickness() / 2.0).clamp(0.05, 0.75);
|
|
let exact: Vec<Option<PathData>> = facets.iter().map(|face| seamed_fill(&face.path(), seam(face))).collect();
|
|
let channels = (0..3)
|
|
.map(|channel| {
|
|
let mut color = [0.0; 3];
|
|
if let Some(value) = color.get_mut(channel) {
|
|
*value = 1.0;
|
|
}
|
|
let paints: Vec<Paint> = facets
|
|
.iter()
|
|
.map(|face| {
|
|
if let Some(ramp) = face.rgb_gradient {
|
|
smooth_paint(vectorcraft_three_d::LightGradient { diffuse: ramp.channels[channel], ambient: 0.0, color }, Color::WHITE)
|
|
} else {
|
|
Paint::solid(shade(Color::WHITE, color.map(|c| c * face.illumination[channel])))
|
|
}
|
|
})
|
|
.collect();
|
|
let draw = |seam: fn(&vectorcraft_three_d::Facet) -> f64| -> Vec<Arc<Node>> {
|
|
facets
|
|
.iter()
|
|
.zip(&paints)
|
|
.map(|(face, paint)| {
|
|
let edge = seam_stroke(paint.clone(), seam(face));
|
|
Arc::new(Node::path(
|
|
id,
|
|
face.path(),
|
|
Appearance {
|
|
items: vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(edge)],
|
|
..Default::default()
|
|
},
|
|
))
|
|
})
|
|
.collect()
|
|
};
|
|
let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))];
|
|
children.extend(draw(|_| UNDERLAY_SEAM));
|
|
children.extend(facets.iter().zip(&exact).zip(&paints).map(|((face, fill), paint)| {
|
|
let mut items = vec![AppearanceItem::Fill(FillLayer::new(paint.clone()))];
|
|
let path = match fill {
|
|
Some(fill) => fill.clone(),
|
|
None => {
|
|
items.push(AppearanceItem::Stroke(seam_stroke(paint.clone(), seam(face))));
|
|
face.path()
|
|
}
|
|
};
|
|
Arc::new(Node::path(id, path, Appearance { items, ..Default::default() }))
|
|
}));
|
|
let mut group = Node::group(id, children);
|
|
group.isolate = true;
|
|
group.blend = BlendMode::Screen;
|
|
Arc::new(group)
|
|
})
|
|
.collect();
|
|
let mut light = Node::group(id, channels);
|
|
light.isolate = true;
|
|
light.blend = BlendMode::Multiply;
|
|
let mut colors = Node::group(id, vec![Arc::new(cover(paint.clone())), Arc::new(light)]);
|
|
colors.isolate = true;
|
|
Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(colors)], clip: true })
|
|
}
|
|
|
|
enum Ramp {
|
|
Single(vectorcraft_three_d::LightGradient),
|
|
Rgb(vectorcraft_three_d::RgbGradient),
|
|
}
|
|
|
|
/// Separate a gradient's color and coverage so a tessellated surface can apply its opacity
|
|
/// once, instead of building opacity at the overlapping seam strokes of adjacent faces.
|
|
pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option<Paint>) {
|
|
let mut base = paint.clone();
|
|
let mut mask = paint.clone();
|
|
let mut transparent = false;
|
|
if let (Paint::Gradient(b), Paint::Gradient(m)) = (&mut base, &mut mask) {
|
|
b.swatch = None;
|
|
m.swatch = None;
|
|
for (b, m) in b.gradient.stops.iter_mut().zip(&mut m.gradient.stops) {
|
|
transparent |= b.opacity != 1.0;
|
|
b.opacity = 1.0;
|
|
m.color = Color::WHITE;
|
|
m.swatch = None;
|
|
m.tint = 1.0;
|
|
}
|
|
if let (Some(b), Some(m)) = (&mut b.freeform, &mut m.freeform) {
|
|
for (b, m) in b.points.iter_mut().zip(&mut m.points) {
|
|
transparent |= b.opacity != 1.0;
|
|
b.opacity = 1.0;
|
|
m.color = Color::WHITE;
|
|
}
|
|
}
|
|
}
|
|
(base, transparent.then_some(mask))
|
|
}
|
|
|
|
/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient
|
|
/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the
|
|
/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement.
|
|
/// An opaque gradient is returned as [`opaque_paint`] returns it.
|
|
pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option<Paint>) {
|
|
let (base, mask) = opaque_paint(paint);
|
|
if mask.is_none() || !matches!(paint, Paint::Gradient(_)) {
|
|
return (base, mask);
|
|
}
|
|
let mut pinned = paint.clone();
|
|
if let Paint::Gradient(g) = &mut pinned {
|
|
g.pin(bounds().inflate(1.0, 1.0));
|
|
}
|
|
opaque_paint(&pinned)
|
|
}
|
|
|
|
fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node {
|
|
use std::sync::Arc;
|
|
use vectorcraft_doc::color::BlendMode;
|
|
use vectorcraft_doc::{Appearance, Node, NodeKind, OpacityMask};
|
|
use vectorcraft_geom::{Rect, shapes};
|
|
// An unplaced gradient (and a freeform gradient without points) stays fitted to the face's
|
|
// bounds grown by 1 pt, not to the larger cover below.
|
|
let mut paint = paint.clone();
|
|
if let Paint::Gradient(g) = &mut paint {
|
|
g.pin(path.bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0));
|
|
}
|
|
let (base, mask) = opaque_paint(&paint);
|
|
// Clip once to the union of this single-contour face and its round seam stroke.
|
|
let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint(&path.to_bezpath(), seam)), Appearance::default());
|
|
// Opaque rectangles cover the complete seam stroke, without separately antialiasing
|
|
// either ramp. Opaque sources need only vector clipping, not full-frame opacity masks. They
|
|
// reach at least half a point past the seam stroke grown for an underlay ([`sealed`]), so
|
|
// their own edges stay outside either clip.
|
|
let margin = seam.max(1.0) + UNDERLAY_SEAM / 2.0;
|
|
let bounds = path.bounds().unwrap_or(Rect::ZERO).inflate(margin, margin);
|
|
let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0));
|
|
let mut illumination = match light {
|
|
Ramp::Single(light) => cover(smooth_paint(light, Color::WHITE)),
|
|
Ramp::Rgb(light) => {
|
|
let channels = light
|
|
.channels
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(channel, gradient)| {
|
|
let mut color = [0.0; 3];
|
|
if let Some(value) = color.get_mut(channel) {
|
|
*value = 1.0;
|
|
}
|
|
let mut layer = cover(smooth_paint(vectorcraft_three_d::LightGradient { diffuse: *gradient, ambient: 0.0, color }, Color::WHITE));
|
|
// Screen adds disjoint R, G and B channels exactly; no light is clamped
|
|
// separately. Each ramp already holds the sum of all directional lights.
|
|
layer.blend = BlendMode::Screen;
|
|
Arc::new(layer)
|
|
})
|
|
.collect();
|
|
let mut group = Node::group(id, channels);
|
|
group.isolate = true;
|
|
group
|
|
}
|
|
};
|
|
illumination.blend = BlendMode::Multiply;
|
|
let mut colors = Node::group(id, vec![Arc::new(cover(base)), Arc::new(illumination)]);
|
|
colors.isolate = true;
|
|
// Keep isolation inside the clip: the clip then applies to the finished colors,
|
|
// rather than separately antialiasing each of the two gradient drawings.
|
|
let mut face = Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(colors)], clip: true });
|
|
if let Some(mask) = mask {
|
|
face.extras_mut().mask = Some(Box::new(OpacityMask::new(cover(mask), true)));
|
|
}
|
|
face
|
|
}
|
|
|
|
pub(crate) fn fills(paint: &Paint, rgb: [f64; 3], brightness: f64, colored: bool) -> Vec<AppearanceItem> {
|
|
let shade = |c: Color| shade(c, rgb);
|
|
if let Some(c) = paint.color() {
|
|
return vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(shade(c))))];
|
|
}
|
|
// Keep the white-light gradient treatment identical to existing documents. Colored light
|
|
// shades the ramp itself, keeping placement, stops, midpoint and opacity as vector data.
|
|
if matches!(paint, Paint::Gradient(_)) && colored {
|
|
let mut shaded = paint.clone();
|
|
vectorcraft_doc::recolor::map_paint(&mut shaded, &shade);
|
|
if let Paint::Gradient(g) = &mut shaded {
|
|
g.swatch = None;
|
|
}
|
|
return vec![AppearanceItem::Fill(FillLayer::new(shaded))];
|
|
}
|
|
// Pattern tiles remain referenced artwork. Retain their existing neutral shadow
|
|
// approximation; tinting arbitrary pattern contents needs document-level evaluation.
|
|
let mut shadow = FillLayer::new(Paint::solid(Color::BLACK));
|
|
shadow.opacity = (1.0 - brightness) as f32;
|
|
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Fill(shadow)]
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
|
use vectorcraft_geom::Point;
|
|
|
|
#[test]
|
|
fn command_contract_is_strict_and_loaded_invalid_colors_fall_back_to_white() {
|
|
assert_eq!(light_color(&json!({})), [1.0; 3]);
|
|
assert_eq!(light_color(&json!({"lightColor":"#FF0000"})), [1.0, 0.0, 0.0]);
|
|
for v in [json!("#ff0"), json!("#ffffff80"), json!("blue"), json!("#gg0000"), json!(null), json!([1, 0, 0])] {
|
|
let p = json!({"lightColor":v});
|
|
assert!(validate(&p).is_err(), "{p}");
|
|
assert_eq!(light_color(&p), [1.0; 3]);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn malformed_loaded_lists_keep_the_legacy_light_and_valid_lists_override_it() {
|
|
for value in [json!([]), json!(vec![json!({}); 11]), json!([false]), json!([{"height": 91}]), json!([{"color":"#ff0"}])] {
|
|
let p = json!({"lights": value, "lightColor":"#ff0000"});
|
|
assert!(lights(&p).is_none());
|
|
assert_eq!(light_color(&p), [1.0, 0.0, 0.0]);
|
|
assert!(validate(&p).is_err());
|
|
}
|
|
let p = json!({"lights":[{}, {"color":"#0000ff","intensity":40}], "lightColor":"#ff0000"});
|
|
let list = lights(&p).unwrap();
|
|
assert_eq!(list.iter().count(), 2);
|
|
assert_eq!(*list.iter().next().unwrap(), vectorcraft_three_d::Light::default());
|
|
assert_eq!(list.iter().nth(1).unwrap().color, [0.0, 0.0, 1.0]);
|
|
}
|
|
|
|
#[test]
|
|
fn colored_gradient_keeps_placement_alpha_and_midpoints() {
|
|
let mut stop = GradientStop::new(0.0, Color::WHITE);
|
|
stop.opacity = 0.4;
|
|
stop.midpoint = 0.3;
|
|
let g = GradientPaint {
|
|
gradient: Gradient::new(GradientKind::Linear, vec![stop, GradientStop::new(1.0, Color::BLACK)]),
|
|
geom: Some(GradientGeom { start: Point::new(20.0, 30.0), end: Point::new(100.0, 30.0), aspect: 1.0, focal: None }),
|
|
angle: 0.0,
|
|
swatch: None,
|
|
freeform: None,
|
|
};
|
|
let paint = Paint::Gradient(Box::new(g.clone()));
|
|
let items = fills(&paint, [1.0, 0.25, 0.25], 1.0, true);
|
|
let Paint::Gradient(shaded) = items[0].paint() else { panic!("vector gradient") };
|
|
assert_eq!(shaded.geom, g.geom);
|
|
assert_eq!(shaded.gradient.stops[0].color.to_rgb(), [1.0, 0.25, 0.25]);
|
|
assert_eq!(shaded.gradient.stops[0].opacity, 0.4);
|
|
assert_eq!(shaded.gradient.stops[0].midpoint, 0.3);
|
|
assert_eq!(shaded.gradient.stops[1].color, Color::BLACK);
|
|
assert_eq!(paint, Paint::Gradient(Box::new(g)));
|
|
let white = fills(&paint, [0.4; 3], 0.4, false);
|
|
assert_eq!(white[0].paint(), &paint, "white retains the previous gradient treatment");
|
|
assert_eq!(white.len(), 2);
|
|
let unlit = fills(&paint, [0.25; 3], 0.25, true);
|
|
assert_eq!(unlit.len(), 1, "neutral ambient under colored light still tints once");
|
|
let mut freeform = if let Paint::Gradient(g) = paint { g } else { panic!("gradient") };
|
|
freeform.gradient.kind = GradientKind::Freeform;
|
|
freeform.gradient.stops = vec![GradientStop::new(0.0, Color::BLACK)];
|
|
freeform.swatch = Some("Original ramp".into());
|
|
freeform.freeform = Some(vectorcraft_doc::color::Freeform {
|
|
points: vec![vectorcraft_doc::color::FreeformPoint::new(Point::new(12.0, 18.0), Color::WHITE)],
|
|
..Default::default()
|
|
});
|
|
let original = Paint::Gradient(freeform);
|
|
let items = fills(&original, [1.0, 0.25, 0.25], 1.0, true);
|
|
let Paint::Gradient(shaded) = items[0].paint() else { panic!("freeform gradient") };
|
|
let point = shaded.freeform.as_ref().unwrap().points[0];
|
|
assert_eq!(point.at, Point::new(12.0, 18.0));
|
|
assert_eq!(point.color.to_rgb(), [1.0, 0.25, 0.25]);
|
|
assert_eq!(shaded.swatch, None, "a changed freeform point detaches the gradient swatch");
|
|
}
|
|
|
|
/// Under colored light, a face's unplaced source gradient is fitted to the face's bounds grown by
|
|
/// 1 pt, whatever the size of the cover rectangle that draws it; a placed one keeps its placement.
|
|
#[test]
|
|
fn composed_faces_fit_unplaced_gradients_to_the_face_not_the_cover() {
|
|
use vectorcraft_doc::NodeKind;
|
|
use vectorcraft_geom::{Rect, shapes};
|
|
use vectorcraft_three_d::{RgbGradient, ShadeGradient};
|
|
let face = shapes::rectangle(Rect::new(10.0, 20.0, 50.0, 40.0));
|
|
let ramp = |b| ShadeGradient { start: Point::new(10.0, 20.0), end: Point::new(50.0, 20.0), brightness: [b, 1.0] };
|
|
let light = RgbGradient { channels: [ramp(0.2), ramp(0.5), ramp(0.8)] };
|
|
let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)];
|
|
let unplaced = GradientPaint { gradient: Gradient::new(GradientKind::Linear, stops), geom: None, angle: 0.0, swatch: None, freeform: None };
|
|
let placed = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(80.0, 0.0), aspect: 1.0, focal: None };
|
|
let fitted = unplaced.resolve(Rect::new(9.0, 19.0, 51.0, 41.0));
|
|
for (geom, expected) in [(None, fitted), (Some(placed), placed)] {
|
|
let paint = Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }));
|
|
for seam in [0.05, 0.75] {
|
|
let art = facet_art(vectorcraft_doc::NodeId(1), &face, &paint, light, seam);
|
|
let NodeKind::Group { children, clip: true } = &art.kind else { panic!("a clipped composite") };
|
|
let base = &children[1].children().unwrap()[0];
|
|
let Paint::Gradient(g) = base.appearance.items[0].paint() else { panic!("the source gradient") };
|
|
assert_eq!(g.geom, Some(expected), "seam {seam}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A material's highlight over a curved face reaches its seam too, as the face's clip does,
|
|
/// wound one way so a nonzero fill screens it once. A curved face that folds over itself keeps
|
|
/// its outline alone.
|
|
#[test]
|
|
fn a_highlight_over_a_curved_face_covers_its_seam() {
|
|
use kurbo::Shape;
|
|
let circle = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
|
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
|
|
for path in [circle.clone(), vectorcraft_geom::PathData::from_bezpath(&circle.to_bezpath().reverse_subpaths())] {
|
|
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
|
|
let Some(shape) = over.path_data() else { panic!("a path") };
|
|
let bez = shape.to_bezpath();
|
|
assert_ne!(bez.winding(Point::new(5.0, 10.4)), 0, "the seam past the bottom edge");
|
|
assert_ne!(bez.winding(Point::new(5.0, 5.0)), 0, "the face");
|
|
assert_eq!(bez.winding(Point::new(5.0, 11.0)), 0, "past the seam");
|
|
assert!(bez.elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count() >= 2);
|
|
}
|
|
// A curved face that folds over itself keeps its outline alone, as its own nonzero fill.
|
|
let mut folded = vectorcraft_geom::BezPath::new();
|
|
folded.move_to((0.0, 0.0));
|
|
folded.quad_to((5.0, -1.0), (10.0, 10.0));
|
|
folded.line_to((10.0, 0.0));
|
|
folded.quad_to((5.0, 1.0), (0.0, 10.0));
|
|
folded.close_path();
|
|
let folded = vectorcraft_geom::PathData::from_bezpath(&folded);
|
|
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &folded, 1.0, Some(highlight)) else { panic!("a highlight") };
|
|
assert_eq!(over.path_data(), Some(&folded));
|
|
}
|
|
|
|
/// A curved face whose fold is smaller than the flattening tolerance, so that its flattened
|
|
/// outline does not cross itself, still keeps its outline alone, wound either way.
|
|
#[test]
|
|
fn a_highlight_over_a_fold_smaller_than_flatness_keeps_its_outline() {
|
|
let mut folded = vectorcraft_geom::BezPath::new();
|
|
folded.move_to((0.0, 0.0));
|
|
folded.line_to((10.0, 0.0));
|
|
folded.line_to((10.0, 10.0));
|
|
folded.line_to((0.0, 10.0));
|
|
folded.line_to((0.0, 0.01));
|
|
folded.quad_to((5.0, -0.03), (9.0, 0.01));
|
|
folded.close_path();
|
|
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
|
|
for bez in [folded.clone(), folded.reverse_subpaths()] {
|
|
let mut flat = vectorcraft_geom::BezPath::new();
|
|
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
|
|
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the fold");
|
|
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
|
|
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
|
|
assert_eq!(over.path_data(), Some(&path));
|
|
}
|
|
}
|
|
|
|
/// A face with a collinear cubic that reverses direction keeps its highlight outline.
|
|
#[test]
|
|
fn a_highlight_over_a_retraced_cubic_keeps_its_outline() {
|
|
let mut folded = vectorcraft_geom::BezPath::new();
|
|
folded.move_to((0.0, 0.0));
|
|
folded.curve_to((-8.0, 0.0), (-4.0, 0.0), (12.0, 0.0));
|
|
folded.line_to((12.0, 10.0));
|
|
folded.line_to((0.0, 10.0));
|
|
folded.close_path();
|
|
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
|
|
for bez in [folded.clone(), folded.reverse_subpaths()] {
|
|
let mut flat = vectorcraft_geom::BezPath::new();
|
|
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
|
|
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the reversal");
|
|
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
|
|
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
|
|
assert_eq!(over.path_data(), Some(&path));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_curved_edge_crossing_its_neighbor_keeps_the_highlight_outline() {
|
|
let mut folded = vectorcraft_geom::BezPath::new();
|
|
folded.move_to((0.0, 0.0));
|
|
folded.line_to((1000.0, 1000.0));
|
|
folded.quad_to((500.0, 499.999), (0.0, 0.2));
|
|
folded.line_to((-1000.0, 1000.0));
|
|
folded.line_to((-1000.0, -1000.0));
|
|
folded.close_path();
|
|
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
|
|
for bez in [folded.clone(), folded.reverse_subpaths()] {
|
|
let mut flat = vectorcraft_geom::BezPath::new();
|
|
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
|
|
assert!(seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0, 2.0 * HIGHLIGHT_FLATNESS).is_some());
|
|
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
|
|
let over = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)).unwrap();
|
|
assert_eq!(over.path_data(), Some(&path));
|
|
}
|
|
}
|
|
|
|
/// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the
|
|
/// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound
|
|
/// either way and in a concave notch. A facet whose footprint would gain or lose area under a
|
|
/// nonzero fill (no area, crossing edges, a hole, curves) or a seam with no width has none.
|
|
#[test]
|
|
fn seamed_fill_covers_a_polygon_and_its_seam_once() {
|
|
use kurbo::Shape;
|
|
use vectorcraft_geom::BezPath;
|
|
let polygon = |points: &[(f64, f64)]| {
|
|
let mut bp = BezPath::new();
|
|
bp.move_to(points[0]);
|
|
for p in &points[1..] {
|
|
bp.line_to(*p);
|
|
}
|
|
bp.close_path();
|
|
bp
|
|
};
|
|
let covers = |fill: &vectorcraft_geom::PathData, x: f64, y: f64| fill.to_bezpath().winding(Point::new(x, y)) != 0;
|
|
let notched = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (6.0, 10.0), (6.0, 4.0), (4.0, 4.0), (4.0, 10.0), (0.0, 10.0)];
|
|
let mut reversed = notched;
|
|
reversed.reverse();
|
|
for points in [¬ched[..], &reversed[..], &[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)][..]] {
|
|
let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(points)), 0.75).expect("a simple polygon");
|
|
let contours = fill.to_bezpath().elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count();
|
|
assert!(contours >= 2, "{points:?}: the seam's outline and the facet, {contours} contours");
|
|
for (x, y) in [(1.0, 1.0), (2.0, 0.5), (5.0, -0.3), (-0.3, 5.0), (-0.2, -0.2)] {
|
|
assert!(covers(&fill, x, y), "{points:?} covers ({x},{y})");
|
|
}
|
|
for (x, y) in [(5.0, -0.5), (-0.5, 5.0), (-0.3, -0.3), (12.0, 12.0)] {
|
|
assert!(!covers(&fill, x, y), "{points:?} leaves ({x},{y})");
|
|
}
|
|
}
|
|
let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(¬ched)), 0.75).unwrap();
|
|
assert!(covers(&fill, 4.3, 8.0) && covers(&fill, 5.0, 4.3), "the notch's edges carry the seam");
|
|
assert!(!covers(&fill, 5.0, 8.0), "the notch stays open");
|
|
let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
|
|
let mut holed = square.clone();
|
|
holed.extend(polygon(&[(3.0, 3.0), (3.0, 7.0), (7.0, 7.0), (7.0, 3.0)]).iter());
|
|
let mut curved = BezPath::new();
|
|
curved.move_to((0.0, 0.0));
|
|
curved.quad_to((5.0, -5.0), (10.0, 0.0));
|
|
curved.line_to((5.0, 10.0));
|
|
curved.close_path();
|
|
let mut open = BezPath::new();
|
|
open.move_to((0.0, 0.0));
|
|
open.line_to((10.0, 0.0));
|
|
open.line_to((10.0, 10.0));
|
|
for (name, path, seam) in [
|
|
("sliver", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 0.0)]), 0.75),
|
|
("bow tie", polygon(&[(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 10.0)]), 0.75),
|
|
("a vertex visited twice", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 5.0), (10.0, 10.0), (0.0, 10.0), (5.0, 5.0)]), 0.75),
|
|
("hole", holed, 0.75),
|
|
("curve", curved, 0.75),
|
|
("open", open, 0.75),
|
|
("no seam", square.clone(), 0.0),
|
|
("endless seam", square, f64::INFINITY),
|
|
] {
|
|
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&path), seam).is_none(), "{name}");
|
|
}
|
|
}
|
|
}
|