From 52e959d4bedd6eaec1a04b5498c27b341c223126 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:25:43 -0800 Subject: [PATCH] 3D (Classic): Map Art keeps to the limits the art draws within - When any solid's mapped art passes the shared limits, every solid in the effect draws without its mapped art, so Invisible Geometry hides all of them or none. - A revolved group lists its surfaces with the members' shared curve sampling, and an extruded group lists none past the faces of one object. - Commands refuse art on walls, bevels and Revolve's side whose curves, cut into straight pieces at the map's scale and placed about the surface's center, pass 400,000 points. Caps are not counted. - Each contour's bounds test counts as a cut, in Map Art and in the side graphics. - On a facet whose curved edge bows out of its cell, the art reaches the whole facet. - A bevel as deep as the solid leaves no walls, and its bevels take the numbers after the caps. - Surfaces past the face limit are refused as the side is. - threeD.mapArt keeps a deleted symbol only while the request leaves `symbol` out. --- crates/effects/src/revolve.rs | 13 +- crates/effects/src/solids.rs | 69 ++++-- crates/effects/src/solids/classic.rs | 27 +-- crates/effects/src/solids/graphics.rs | 35 ++- crates/effects/src/solids/map_art.rs | 138 ++++++++++- crates/effects/src/solids/tests_map_art.rs | 218 +++++++++++++++++- crates/engine/src/cmd/effectcmd/graphics.rs | 4 +- .../engine/src/cmd/effectcmd/map_art_tests.rs | 17 ++ crates/three-d/src/solid/build.rs | 24 +- crates/three-d/src/solid/tests_side.rs | 29 ++- docs/mcp.md | 8 +- docs/three-d.md | 7 +- 12 files changed, 536 insertions(+), 53 deletions(-) diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 75f60c894e..bf347d8ed6 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -239,10 +239,15 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of /// appearance item `target` of `n` ([`validate_item_of`]). /// An error when the symbols that Revolve (Classic)'s Map Art in `p` places, with the symbols of -/// `doc`, are past the limits of a graphic's art, as on Extrude & Bevel (Classic). +/// `doc`, are past the limits of a graphic's art, as on Extrude & Bevel (Classic), or past the +/// limits of art unrolled onto its side, its only surface. fn validate_map_symbols(doc: Option<&Document>, id: &str, p: &Value) -> Result<(), String> { match doc.filter(|_| id == CLASSIC_REVOLVE) { - Some(doc) => crate::solids::graphics::validate_symbols(doc, p), + Some(doc) => { + crate::solids::graphics::validate_symbols(doc, p)?; + // The side is surface 1, laid out about the origin; a map past it draws nothing. + crate::solids::graphics::validate_unrolled_symbols(doc, p, &|surface| (surface == 1).then_some(Point::ZERO)) + } None => Ok(()), } } @@ -345,7 +350,7 @@ fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&Appea /// `options` with one number of samples for every curve of `shapes`, the members of one group: the /// members share Revolve's limits. -fn shared_options(shapes: &[Profile], options: Revolve) -> Result { +pub(crate) fn shared_options(shapes: &[Profile], options: Revolve) -> Result { let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?; Ok(Revolve { curve_samples: Some(samples), ..options }) } @@ -529,7 +534,7 @@ fn surface( budget: &mut budget, copies: &mut copies.graphics, }); - let (art, hidden) = crate::solids::classic::surface(n, facets, &paint, (opacity, blend), &p, mapped, hide); + let (art, hidden, _) = crate::solids::classic::surface(n, &facets, &paint, (opacity, blend), &p, mapped, hide); return Some((drawn, art, kept, false, hidden)); } let colored = colored(&options); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 8c66f95573..7d909b7dda 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -437,11 +437,22 @@ fn visible(item: &AppearanceItem, member: f32) -> bool { /// ([`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. +/// included. On Extrude & Bevel (Classic), the art Map Art places on walls and bevels must also fit +/// ([`graphics::validate_unrolled_symbols`]). 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); + // Map Art unrolls its art onto walls and bevels; the caps draw it as it is. + if id == CLASSIC_EXTRUDE && !surface_maps(p).is_empty() { + let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(p) }; + let unrolled: Vec> = parts + .iter() + .flat_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default()) + .map(|s| (!matches!(s.kind, SurfaceKind::End(_))).then(|| graphics::map_art::flat_center(&s))) + .collect(); + graphics::validate_unrolled_symbols(doc, p, &|surface| surface.checked_sub(1).and_then(|k| unrolled.get(k).copied().flatten()))?; + } if side_carrier(id, p, &parts, bounds).is_none() { return Ok(()); } @@ -1931,7 +1942,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil } } let art = if classic { - classic::surface(n, f, &paint, (opacity, blend), &p, None, false).0 + classic::surface(n, &f, &paint, (opacity, blend), &p, None, false).0 } else { surface(n, f, &paint, opacity, blend, colored, false) }; @@ -2057,7 +2068,34 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let split = split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::() <= MAX_FACE_COMPOSITES; let members: Vec = solids.iter().map(|s| s.4).collect(); - let mut map_budget = MapBudget::default(); + // The classic surfaces of the solids, with mapped art when the effect has maps. When the art of + // any solid is past the limits the object's maps share, every solid draws without mapped art. + let mut classic_arts = if classic { + let draw = |with_art: bool, copies: &mut usize| { + let mut budget = MapBudget::default(); + let mut dropped = false; + let mut arts = Vec::with_capacity(solids.len()); + for (k, (item, member, _, f, _)) in solids.iter().enumerate() { + let (paint, opacity, blend) = paint_of(item, *member); + let mapped = map_art.as_ref().filter(|_| with_art).zip(layouts.get(k)).map(|(art, layout)| classic::Mapped { + art, + layout, + budget: &mut budget, + copies: &mut *copies, + }); + let (art, _, left_out) = classic::surface(n, f, &paint, (opacity, blend), &p, mapped, false); + dropped |= left_out; + arts.push(art); + } + (arts, dropped) + }; + let mut used = paint_bytes; + let (arts, dropped) = draw(map_art.is_some(), &mut used); + if dropped { draw(false, &mut paint_bytes).0 } else { arts } + } else { + vec![] + } + .into_iter(); // Which surfaces lie over an underlay of their facets, in one order or whole // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); @@ -2067,8 +2105,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() - .enumerate() - .map(|(k, (item, member, scopes, f, shape))| { + .map(|(item, member, scopes, f, shape)| { let paints = Paints::of(item, closed(shape)); let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); @@ -2085,13 +2122,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil }; let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { - let mapped = map_art.as_ref().zip(layouts.get(k)).map(|(art, layout)| classic::Mapped { - art, - layout, - budget: &mut map_budget, - copies: &mut paint_bytes, - }); - classic::surface(n, f, &paint, (opacity, blend), &p, mapped, false).0 + classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![])) } else { 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) @@ -2551,8 +2582,12 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, in let mut out = vec![]; if fx.id == crate::CLASSIC_REVOLVE { // Revolve (Classic) has one surface: its side, in a group that of the member with the - // longest profile. - let options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(&fx.id, &p) }; + // longest profile. A group's members share one sampling of their curves, and a group past + // those shared limits has no surface. + let mut options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(&fx.id, &p) }; + if is_container(n) { + options = crate::revolve::shared_options(&shapes, options).ok()?; + } let shape = shapes.get(crate::revolve::graphics_member(&shapes, b, options)?)?; let (width, height) = vectorcraft_three_d::revolve_surface_size(&shape.path, b, options)?; let surfaces = [vectorcraft_three_d::SolidSurface { kind: SurfaceKind::Side, width, height, center: None }]; @@ -2563,9 +2598,15 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, in let (parts, bounds) = solid_parts(&shapes, b); let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(&p) }; let view = view_options(&p); + // The faces of the solids count together against the limit the art draws within. + let mut kept = 0usize; for (_, _, area, rule, _, _) in &parts { let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default(); + kept = kept.saturating_add(facets.len()); + if kept > MAX_OBJECT_FACES { + return None; + } listed(&surfaces, &facets, &mut out); } Some(out) diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 54401fd189..609743fe03 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -282,51 +282,52 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// draws no mapped art. Without `mapped`, `hide` leaves the faces out the same way, for a solid /// that shares Invisible Geometry with another solid's mapped art; Wireframe still draws. /// -/// Returns the group and whether its faces were left out. +/// Returns the group, whether its faces were left out, and whether `mapped` art was left out past +/// the limits. pub(crate) fn surface( n: &Node, - facets: Vec, + facets: &[Facet], source: &Paint, (opacity, blend): (f32, BlendMode), p: &Value, mapped: Option>, hide: bool, -) -> (Node, bool) { +) -> (Node, bool, bool) { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); let overprint = black_overprint(p); let wire = shading.surface == ClassicSurface::Wireframe; - let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; + let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(facets)) }; let paint = &paint; // The mapped art of each facet, and whether the faces themselves are left out. Art past the // limits is left out, and the faces draw; the copies and the points of art left out do not // count against the art of later solids. - let (mut parts, invisible) = match mapped.filter(|_| !wire) { + let (mut parts, invisible, dropped) = match mapped.filter(|_| !wire) { Some(m) => { let shaded_as = |f: &Facet, c: Color| { let (tone, spec) = shading.tone(f.normal, &lights); shaded(c, tone, spec, shade) }; let (mut used, mut budget) = (*m.copies, m.budget.clone()); - match m.art.parts(n.id, &facets, m.layout, &shaded_as, &mut budget, &mut used) { + match m.art.parts(n.id, facets, m.layout, &shaded_as, &mut budget, &mut used) { Some(parts) => { (*m.copies, *m.budget) = (used, budget); - (parts, m.art.invisible) + (parts, m.art.invisible, false) } - None => (vec![], false), + None => (vec![], false, true), } } - None => (vec![], hide && !wire), + None => (vec![], hide && !wire, false), }; let children = facets - .into_iter() + .iter() .enumerate() .map(|(k, face)| { let art = parts.get_mut(k).map(std::mem::take).unwrap_or_default(); if !art.is_empty() || invisible { - let drawn = (!invisible).then(|| Arc::new(shaded_face(n, &face, paint, &shading, &lights, shade, preserve, overprint))); + let drawn = (!invisible).then(|| Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint))); return Arc::new(Node::group(n.id, drawn.into_iter().chain(art).collect())); } if wire { @@ -334,7 +335,7 @@ pub(crate) fn surface( let edge = crate::lighting::seam_stroke(paint.clone(), WIRE); return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() })); } - Arc::new(shaded_face(n, &face, paint, &shading, &lights, shade, preserve, overprint)) + Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint)) }) .collect(); let mut group = Node::group(n.id, children); @@ -345,7 +346,7 @@ pub(crate) fn surface( let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0)); group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true))); } - (group, invisible) + (group, invisible, dropped) } /// One face of a solid in paint `paint` (opaque: [`surface`] masks a gradient's transparency), diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 2859f2edf1..66358df431 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -211,11 +211,11 @@ pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option< /// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol /// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as -/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. +/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. The symbols Map +/// Art places count with the graphics. pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 }; let mut elements = 0usize; - // The symbols Map Art places count with the graphics. let names = mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)); for name in names { let Some(symbol) = doc.symbols.iter().find(|s| s.name == name) else { continue }; @@ -228,6 +228,30 @@ pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { Ok(()) } +/// Does the art Map Art in `p` places on the surfaces that `unrolled` gives a flat center for (by +/// number, from 1; [`map_art::flat_center`]), with the symbols of `doc`, fit the limits as a wall, a +/// bevel or Revolve's side draws it: each map's art placed about that center at its scale, cut into +/// straight pieces, at most [`MAX_ELEMENTS`] points together and within reach? A map whose symbol +/// `doc` does not have is not counted. +pub fn validate_unrolled_symbols(doc: &Document, p: &Value, unrolled: &dyn Fn(usize) -> Option) -> Result<(), String> { + const TOO_COMPLEX: &str = "The graphics are too complex: simplify the symbols' art"; + let mut points = 0usize; + for m in map_art::surface_maps(p) { + let Some(center) = unrolled(m.surface) else { continue }; + let Some(symbol) = doc.symbols.iter().find(|s| s.name == m.symbol) else { continue }; + let pieces = pieces_of(doc, symbol)?; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; + let place = m.placement(bounds, center, false); + for piece in &pieces { + straight_pieces(&(place * piece.path.to_bezpath()), &mut points).ok_or(TOO_COMPLEX)?; + } + if points > MAX_ELEMENTS { + return Err(TOO_COMPLEX.into()); + } + } + Ok(()) +} + /// The path elements `path` draws when each curve draws `curve` elements, before curves near the /// eye are split further: one for each straight line, move and close. fn drawn_elements(path: &PathData, curve: usize) -> usize { @@ -848,7 +872,12 @@ pub(crate) fn surface_parts( for k in near { let Some(piece) = pieces.get(k) else { continue }; let mut path = BezPath::new(); - // Each contour is cut only where its own bounds reach the triangle. + // Each contour is cut only where its own bounds reach the triangle. Each bounds test + // counts as one point cut, whether or not the contour reaches it. + cut_points = cut_points.saturating_add(piece.boxes.len()); + if cut_points > MAX_SURFACE_CUTS { + return None; + } for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) { if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 { continue; diff --git a/crates/effects/src/solids/map_art.rs b/crates/effects/src/solids/map_art.rs index 51b86118bc..3e395a6d03 100644 --- a/crates/effects/src/solids/map_art.rs +++ b/crates/effects/src/solids/map_art.rs @@ -23,8 +23,8 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect}; use vectorcraft_three_d::{Extrude, FaceMap, Facet, MapCell, PlanarFace, SolidSurface, SurfaceKind, View}; use super::{ - MAX_ELEMENTS, MAX_SURFACE_CUTS, MAX_SURFACE_POINTS, NotMapped, SURFACE_SEAM, Unrolled, counterclockwise, map_path, pieces_of, straight_pieces, - takes_seam, triangle_map, + MAX_ELEMENTS, MAX_SURFACE_CUTS, MAX_SURFACE_POINTS, NotMapped, SURFACE_SEAM, SURFACE_TOLERANCE, Unrolled, counterclockwise, map_path, pieces_of, + straight_pieces, takes_seam, triangle_map, }; /// The effect parameter that holds the maps. @@ -438,6 +438,22 @@ impl Mapper { } } + /// The point of the flat surface this map takes to `p` on the page. `None` where there is none. + fn back(&self, p: Point) -> Option { + let q = match self { + Mapper::Affine(a) => a.inverse() * p, + Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => { + // x (g u + h v + 1) = a u + b v + c, and the same for y, solved for u and v. + let (m00, m01, r0) = (a - g * p.x, b - h * p.x, p.x - c); + let (m10, m11, r1) = (d - g * p.y, e - h * p.y, p.y - f); + let det = m00 * m11 - m01 * m10; + let (u, v) = ((r0 * m11 - m01 * r1) / det, (m00 * r1 - r0 * m10) / det); + Point::new(origin.x + u * size.0, origin.y + v * size.1) + } + }; + q.is_finite().then_some(q) + } + /// The affine map nearest this one around `p`, for gradients and patterns. fn local(&self, p: Point, step: f64) -> Affine { match self { @@ -523,6 +539,108 @@ fn clip_convex(polygon: &[Point], window: &[Point]) -> Vec { out } +/// How far `p` lies outside the convex `polygon`, wound with its inside on the positive side of each +/// edge, across the edges for which `counts` holds: 0 or less when it lies inside them. +fn beyond(polygon: &[Point], p: Point, counts: &dyn Fn(Point, Point) -> bool) -> f64 { + let mut most = f64::NEG_INFINITY; + for (k, &a) in polygon.iter().enumerate() { + let Some(&b) = polygon.get((k + 1) % polygon.len()) else { continue }; + let length = (b - a).hypot(); + if length > 0.0 && counts(a, b) { + most = most.max(-(b - a).cross(p - a) / length); + } + } + most +} + +/// `regions` of `cell` ([`regions`]) with the edges they share with the cell's own outline moved out +/// on the flat surface, far enough that their maps reach the outline of facet `f` where its curved +/// edges bow out of the cell: each outline point is taken back onto the flat surface through the +/// region's own map. The edge between two triangles stays, so the regions do not overlap. A region +/// moves out at most four times the size of the cell, and one whose projective map would turn +/// inside out where it reaches stays as it is. Without a curved outline, or where the outline stays +/// inside the cell, the regions are returned unchanged. +fn reaching_outline(regions: Vec<(Vec, Mapper)>, cell: &MapCell, f: &Facet) -> Vec<(Vec, Mapper)> { + let Some(outline) = f.outline.as_ref() else { return regions }; + let Some(uv) = box_of(&cell.uv) else { return regions }; + // The cell on the page, wound with its inside on the positive side of each edge. + let mut around = cell.page.clone(); + let turn: f64 = around.iter().zip(around.iter().cycle().skip(1)).map(|(a, b)| a.to_vec2().cross(b.to_vec2())).sum(); + if turn < 0.0 { + around.reverse(); + } + // The points of the outline that lie outside the cell on the page, or near enough that the + // curve between them may: the curve strays from its flattened points by up to the tolerance, + // so each point counts as the corners of a square of that half width around it. + let mut out = vec![]; + let outline = outline.to_bezpath(); + let t = SURFACE_TOLERANCE; + vectorcraft_geom::kurbo::flatten(outline.elements().iter().copied(), t, |el| { + if let vectorcraft_geom::kurbo::PathEl::MoveTo(p) | vectorcraft_geom::kurbo::PathEl::LineTo(p) = el + && beyond(&around, p, &|_, _| true) > -2.0 * t + { + out.extend([(t, t), (t, -t), (-t, t), (-t, -t)].map(|(x, y)| p + vectorcraft_geom::Vec2::new(x, y))); + } + }); + if out.is_empty() { + return regions; + } + let most = 4.0 * uv.width().hypot(uv.height()); + let on_outline = |a: Point, b: Point| { + let at = |q: Point| cell.uv.iter().position(|u| *u == q); + let count = cell.uv.len(); + matches!((at(a), at(b)), (Some(i), Some(j)) if (i + 1) % count == j || (j + 1) % count == i) + }; + regions + .into_iter() + .map(|(window, mapper)| { + let reach = out.iter().filter_map(|p| mapper.back(*p)).map(|q| beyond(&window, q, &on_outline)).fold(0.0f64, f64::max); + if reach <= 0.0 { + return (window, mapper); + } + // A little past the farthest point, so the cut to the outline meets it. + let reach = (reach * 1.01 + 1e-9).min(most); + let grown = grown_window(&window, reach, &on_outline); + let holds = match &mapper { + Mapper::Affine(_) => true, + Mapper::Quad { origin, size, rows } => grown.iter().all(|p| { + let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1); + rows[6] * u + rows[7] * v + 1.0 > 1e-6 + }), + }; + (if holds && grown.len() == window.len() { grown } else { window }, mapper) + }) + .collect() +} + +/// The convex `window`, wound as [`clip_convex`] reads it, with each edge for which `moves` holds +/// moved out by `by`, and its corners where the moved edges meet. +fn grown_window(window: &[Point], by: f64, moves: &dyn Fn(Point, Point) -> bool) -> Vec { + let count = window.len(); + // Each edge as a point on its line and its direction, moved out where it moves. + let lines: Vec<(Point, vectorcraft_geom::Vec2)> = (0..count) + .filter_map(|k| { + let (a, b) = (*window.get(k)?, *window.get((k + 1) % count)?); + let d = b - a; + let length = d.hypot(); + let out = if moves(a, b) && length > 0.0 { vectorcraft_geom::Vec2::new(d.y, -d.x) * (by / length) } else { vectorcraft_geom::Vec2::ZERO }; + Some((a + out, d)) + }) + .collect(); + (0..count) + .filter_map(|k| { + let ((p1, d1), (p2, d2)) = (*lines.get((k + count - 1) % count)?, *lines.get(k)?); + let den = d1.cross(d2); + if den.abs() <= 1e-12 * d1.hypot() * d2.hypot() { + return Some(p2); + } + let t = (p2 - p1).cross(d2) / den; + let p = p1 + d1 * t; + p.is_finite().then_some(p) + }) + .collect() +} + /// The parts of `pieces`, a map's art on its flat surface, that fall on `cell`, the cell of facet /// `f`, drawn on the page. `None` past the limits. fn cell_art( @@ -538,16 +656,24 @@ fn cell_art( return Some(vec![]); } let Some(reach) = box_of(&cell.uv) else { return Some(vec![]) }; - let apart = |b: &Rect| b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1; - let regions = regions(cell); // A facet cut after it was built, or one whose edges follow the profile's curves, draws only the - // part of the art inside its own outline. + // part of the art inside its own outline, which the regions reach where it bows out of the cell. let whole = f.outline.is_none() && f.contours.first() == Some(&cell.page); + let regions = if whole { regions(cell) } else { reaching_outline(regions(cell), cell, f) }; + let within = regions.iter().filter_map(|(w, _)| box_of(w)).fold(reach, |a, b| a.union(b)); + let apart = |b: &Rect| b.x1 < within.x0 || b.x0 > within.x1 || b.y1 < within.y0 || b.y0 > within.y1; let mut out = vec![]; for piece in pieces.iter().filter(|p| !apart(&p.bounds)) { + // Each contour's bounds test counts as one point cut, whether or not the contour reaches + // the cell. + budget.cuts = budget.cuts.saturating_add(piece.boxes.len()); + if budget.cuts > MAX_SURFACE_CUTS { + return None; + } + let near: Vec<&Vec> = piece.polygons.iter().zip(&piece.boxes).filter(|(_, b)| !apart(b)).map(|(p, _)| p).collect(); let mut path = BezPath::new(); for (window, mapper) in ®ions { - for (polygon, _) in piece.polygons.iter().zip(&piece.boxes).filter(|(_, b)| !apart(b)) { + for polygon in &near { budget.cuts = budget.cuts.saturating_add(polygon.len()); if budget.cuts > MAX_SURFACE_CUTS { return None; diff --git a/crates/effects/src/solids/tests_map_art.rs b/crates/effects/src/solids/tests_map_art.rs index dfa35a019d..af7fe06965 100644 --- a/crates/effects/src/solids/tests_map_art.rs +++ b/crates/effects/src/solids/tests_map_art.rs @@ -107,6 +107,18 @@ fn the_surfaces_are_the_caps_then_each_wall_then_each_bevel() { assert_eq!(seen, [true, false, false, false, false, false]); } +#[test] +fn a_bevel_as_deep_as_the_solid_leaves_no_walls_and_its_bevels_take_their_maps() { + let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back)); + let solid = |maps: Value| object(CLASSIC_EXTRUDE, json!({"depth": 10, "bevel": "classic", "bevelHeight": 10, "mapArt": maps})); + let kinds: Vec = surfaces(&solid(json!([]))).iter().map(|s| s.kind).collect(); + assert_eq!(kinds, [vec![front, back], vec![SurfaceKind::Bevel; 4]].concat()); + // Seen straight on, the front bevels draw the art mapped onto them. + let bevels: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + let art = solid_art_in(Some(&document()), &solid(json!(bevels))).unwrap(); + assert!(!filled(&art, RED).is_empty()); +} + #[test] fn a_map_on_the_front_cap_draws_the_symbol_at_its_offset_scales_and_turn() { let d = document(); @@ -216,16 +228,139 @@ fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() { assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge"); } +#[test] +fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + // The facet's top edge follows a curve that bows out of the quad, up to y = -2. + let mut curved = BezPath::new(); + curved.move_to((0.0, 0.0)); + curved.curve_to((10.0 / 3.0, -8.0 / 3.0), (20.0 / 3.0, -8.0 / 3.0), (10.0, 0.0)); + curved.line_to((10.0, 10.0)); + curved.line_to((0.0, 10.0)); + curved.close_path(); + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: Some(PathData::from_bezpath(&curved)), + side: true, + away: false, + end: None, + plane: None, + surface: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad }; + // Art that covers the facet and more. + let cover = vec![Point::new(-5.0, -5.0), Point::new(15.0, -5.0), Point::new(15.0, 15.0), Point::new(-5.0, 15.0)]; + let whole = Rect::new(-5.0, -5.0, 15.0, 15.0); + let art = Unrolled { + polygons: vec![cover], + boxes: vec![whole], + bounds: whole, + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let (mut budget, mut copies) = (MapBudget::default(), 0); + let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap(); + let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum(); + let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs(); + assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge"); +} + +#[test] +fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + plane: None, + surface: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad }; + // Small contours on either side of the cell: the piece's bounds reach across it, but no + // contour's own bounds do. + let polygons: Vec> = (0..2000) + .map(|k| { + let x = if k % 2 == 0 { -1000.0 } else { 1000.0 }; + vec![Point::new(x, 0.0), Point::new(x + 1.0, 0.0), Point::new(x + 1.0, 1.0)] + }) + .collect(); + let boxes: Vec = polygons.iter().filter_map(|p| box_of(p)).collect(); + let art = Unrolled { + polygons, + boxes, + bounds: Rect::new(-1000.0, 0.0, 1001.0, 1.0), + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let mut budget = MapBudget { cuts: MAX_SURFACE_CUTS - 10, ..MapBudget::default() }; + assert!(cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut 0).is_none()); +} + #[test] fn a_map_on_the_back_cap_reads_the_right_way_round_from_behind() { let d = document(); - let n = object(CLASSIC_EXTRUDE, json!({"rotationY": 180, "mapArt": [{"surface": 1, "symbol": "Corner"}, {"surface": 2, "symbol": "Corner"}]})); + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": 180, "mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 2, "symbol": "Corner"}]})); let art = solid_art_in(Some(&d), &n).unwrap(); - // Only the back cap is seen. + // Only the back cap is seen, and it carries its own map's art. assert_eq!(filled(&art, RED).len(), 1); + assert_eq!((filled(&art, BLUE).len(), filled(&art, GREEN).len()), (1, 1)); assert!(handedness(&art) > 0.0); } +#[test] +fn art_past_the_shared_limits_leaves_out_the_mapped_art_of_every_solid() { + let mut d = document(); + // A zigzag of half the straight sides one 3D effect's mapped art may draw. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + for i in 1..=MAX_ELEMENTS / 2 { + b.line_to((i as f64 * 0.00005, (i % 2) as f64)); + } + b.close_path(); + let half = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Half".into(), art: Arc::new(half) }); + let gray = Color::rgb(0.5, 0.5, 0.5); + // A group of two squares: the first solid's front is surface 1, the second's surface 7. + let art = |maps: Value, invisible: bool| { + let members = + vec![Arc::new(square(8, Rect::new(0.0, 0.0, 100.0, 100.0), gray)), Arc::new(square(9, Rect::new(200.0, 0.0, 300.0, 100.0), gray))]; + let mut g = Node::group(NodeId(7), members); + let p = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "mapInvisible": invisible, "mapArt": maps}); + g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &p).unwrap()); + solid_art_in(Some(&d), &g).unwrap() + }; + // One solid's art fits. + assert!(!filled(&art(json!([{"surface": 1, "symbol": "Half"}]), false), RED).is_empty()); + // Both together are past the limit: no solid draws its art, and with Invisible Geometry every + // solid's faces draw. + let both = json!([{"surface": 1, "symbol": "Half"}, {"surface": 7, "symbol": "Half"}]); + assert!(filled(&art(both.clone(), false), RED).is_empty()); + let hidden = art(both, true); + assert!(filled(&hidden, RED).is_empty()); + let faces = bounds_of(&filled(&hidden, gray)); + assert!(faces.x0 < 1.0 && faces.x1 > 299.0, "{faces:?}"); +} + #[test] fn a_wall_under_a_perspective_maps_its_art_whole() { let d = document(); @@ -333,7 +468,7 @@ fn art_past_the_paint_copies_allowance_leaves_the_allowance_to_later_art() { let draw = |copies: &mut usize, budget: &mut MapBudget| { let mapped = crate::solids::classic::Mapped { art: &art, layout: &layout, budget, copies }; let blend = vectorcraft_doc::color::BlendMode::Normal; - crate::solids::classic::surface(&n, facets.clone(), &gray, (1.0, blend), &p, Some(mapped), false).0 + crate::solids::classic::surface(&n, &facets, &gray, (1.0, blend), &p, Some(mapped), false).0 }; let (mut copies, mut budget) = (0, MapBudget::default()); assert!(!filled(&draw(&mut copies, &mut budget), RED).is_empty()); @@ -403,6 +538,53 @@ fn invisible_geometry_leaves_out_every_member_of_a_revolved_group() { assert!(strokes > 0); } +#[test] +fn a_revolved_group_past_its_shared_limits_lists_no_surface() { + let gray = Color::rgb(0.5, 0.5, 0.5); + // Profiles of five anchors each; one alone fits Revolve's limits. + let profile = |id: u64, x: f64| { + let mut b = BezPath::new(); + b.move_to((x, 0.0)); + for i in 1..5 { + b.line_to((x + f64::from(i % 2), f64::from(i) * 10.0)); + } + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0))) + }; + let group = |count: u64| { + let mut g = Node::group(NodeId(7), (0..count).map(|k| profile(k + 8, 100.0 + k as f64 * 0.01)).collect()); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({})).unwrap()); + g + }; + let d = document(); + assert_eq!(map_surfaces_at(Some(&d), &group(2), None, 0).map(|s| s.len()), Some(1)); + // 4,000 of them together are past the anchors the members share. + assert!(map_surfaces_at(Some(&d), &group(4000), None, 0).is_none()); +} + +#[test] +fn an_extruded_group_past_the_faces_of_one_object_lists_no_surface() { + // Polygons of 1,000 corners: each solid alone has about 1,000 faces. + let polygon = |id: u64, x: f64| { + let mut b = BezPath::new(); + for i in 0..1000 { + let a = f64::from(i) * std::f64::consts::TAU / 1000.0; + let p = (x + 40.0 * a.cos(), 40.0 * a.sin()); + if i == 0 { b.move_to(p) } else { b.line_to(p) } + } + b.close_path(); + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0))) + }; + let group = |count: u64| { + let mut g = Node::group(NodeId(7), (0..count).map(|k| polygon(k + 8, k as f64 * 100.0)).collect()); + g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({"drawHiddenFaces": true})).unwrap()); + g + }; + let d = document(); + assert!(map_surfaces_at(Some(&d), &group(2), None, 0).is_some()); + // 200 of them together have more faces than one object draws. + assert!(map_surfaces_at(Some(&d), &group(200), None, 0).is_none()); +} + #[test] fn bad_maps_are_refused() { let d = document(); @@ -464,6 +646,36 @@ fn a_mapped_symbol_past_the_limits_of_a_graphics_art_is_refused() { assert!(e.contains("too complex"), "{e}"); } +#[test] +fn a_mapped_symbol_whose_curves_cut_into_too_many_pieces_is_refused() { + let mut d = document(); + // Large circles: a few curves each, but many straight pieces once they are cut. + let loops = |name: &str, count: usize| { + let mut b = BezPath::new(); + for k in 0..count { + let r = 1e5; + let circle = vectorcraft_geom::kurbo::Circle::new((k as f64 * 2.1 * r, 0.0), r); + b.extend(vectorcraft_geom::kurbo::Shape::path_elements(&circle, 0.1)); + } + let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + Symbol { dynamic: false, name: name.into(), art: Arc::new(art) } + }; + d.symbols.push(loops("Loop", 1)); + d.symbols.push(loops("Loops", 400)); + let check = |id: &str, surface: usize, symbol: &str| { + let p = crate::merged_params(id, &json!({"mapArt": [{"surface": surface, "symbol": symbol}]})); + validate_three_d_in(Some(&d), &object(id, json!({})), id, &p) + }; + // Extrude & Bevel's surface 3 is a wall, and Revolve's surface 1 its side. + for (id, surface) in [(CLASSIC_EXTRUDE, 3), (CLASSIC_REVOLVE, 1)] { + assert_eq!(check(id, surface, "Loop"), Ok(()), "{id}"); + let e = check(id, surface, "Loops").unwrap_err(); + assert!(e.contains("too complex"), "{id}: {e}"); + } + // A cap draws the curves as they are, without cutting them. + assert_eq!(check(CLASSIC_EXTRUDE, 1, "Loops"), Ok(())); +} + #[test] fn maps_are_set_cleared_and_renamed_with_their_symbols() { let p = json!({"depth": 20}); diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index fe97de4765..743101a984 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -282,7 +282,9 @@ fn map_art(s: &mut Session, p: &Value) -> Result { } } let mut map = effects::SurfaceMap::from_value(&given).map_err(|e| bad(C, e))?; - if !d.symbols.iter().any(|sym| sym.name == map.symbol) && current.as_ref().is_none_or(|m| m.symbol != map.symbol) { + // A map whose symbol was deleted keeps it while the request leaves `symbol` out; a + // symbol the request names must exist. + if !d.symbols.iter().any(|sym| sym.name == map.symbol) && (p.get("symbol").is_some() || current.is_none()) { return Err(bad(C, format!("no symbol named `{}`", map.symbol))); } if fit { diff --git a/crates/engine/src/cmd/effectcmd/map_art_tests.rs b/crates/engine/src/cmd/effectcmd/map_art_tests.rs index d20033cda4..a63e46b429 100644 --- a/crates/engine/src/cmd/effectcmd/map_art_tests.rs +++ b/crates/engine/src/cmd/effectcmd/map_art_tests.rs @@ -87,6 +87,23 @@ fn a_map_past_the_surface_count_can_still_be_removed() { assert!(e.contains("the object's surface count"), "{e}"); } +#[test] +fn a_map_of_a_deleted_symbol_keeps_it_only_while_the_request_leaves_symbol_out() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("symbol.delete", &json!({"name": "Mark"})).unwrap(); + let ids = json!([id.0]); + // Naming the deleted symbol is refused, and nothing changes. + let e = s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "symbol": "Mark", "x": 10.0})).unwrap_err().to_string(); + assert!(e.contains("no symbol named `Mark`"), "{e}"); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 0.0, (100.0, 100.0), 0.0)])); + // Leaving it out edits the map and keeps its symbol, and `symbol: null` removes the map. + s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "x": 10.0})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 10.0, (100.0, 100.0), 0.0)])); + s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([])); +} + #[test] fn scale_to_fit_centers_the_art_and_fills_the_surface() { let (mut s, id) = setup("threeD.classicExtrude"); diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d7d68c261e..e5b311ed0c 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -743,7 +743,12 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue }; b.cells = layout.as_ref().and_then(|(sides, spans)| { let (bevel, v0, v1) = spans.get(k).copied().flatten()?; - let base = caps + if bevel { sides.lengths.len() } else { 0 }; + // Without a wall span the walls are not numbered, and the bevels follow the caps. + let walls = has_walls(spans); + if !bevel && !walls { + return None; + } + let base = caps + if bevel && walls { sides.lengths.len() } else { 0 }; let edges = sides.edges.get(r)?.iter().map(|e| e.map(|(section, u0, u1)| (base + section, u0, u1))).collect(); Some(BandCells { edges, across: (v0, v1) }) }); @@ -875,10 +880,17 @@ fn band_spans(steps: &[Step], depth: f64) -> Vec> { .collect() } +/// Whether the bands of `spans` ([`band_spans`]) hold a wall with some width across it: a bevel as +/// deep as the solid leaves none. +fn has_walls(spans: &[Option<(bool, f64, f64)>]) -> bool { + spans.iter().flatten().any(|(bevel, from, to)| !bevel && to > from) +} + /// The numbered surfaces of the solid [`extrude`] builds from `path`, in order: the front and back /// caps of a solid with caps, then each side wall, ring by ring from each ring's first corner, then /// the bevel above each wall in the same order. A plane (no depth) has its front only, and a solid -/// with a twist or a taper has only its caps. The facets of a solid built with +/// with a twist or a taper has only its caps. A solid whose bevel is as deep as the solid has no +/// walls. The facets of a solid built with /// [`Extrude::map_surfaces`] carry these indexes ([`MapCell`]). pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude) -> Result, String> { check_bounds(bounds)?; @@ -894,6 +906,11 @@ pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: let most = curve_pieces(path, size, bands, caps)?; let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); + // A solid past the face limit is refused, as [`extrude_faces`] refuses it. + let edges = traced.iter().map(|r| r.points.len()).fold(0usize, usize::saturating_add); + if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); + } let mut out = vec![]; if o.cap { for (step, face) in [(steps.first(), PlanarFace::Front), (steps.last(), PlanarFace::Back)] { @@ -909,7 +926,8 @@ pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: let sides = sides(&traced, wall_inset(&o)); let spans = band_spans(&steps, o.depth); let across = |bevel: bool| spans.iter().flatten().filter(|s| s.0 == bevel).map(|s| s.2).fold(0.0, f64::max); - let kinds = [(SurfaceKind::Wall, false)].into_iter().chain(spans.iter().flatten().any(|s| s.0).then_some((SurfaceKind::Bevel, true))); + let walls = has_walls(&spans).then_some((SurfaceKind::Wall, false)); + let kinds = walls.into_iter().chain(spans.iter().flatten().any(|s| s.0).then_some((SurfaceKind::Bevel, true))); for (kind, bevel) in kinds { out.extend(sides.lengths.iter().map(|l| SolidSurface { kind, width: *l, height: across(bevel), center: None })); } diff --git a/crates/three-d/src/solid/tests_side.rs b/crates/three-d/src/solid/tests_side.rs index f2d7ec722a..47c519ca05 100644 --- a/crates/three-d/src/solid/tests_side.rs +++ b/crates/three-d/src/solid/tests_side.rs @@ -1,6 +1,6 @@ use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; -use super::super::{Bevel, Extrude, View, extrude, extrude_side_size}; +use super::super::{Bevel, Extrude, View, extrude, extrude_side_size, extrude_surfaces}; use super::{across_steps, along_ring, longest}; fn square(r: Rect, hole: Option) -> PathData { @@ -94,3 +94,30 @@ fn the_side_measures_around_the_outline_and_across_the_bevels() { let rings = [&[Point::ZERO, Point::new(1.0, 0.0), Point::new(0.0, 1.0)][..], &[Point::ZERO, Point::new(5.0, 0.0), Point::new(0.0, 5.0)][..]]; assert_eq!(longest(&rings), Some(1)); } + +#[test] +fn the_surfaces_of_a_solid_past_the_face_limit_are_refused_as_its_side_is() { + // A star of `n` thin spikes: a bevel outside cuts each sharp tip square, adding a corner there. + let star = |n: usize| { + let mut b = BezPath::new(); + for i in 0..2 * n { + let a = i as f64 * std::f64::consts::PI / n as f64; + let r = if i % 2 == 0 { 1000.0 } else { 100.0 }; + if i == 0 { b.move_to((r * a.cos(), r * a.sin())) } else { b.line_to((r * a.cos(), r * a.sin())) } + } + b.close_path(); + PathData::from_bezpath(&b) + }; + let bounds = Rect::new(-1000.0, -1000.0, 1000.0, 1000.0); + let o = Extrude { depth: 40.0, bevel: Some(Bevel { width: 1.0, height: 1.0, ..Bevel::default() }), ..Extrude::default() }; + let fits = |n: usize| extrude_side_size(&star(n), FillRule::NonZero, bounds, o).is_some(); + // The fewest spikes past the limits, as the side's size counts them. + let (mut lo, mut hi) = (3usize, 100_000usize); + assert!(fits(lo) && !fits(hi)); + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if fits(mid) { lo = mid } else { hi = mid } + } + assert!(extrude_surfaces(&star(lo), FillRule::NonZero, bounds, o).is_ok()); + assert!(extrude_surfaces(&star(hi), FillRule::NonZero, bounds, o).is_err(), "{hi} spikes"); +} diff --git a/docs/mcp.md b/docs/mcp.md index 12932cba76..c1a28945d1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5073,14 +5073,16 @@ Rotate (Classic) and the other 3D effects take no map. - `surface` is a whole number from 1 to the object's surface count. Extrude & Bevel (Classic) numbers the surfaces through the object's solids in the order they are built: each solid's front cap and back cap, then each side wall from corner to corner of the outline, then the bevel above each wall. A hollow solid (`cap` false) has no caps, so - its numbering starts at its first side wall. A side wall is laid out at its own length, and a bevel at the length of + its numbering starts at its first side wall, and a solid whose bevel is as deep as the solid has no walls, so its + bevels follow its caps. A side wall is laid out at its own length, and a bevel at the length of the wall below it. Revolve (Classic) has one surface, its swept side; on a group it is the side of the member with the longest profile, and the other members take no map. The numbering is VectorCraft's own. - `symbol` names the symbol mapped onto the surface, and `null` removes the surface's map, also a map kept past the object's surface count; `null` with `x`, `y`, - `scaleX`, `scaleY`, `rotation` or `fit: true` is refused. Omitted, the surface keeps its map's symbol; a surface with - no map then is refused. + `scaleX`, `scaleY`, `rotation` or `fit: true` is refused. Omitted, the surface keeps its map's symbol, even one the + document no longer has; a surface with no map then is refused. A symbol the document does not have is refused when + `symbol` names it. - `x` and `y` (points, -1000000..1000000) place the center of the art from the center of the surface laid out flat, `scaleX` and `scaleY` (1..10000%) scale it from the symbol's own size, and `rotation` (-360..360 degrees) turns it counterclockwise. A new map starts at 0, 0, 100%, 100% and 0°. diff --git a/docs/three-d.md b/docs/three-d.md index ea4eeadb0e..35b097f4ac 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -581,7 +581,8 @@ Rotate (Classic) and the other 3D effects take no map. The command is `threeD.ma Extrude & Bevel (Classic) numbers its surfaces through the object's solids in the order they are built (the top fill's solid, then each stroke's): each solid's front cap and back cap, then each side wall from corner to corner of the -outline, then the bevel above each wall. An extruded square has six surfaces. A hollow solid has no caps to number. +outline, then the bevel above each wall. An extruded square has six surfaces. A hollow solid has no caps to number, +and a solid whose bevel is as deep as the solid has no walls. A side wall is laid out at its own length, which a bevel added around the shape makes longer than the outline. A bevel is laid out at the length of the wall below it, so mapped art on a bevel is stretched or squeezed along its edge nearer the cap. Revolve (Classic) has one surface, its swept side, unrolled around the axis as Revolve's graphics are; on a group it is @@ -597,7 +598,9 @@ is VectorCraft's own. Unused counts a symbol a map uses as used. - A map's art follows the rules and limits of a graphic's art ([Graphics](#graphics)). An object takes up to 64 maps, and its maps share the 400,000 path elements of one 3D effect's graphics; past that limit the object draws without - its mapped art. The limits and the shading of the mapped art are VectorCraft's own. + its mapped art. The art of the maps on walls, bevels and Revolve's side, at each map's scale and with its curves cut + into straight pieces, may also take at most 400,000 points together, and commands refuse art past it. The limits and the shading of the mapped art are + VectorCraft's own. ## Parameters (`effect.apply`, `effect.setParams`)