WIP: geometry cell on the vector, shared click targets, transparent stacks in metadata

This commit is contained in:
Dennis Kobert committed 2026-09-18 23:10:28 +00:00
1 parent d650ea3c8c
commit ee0918e1de
13 files changed
+410 -66

No files matched your search

@@ -553,6 +553,7 @@ impl TableItemLayout for Graphic<'_> {
Self::Gradient(list) => list.identifier(),
Self::Text(list) => list.identifier(),
Self::Group(_) => "Group".to_string(),
Self::Segmented(_) => "Stack".to_string(),
}
}
// Don't put a breadcrumb for Graphic
@@ -571,6 +572,7 @@ impl TableItemLayout for Graphic<'_> {
Self::Gradient(list) => list.layout_with_breadcrumb(data),
Self::Text(list) => list.layout_with_breadcrumb(data),
Self::Group(_) => Vec::new(),
Self::Segmented(_) => Vec::new(),
}
}
}
@@ -1901,8 +1901,8 @@ impl DocumentMessageHandler {
layer_click_targets.is_some_and(|targets| {
targets.iter().all(|target| match target.target_type() {
ClickTargetType::Path(path) => {
let mut path = path.clone();
ClickTargetType::Path(_) | ClickTargetType::Instance { .. } => {
let mut path = target.path_in_layer().map(|path| path.into_owned()).unwrap_or_default();
path.apply_affine(Affine::new(layer_transform.to_cols_array()));
bezpath_is_inside_bezpath(&path, &viewport_polygon, None, None)
}
@@ -3832,8 +3832,8 @@ fn quad_to_kurbo(quad: Quad) -> BezPath {
fn click_targets_to_kurbo<'a>(click_targets: impl Iterator<Item = &'a ClickTarget>, transform: DAffine2) -> BezPath {
let segments = click_targets
.filter_map(|target| if let ClickTargetType::Path(path) = target.target_type() { Some(path.segments()) } else { None })
.flatten()
.filter_map(|target| target.path_in_layer().map(|path| path.into_owned()))
.flat_map(|path| path.segments().collect::<Vec<_>>())
.map(|bezier| Affine::new(transform.to_cols_array()) * bezier);
BezPath::from_path_segments(segments)
}
@@ -1012,6 +1012,11 @@ impl OverlayContextInternal {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
ClickTargetType::Instance { path, transform } => {
let mut placed = (**path).clone();
placed.apply_affine(Affine::new(transform.to_cols_array()));
combined.extend(placed.elements().iter().copied());
}
}
}
@@ -972,6 +972,11 @@ impl OverlayContext {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
ClickTargetType::Instance { path, transform } => {
let mut placed = (**path).clone();
placed.apply_affine(Affine::new(transform.to_cols_array()));
combined.extend(placed.elements().iter().copied());
}
});
if !combined.is_empty() {
@@ -189,8 +189,8 @@ impl DocumentMetadata {
self.visual_targets(layer)?
.iter()
.filter_map(|click_target| match click_target.target_type() {
ClickTargetType::Path(path) => {
let mut transformed = path.clone();
ClickTargetType::Path(_) | ClickTargetType::Instance { .. } => {
let mut transformed = click_target.path_in_layer().map(|path| path.into_owned()).unwrap_or_default();
transformed.apply_affine(Affine::new(transform.to_cols_array()));
let control_box = transformed.control_box();
@@ -254,11 +254,8 @@ impl DocumentMetadata {
self.all_layers().filter_map(|layer| self.bounding_box_viewport(layer)).reduce(Quad::combine_bounds)
}
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &BezPath> {
self.visual_targets(layer).unwrap_or(&[]).iter().filter_map(|target| match target.target_type() {
ClickTargetType::Path(path) => Some(path),
ClickTargetType::FreePoint(_) => None,
})
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = std::borrow::Cow<'_, BezPath>> {
self.visual_targets(layer).unwrap_or(&[]).iter().filter_map(|target| target.path_in_layer())
}
pub fn layer_with_free_points_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &ClickTargetType> {
@@ -734,7 +734,7 @@ pub fn get_layer_snap_points(layer: LayerNodeIdentifier, snap_data: &SnapData, p
if !snap_data.ignore_bounds(layer) {
let to_document = document.metadata().transform_to_document(layer);
for bezpath in document.metadata().layer_outline(layer) {
bezpath_anchor_snap_points(layer, bezpath, snap_data, points, to_document);
bezpath_anchor_snap_points(layer, &bezpath, snap_data, points, to_document);
}
}
@@ -144,6 +144,7 @@ pub mod migrations {
colinear_manipulators: old.colinear_manipulators,
point_domain: old.point_domain,
segment_domain: old.segment_domain,
geometry_cell: Default::default(),
}),
VectorFormat::Vector(vector) => Some(vector),
VectorFormat::List(list) => list.element.into_iter().next(),
+79 -40
View File
@@ -73,8 +73,32 @@ impl MaskType {
}
}
/// Derived geometry per parked vector for one render pass: a park never
/// changes, so its address keys every lane that shares it, and the paths,
/// path data and stroke bounds compute once per distinct vector.
/// The renderer's view of the geometry carried on each vector: the cell on
/// the parked value fills once and every lane sharing the park reads it, so
/// the cache flows with the data across renders.
#[derive(Clone, Debug, Default)]
pub struct GeometryCache;
impl GeometryCache {
pub fn geometry(&mut self, vector: &Vector) -> Arc<graphic_types::vector_types::vector::VectorGeometry> {
vector.geometry()
}
pub fn svg_path(&mut self, vector: &Vector) -> Arc<String> {
vector.geometry().svg_path_cached()
}
pub fn stroke_bounds(&mut self, vector: &Vector, stroke: Option<&graphic_types::vector_types::vector::style::Stroke>) -> Option<[DVec2; 2]> {
vector.geometry().stroke_bounds_cached(stroke)
}
}
/// Mutable state used whilst rendering to an SVG
pub struct SvgRender {
pub geometry: GeometryCache,
pub svg: Vec<SvgSegment>,
pub svg_defs: String,
pub transform: DAffine2,
@@ -86,6 +110,7 @@ impl SvgRender {
pub fn new() -> Self {
Self {
svg: Vec::default(),
geometry: GeometryCache::default(),
svg_defs: String::new(),
transform: DAffine2::IDENTITY,
image_data: HashMap::new(),
@@ -178,6 +203,7 @@ pub struct SvgRenderOutput {
impl From<&SvgRenderOutput> for SvgRender {
fn from(value: &SvgRenderOutput) -> Self {
Self {
geometry: GeometryCache::default(),
svg: vec![value.svg.clone().into()],
svg_defs: value.svg_defs.clone(),
transform: DAffine2::IDENTITY,
@@ -205,6 +231,7 @@ impl Default for SvgRender {
#[derive(Clone, Debug, Default)]
pub struct RenderContext {
pub geometry: GeometryCache,
pub resource_overrides: Vec<(peniko::ImageBrush, Texture)>,
}
@@ -886,7 +913,7 @@ fn collect_element_metadata<'a>(
Graphic::Group(group) => collect_group_metadata(group, reach, metadata, footprint, element_id),
Graphic::Segmented(stack) => {
for group in segmented_groups(stack) {
collect_group_metadata(&group, reach, metadata, footprint, element_id);
collect_group_metadata_composed(&group, reach, metadata, footprint, element_id, lane_transform);
}
}
}
@@ -1002,9 +1029,13 @@ fn render_group_vello<'a>(group: &'a Group, reach: PaintReach<'a>, scene: &mut S
/// typed variant the conversion produced, so a caller's element id passes
/// through to the typed body unchanged.
fn collect_group_metadata<'a>(group: &'a Group, reach: PaintReach<'a>, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
collect_group_metadata_composed(group, reach, metadata, footprint, element_id, DAffine2::IDENTITY)
}
fn collect_group_metadata_composed<'a>(group: &'a Group, reach: PaintReach<'a>, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>, outer: DAffine2) {
let item = &group.content;
if let Some(run) = RunView::<Graphic>::new(item) {
collect_graphic_metadata_with(&run, reach, metadata, footprint, element_id)
collect_graphic_metadata_composed(&run, reach, metadata, footprint, element_id, outer)
} else if let Some(run) = RunView::<Vector>::new(item) {
collect_vector_metadata(&run, reach.appearance, metadata, footprint, element_id)
} else if let Some(run) = RunView::<Raster<CPU>>::new(item) {
@@ -1436,17 +1467,32 @@ fn collect_graphic_metadata_with<'a, 'e, S: LaneSource<Element = Graphic<'e>>>(
metadata: &mut RenderMetadata,
footprint: Footprint,
element_id: Option<NodeId>,
) {
collect_graphic_metadata_composed(source, inherited, metadata, footprint, element_id, DAffine2::IDENTITY)
}
/// The walk under a stack lane: the lane's transform composes onto each of the
/// stacked lanes, as the flat level would have carried it. `footprint` already
/// includes it, so only the lane's own transform advances it.
fn collect_graphic_metadata_composed<'a, 'e, S: LaneSource<Element = Graphic<'e>>>(
source: &'a S,
inherited: PaintReach<'a>,
metadata: &mut RenderMetadata,
footprint: Footprint,
element_id: Option<NodeId>,
outer: DAffine2,
) {
let paint_columns = PaintColumns::new(source);
for index in 0..source.lane_count() {
let item_transform: DAffine2 = source.attr::<Transform>(index);
let own_transform: DAffine2 = source.attr::<Transform>(index);
let item_transform = outer * own_transform;
let layer_path: &[NodeId] = source.attr::<EditorLayerPath>(index);
let layer = layer_path.last().copied();
let element = source.element(index).unwrap();
let reach = inherited.for_lane(&paint_columns, index);
let mut footprint = footprint;
footprint.transform *= item_transform;
footprint.transform *= own_transform;
if let Some(element_id) = layer {
collect_element_metadata(element, reach, item_transform, layer, metadata, footprint, Some(element_id));
@@ -1461,7 +1507,7 @@ fn collect_graphic_metadata_with<'a, 'e, S: LaneSource<Element = Graphic<'e>>>(
let mut all_upstream_outlines = Vec::new();
for index in 0..source.lane_count() {
let item_transform: DAffine2 = source.attr::<Transform>(index);
let item_transform: DAffine2 = outer * source.attr::<Transform>(index);
let element = source.element(index).unwrap();
let reach = inherited.for_lane(&paint_columns, index);
@@ -1587,19 +1633,17 @@ fn render_vector_item_svg<S: LaneSource<Element = Vector>>(source: &S, index: us
let applied_stroke_transform = render_params.alignment_parent_transform.unwrap_or(applied_stroke_transform);
let element_transform = set_stroke_transform.map(|stroke_transform| item_transform * stroke_transform.inverse());
let element_transform = element_transform.unwrap_or(DAffine2::IDENTITY);
let layer_bounds = vector.bounding_box().unwrap_or_default();
let transformed_bounds = vector.bounding_box_with_transform(applied_stroke_transform).unwrap_or_default();
let stroke_layer_bounds = vector.stroke_inclusive_bounding_box_with_transform(DAffine2::IDENTITY, element_stroke).unwrap_or(layer_bounds);
let geometry = render.geometry.geometry(vector);
let layer_bounds = geometry.bounding_box().unwrap_or_default();
let stroke_layer_bounds = render.geometry.stroke_bounds(vector, element_stroke).unwrap_or(layer_bounds);
let bounds_matrix = DAffine2::from_scale_angle_translation(layer_bounds[1] - layer_bounds[0], 0., layer_bounds[0]);
let stroke_bounds_matrix = DAffine2::from_scale_angle_translation(stroke_layer_bounds[1] - stroke_layer_bounds[0], 0., stroke_layer_bounds[0]);
let mut path = String::new();
for mut bezpath in vector.stroke_bezpath_iter() {
bezpath.apply_affine(Affine::new(applied_stroke_transform.to_cols_array()));
path.push_str(bezpath.to_svg().as_str());
}
let path = match applied_stroke_transform == DAffine2::IDENTITY {
true => (*render.geometry.svg_path(vector)).clone(),
false => geometry.svg_path(applied_stroke_transform),
};
let mask_type = if element_stroke.map(|x| x.align) == Some(StrokeAlign::Inside) {
MaskType::Clip
@@ -1613,7 +1657,7 @@ fn render_vector_item_svg<S: LaneSource<Element = Vector>>(source: &S, index: us
let stroke_graphic_list = resolved.stroke_paint.and_then(paint_cell_rows);
let stroke_graphic = stroke_graphic_list.and_then(|l| l.element(0));
let path_is_closed = vector.stroke_bezpath_iter().all(|path| matches!(path.elements().last(), Some(PathEl::ClosePath)));
let path_is_closed = geometry.closed;
let can_draw_aligned_stroke = path_is_closed
&& element_stroke.is_some_and(|stroke| stroke.has_renderable_stroke() && stroke.align.is_not_centered())
&& stroke_graphic.is_some_and(|graphic| !graphic.is_fully_transparent());
@@ -1685,6 +1729,8 @@ fn render_vector_item_svg<S: LaneSource<Element = Vector>>(source: &S, index: us
// `push_id` is only `Some` when `can_draw_aligned_stroke`, which is gated on `path_is_closed`
let (largest_scale, _) = singular_values(applied_stroke_transform);
let inflation = stroke.max_aabb_inflation(true) * largest_scale;
// The exact transformed bounds are only needed here, so they compute on demand.
let transformed_bounds = geometry.bounding_box_with_transform(applied_stroke_transform).unwrap_or_default();
let quad = Quad::from_box(transformed_bounds).inflate(inflation);
let (x, y) = quad.top_left().into();
let (width, height) = (quad.bottom_right() - quad.top_left()).into();
@@ -1862,10 +1908,11 @@ fn render_vector_item_vello<S: LaneSource<Element = Vector>>(
multiplied_transform
};
}
let layer_bounds = element.bounding_box().unwrap_or_default();
let geometry = context.geometry.geometry(element);
let layer_bounds = geometry.bounding_box().unwrap_or_default();
let mut path = kurbo::BezPath::new();
for mut bezpath in element.stroke_bezpath_iter() {
for mut bezpath in geometry.bezpaths.iter().cloned() {
bezpath.apply_affine(Affine::new(applied_stroke_transform.to_cols_array()));
for element in bezpath {
path.push(element);
@@ -2180,6 +2227,7 @@ fn collect_vector_metadata<S: LaneSource<Element = Vector>>(
footprint: Footprint,
caller_element_id: Option<NodeId>,
) {
let mut cache = GeometryCache::default();
// Aggregate all items' targets per element_id so multi-item lists (e.g. the "Text to Vector Glyphs" node) produce hit areas for every glyph.
// Targets are baked relative to the first item carrying each element_id, since that is the transform recorded as its `local_transforms` entry.
let mut reference_transforms: HashMap<NodeId, DAffine2> = HashMap::new();
@@ -2211,12 +2259,12 @@ fn collect_vector_metadata<S: LaneSource<Element = Vector>>(
let item_relative_transform = reference_inverse * transform;
let mut click_targets_unwrapped = Vec::new();
extend_targets_from_vector(&mut click_targets_unwrapped, &resolved, click_target_vector, item_relative_transform);
extend_targets_from_vector(&mut click_targets_unwrapped, &resolved, click_target_vector, item_relative_transform, &mut cache);
accumulated_click_targets.entry(element_id).or_default().extend(click_targets_unwrapped.into_iter().map(Arc::new));
// Outlines always use source geometry so the visual outline reflects actual letterforms
let mut outlines_unwrapped = Vec::new();
extend_targets_from_vector(&mut outlines_unwrapped, &resolved, element, item_relative_transform);
extend_targets_from_vector(&mut outlines_unwrapped, &resolved, element, item_relative_transform, &mut cache);
accumulated_outlines.entry(element_id).or_default().extend(outlines_unwrapped.into_iter().map(Arc::new));
// Source geometry (not the click-target override) so editing tools work on letterforms.
@@ -2266,6 +2314,7 @@ fn collect_vector_metadata<S: LaneSource<Element = Vector>>(
}
fn add_vector_upstream_click_targets<S: LaneSource<Element = Vector>>(source: &S, inherited_appearance: Option<&Appearance>, click_targets: &mut Vec<ClickTarget>) {
let mut cache = GeometryCache::default();
for index in 0..source.lane_count() {
let Some(element) = source.element(index) else { continue };
let transform: DAffine2 = source.attr::<Transform>(index);
@@ -2276,11 +2325,12 @@ fn add_vector_upstream_click_targets<S: LaneSource<Element = Vector>>(source: &S
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
extend_targets_from_vector(click_targets, &resolved, vector, transform);
extend_targets_from_vector(click_targets, &resolved, vector, transform, &mut cache);
}
}
fn add_vector_upstream_outline_targets<S: LaneSource<Element = Vector>>(source: &S, inherited_appearance: Option<&Appearance>, outlines: &mut Vec<ClickTarget>) {
let mut cache = GeometryCache::default();
// Source geometry only, ignoring `editor:click_target`, so outlines reflect actual letterforms
for index in 0..source.lane_count() {
let Some(element) = source.element(index) else { continue };
@@ -2289,7 +2339,7 @@ fn add_vector_upstream_outline_targets<S: LaneSource<Element = Vector>>(source:
let appearance = Appearance::cascade(source.attr::<AppearanceMarker>(index), inherited_appearance);
let resolved = appearance.map(Appearance::fill_and_stroke).unwrap_or_default();
extend_targets_from_vector(outlines, &resolved, element, transform);
extend_targets_from_vector(outlines, &resolved, element, transform, &mut cache);
}
}
@@ -2323,11 +2373,11 @@ impl Render for List<Vector> {
/// Build one combined `BezPath` (non-zero fill rule, so holes like the inside of an "O" work
/// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append.
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, resolved: &graphic_types::appearance::FillAndStroke<'_>, geometry: &Vector, transform: DAffine2) {
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, resolved: &graphic_types::appearance::FillAndStroke<'_>, geometry: &Vector, transform: DAffine2, cache: &mut GeometryCache) {
let filled = resolved.fill_paint.and_then(paint_cell_rows).is_some();
let mut bezpaths: Vec<BezPath> = geometry.stroke_bezpath_iter().filter(|bezpath| !bezpath.elements().is_empty()).collect();
let all_contours_closed = bezpaths.iter().all(|bezpath| matches!(bezpath.elements().last(), Some(PathEl::ClosePath)));
let shared = cache.geometry(geometry);
let all_contours_closed = shared.bezpaths.iter().filter(|bezpath| !bezpath.elements().is_empty()).all(|bezpath| matches!(bezpath.elements().last(), Some(PathEl::ClosePath)));
// Inside/Outside-aligned strokes reach `weight` from the centerline rather than `weight / 2` per side,
// so they need double the click inflation. Alignment is only honored by the renderer for fully-closed paths.
@@ -2339,22 +2389,11 @@ fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, resolved: &graphic
}
});
if filled {
for bezpath in &mut bezpaths {
if !matches!(bezpath.elements().last(), Some(PathEl::ClosePath)) {
bezpath.close_path();
}
}
}
if !bezpaths.is_empty() {
let mut combined_path = BezPath::new();
for bezpath in bezpaths {
combined_path.extend(bezpath);
}
let mut click_target = ClickTarget::new_with_path(combined_path, stroke_width);
click_target.apply_transform(transform);
// The click path is shared with every other lane over this geometry; the
// target carries only its placement.
let click_path = shared.click_path(filled);
if !click_path.elements().is_empty() {
let click_target = ClickTarget::new_with_shared_path(click_path, shared.bounding_box(), transform, stroke_width);
targets.push(click_target);
}
@@ -63,6 +63,23 @@ pub enum ClickTargetType {
/// (e.g. the inside of an "O") correctly count as outside the fill.
Path(BezPath),
FreePoint(FreePoint),
/// A shared local path under an instance transform: every lane holding one
/// parked geometry shares the path and carries only its own placement.
Instance {
#[cfg_attr(feature = "serde", serde(serialize_with = "serialize_shared_path", deserialize_with = "deserialize_shared_path"))]
path: Arc<BezPath>,
transform: DAffine2,
},
}
#[cfg(feature = "serde")]
fn serialize_shared_path<S: serde::Serializer>(path: &Arc<BezPath>, serializer: S) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(&**path, serializer)
}
#[cfg(feature = "serde")]
fn deserialize_shared_path<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Arc<BezPath>, D::Error> {
<BezPath as serde::Deserialize>::deserialize(deserializer).map(Arc::new)
}
/// Fixed-size ring buffer cache for rotated bounding boxes.
@@ -174,6 +191,32 @@ impl ClickTarget {
}
}
/// A target over a shared local path placed by `transform`; `local_bounds` are
/// the path's own, so the loose box is their transformed corners.
pub fn new_with_shared_path(path: Arc<BezPath>, local_bounds: BoundingBox, transform: DAffine2, stroke_width: f64) -> Self {
let bounding_box = local_bounds.map(|bounds| (transform * Quad::from_box(bounds)).bounding_box());
Self {
target_type: ClickTargetType::Instance { path, transform },
stroke_width,
bounding_box,
bounding_box_cache: Default::default(),
}
}
/// The path in the layer's space: borrowed for an owned path, placed for a
/// shared one, none for a point.
pub fn path_in_layer(&self) -> Option<std::borrow::Cow<'_, BezPath>> {
match &self.target_type {
ClickTargetType::Path(path) => Some(std::borrow::Cow::Borrowed(path)),
ClickTargetType::Instance { path, transform } => {
let mut placed = (**path).clone();
placed.apply_affine(Affine::new(transform.to_cols_array()));
Some(std::borrow::Cow::Owned(placed))
}
ClickTargetType::FreePoint(_) => None,
}
}
pub fn new_with_free_point(point: FreePoint) -> Self {
const MAX_LENGTH_FOR_NO_WIDTH_OR_HEIGHT: f64 = 1e-4 / 2.;
let stroke_width = 10.;
@@ -203,8 +246,14 @@ impl ClickTarget {
}
pub fn bounding_box_with_transform(&self, transform: DAffine2) -> BoundingBox {
match self.target_type {
ClickTargetType::Path(ref path) => {
let (path, transform) = match &self.target_type {
ClickTargetType::Path(path) => (path, transform),
ClickTargetType::Instance { path, transform: placement } => (&**path, transform * *placement),
// TODO: use point for calculation of bbox
ClickTargetType::FreePoint(_) => return self.bounding_box.map(|[a, b]| [transform.transform_point2(a), transform.transform_point2(b)]),
};
{
{
// Bypass cache for skewed transforms since rotation decomposition isn't valid
if transform.has_skew() {
return bezpath_bounding_box_with_transform(path, transform);
@@ -229,8 +278,6 @@ impl ClickTarget {
let mut write_lock = self.bounding_box_cache.write().unwrap();
write_lock.add_to_cache(path, rotation, scale, translation, fingerprint)
}
// TODO: use point for calculation of bbox
ClickTargetType::FreePoint(_) => self.bounding_box.map(|[a, b]| [transform.transform_point2(a), transform.transform_point2(b)]),
}
}
@@ -239,6 +286,9 @@ impl ClickTarget {
ClickTargetType::Path(ref mut path) => {
path.apply_affine(Affine::new(affine_transform.to_cols_array()));
}
ClickTargetType::Instance { ref mut transform, .. } => {
*transform = affine_transform * *transform;
}
ClickTargetType::FreePoint(ref mut point) => {
point.apply_transform(affine_transform);
}
@@ -251,6 +301,11 @@ impl ClickTarget {
ClickTargetType::Path(ref path) => {
self.bounding_box = bezpath_bounding_box_with_transform(path, DAffine2::IDENTITY);
}
// The loose box moves with the placement; exactness stays with `bounding_box_with_transform`.
ClickTargetType::Instance { ref path, transform } => {
let control = path.control_box();
self.bounding_box = (!path.elements().is_empty()).then(|| (transform * Quad::from_box([DVec2::new(control.min_x(), control.min_y()), DVec2::new(control.max_x(), control.max_y())])).bounding_box());
}
ClickTargetType::FreePoint(ref point) => {
self.bounding_box = Some([point.position - DVec2::splat(self.stroke_width / 2.), point.position + DVec2::splat(self.stroke_width / 2.)]);
}
@@ -261,6 +316,10 @@ impl ClickTarget {
pub fn intersect_path<It: Iterator<Item = PathSeg>>(&self, mut bezier_iter: impl FnMut() -> It, layer_transform: DAffine2) -> bool {
// Check if the matrix is not invertible
let mut layer_transform = layer_transform;
// A shared path is tested in its own space: the placement joins the layer transform.
if let ClickTargetType::Instance { transform, .. } = &self.target_type {
layer_transform *= *transform;
}
if layer_transform.matrix2.determinant().abs() <= f64::EPSILON {
layer_transform.matrix2 += DMat2::IDENTITY * 1e-4; // TODO: Is this the cleanest way to handle this?
}
@@ -268,8 +327,13 @@ impl ClickTarget {
let inverse = layer_transform.inverse();
let mut bezier_iter = || bezier_iter().map(|bezier| Affine::new(inverse.to_cols_array()) * bezier);
match self.target_type() {
ClickTargetType::Path(path) => {
let path = match self.target_type() {
ClickTargetType::Path(path) => Some(path),
ClickTargetType::Instance { path, .. } => Some(&**path),
ClickTargetType::FreePoint(_) => None,
};
match (path, self.target_type()) {
(Some(path), _) => {
// Outline intersection (catches strokes and both filled/unfilled shapes)
let outline_intersects = |path_segment: PathSeg| bezier_iter().any(|line| !filtered_segment_intersections(path_segment, line, None, None).is_empty());
if path.segments().any(outline_intersects) {
@@ -288,7 +352,8 @@ impl ClickTarget {
selection.close_path();
bezpath_is_inside_bezpath(path, &selection, None, None)
}
ClickTargetType::FreePoint(point) => bezier_iter().map(|segment: PathSeg| segment.winding(dvec2_to_point(point.position))).sum::<i32>() != 0,
(None, ClickTargetType::FreePoint(point)) => bezier_iter().map(|segment: PathSeg| segment.winding(dvec2_to_point(point.position))).sum::<i32>() != 0,
(None, _) => false,
}
}
@@ -320,6 +385,7 @@ impl ClickTarget {
// Check if the point is within the shape
match self.target_type() {
ClickTargetType::Path(path) => closed_contours(path).contains(dvec2_to_point(point)),
ClickTargetType::Instance { path, transform } => closed_contours(path).contains(dvec2_to_point(transform.inverse().transform_point2(point))),
ClickTargetType::FreePoint(free_point) => free_point.position == point,
}
} else {
@@ -896,11 +896,13 @@ impl Vector {
}
pub fn transform(&mut self, transform: DAffine2) {
self.geometry_cell = crate::vector::GeometryCell::default();
self.point_domain.transform(transform);
self.segment_domain.transform(transform);
}
pub fn vector_new_ids_from_hash(&mut self, node_id: u64) {
self.geometry_cell = crate::vector::GeometryCell::default();
let point_map = self.point_domain.ids().iter().map(|&old| (old, old.generate_from_hash(node_id))).collect::<HashMap<_, _>>();
let segment_map = self.segment_domain.ids().iter().map(|&old| (old, old.generate_from_hash(node_id))).collect::<HashMap<_, _>>();
@@ -20,6 +20,11 @@ pub struct Vector {
pub point_domain: PointDomain,
pub segment_domain: SegmentDomain,
/// The derived geometry, filled on first use and carried with the value:
/// a parked vector never changes, so every lane sharing it shares this.
#[cfg_attr(feature = "serde", serde(skip))]
pub geometry_cell: GeometryCell,
}
impl Default for Vector {
@@ -28,6 +33,7 @@ impl Default for Vector {
colinear_manipulators: Vec::new(),
point_domain: PointDomain::new(),
segment_domain: SegmentDomain::new(),
geometry_cell: GeometryCell::default(),
}
}
}
@@ -561,3 +567,219 @@ mod tests {
assert!(vector.segment_domain.ids().is_empty());
}
}
/// A vector's subpaths as kurbo paths, computed once and reused for bounds,
/// stroke bounds and path data: every query below reads the same paths the
/// per-call forms on [`Vector`] would build.
pub struct VectorGeometry {
pub bezpaths: Vec<kurbo::BezPath>,
/// Every subpath ends in a close, which is what stroke alignment needs.
pub closed: bool,
svg_path: std::sync::OnceLock<std::sync::Arc<String>>,
stroke_bounds: std::sync::Mutex<Vec<(u64, Option<[DVec2; 2]>)>>,
click_paths: [std::sync::OnceLock<std::sync::Arc<kurbo::BezPath>>; 2],
}
impl Clone for VectorGeometry {
fn clone(&self) -> Self {
Self::new(self.bezpaths.clone(), self.closed)
}
}
impl std::fmt::Debug for VectorGeometry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VectorGeometry").field("subpaths", &self.bezpaths.len()).field("closed", &self.closed).finish()
}
}
/// A vector's derived geometry, filled once. Cloning a vector starts an empty
/// cell (the copy may be edited); sharing a parked vector shares the filled one.
/// A content fingerprint guards against a value edited in place after the fill:
/// such a read recomputes and leaves the cell as it was.
#[derive(Default)]
pub struct GeometryCell(std::sync::OnceLock<(u64, std::sync::Arc<VectorGeometry>)>);
impl Clone for GeometryCell {
fn clone(&self) -> Self {
Self::default()
}
}
impl std::fmt::Debug for GeometryCell {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Constant on purpose: the cell is not part of the value.
f.write_str("GeometryCell")
}
}
impl PartialEq for GeometryCell {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Vector {
fn content_fingerprint(&self) -> u64 {
let mut hasher = graphene_hash::FxHasher64::default();
graphene_hash::CacheHash::cache_hash(self, &mut hasher);
std::hash::Hasher::finish(&hasher)
}
fn build_geometry(&self) -> VectorGeometry {
let bezpaths: Vec<kurbo::BezPath> = self.stroke_bezpath_iter().collect();
let closed = bezpaths.iter().all(|path| matches!(path.elements().last(), Some(kurbo::PathEl::ClosePath)));
VectorGeometry::new(bezpaths, closed)
}
/// The derived geometry, from the cell where it matches the content.
pub fn geometry(&self) -> std::sync::Arc<VectorGeometry> {
let fingerprint = self.content_fingerprint();
match self.geometry_cell.0.get() {
Some((filled, geometry)) if *filled == fingerprint => geometry.clone(),
Some(_) => std::sync::Arc::new(self.build_geometry()),
None => {
let geometry = std::sync::Arc::new(self.build_geometry());
let _ = self.geometry_cell.0.set((fingerprint, geometry.clone()));
geometry
}
}
}
}
impl VectorGeometry {
pub fn new(bezpaths: Vec<kurbo::BezPath>, closed: bool) -> Self {
Self {
bezpaths,
closed,
svg_path: std::sync::OnceLock::new(),
stroke_bounds: std::sync::Mutex::new(Vec::new()),
click_paths: [std::sync::OnceLock::new(), std::sync::OnceLock::new()],
}
}
/// The subpaths as one click path, non-empty ones only, closed when the
/// lane is filled; shared by every target over this geometry.
pub fn click_path(&self, filled: bool) -> std::sync::Arc<kurbo::BezPath> {
self.click_paths[usize::from(filled)]
.get_or_init(|| {
let mut combined = kurbo::BezPath::new();
for bezpath in self.bezpaths.iter().filter(|bezpath| !bezpath.elements().is_empty()) {
let mut bezpath = bezpath.clone();
if filled && !matches!(bezpath.elements().last(), Some(kurbo::PathEl::ClosePath)) {
bezpath.close_path();
}
combined.extend(bezpath);
}
std::sync::Arc::new(combined)
})
.clone()
}
/// The path data in the vector's own space, filled once.
pub fn svg_path_cached(&self) -> std::sync::Arc<String> {
self.svg_path.get_or_init(|| std::sync::Arc::new(self.svg_path(DAffine2::IDENTITY))).clone()
}
/// The stroke-inclusive bounds in the vector's own space, per stroke.
pub fn stroke_bounds_cached(&self, stroke: Option<&Stroke>) -> Option<[DVec2; 2]> {
let key = stroke.map_or(0, |stroke| {
let mut hasher = graphene_hash::FxHasher64::default();
graphene_hash::CacheHash::cache_hash(stroke, &mut hasher);
std::hash::Hasher::finish(&hasher)
});
if let Some((_, bounds)) = self.stroke_bounds.lock().unwrap().iter().find(|(known, _)| *known == key) {
return *bounds;
}
let bounds = self.stroke_inclusive_bounding_box_with_transform(DAffine2::IDENTITY, stroke);
self.stroke_bounds.lock().unwrap().push((key, bounds));
bounds
}
pub fn bounding_box(&self) -> Option<[DVec2; 2]> {
self.bounding_box_with_transform(DAffine2::IDENTITY)
}
pub fn bounding_box_with_transform(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
self.bounding_box_with_transform_rect(transform)
.map(|rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)])
}
fn bounding_box_with_transform_rect(&self, transform: DAffine2) -> Option<Rect> {
let combine = |r1: Rect, r2: Rect| r1.union(r2);
self.bezpaths
.iter()
.map(|bezpath| {
let mut bezpath = bezpath.clone();
bezpath.apply_affine(Affine::new(transform.to_cols_array()));
bezpath.bounding_box()
})
.reduce(combine)
}
/// [`Vector::stroke_inclusive_bounding_box_with_transform`] over the cached paths.
pub fn stroke_inclusive_bounding_box_with_transform(&self, transform: DAffine2, stroke: Option<&Stroke>) -> Option<[DVec2; 2]> {
let path_bounds = self.bounding_box_with_transform(transform);
let Some(stroke) = stroke else { return path_bounds };
let aligned_renders = stroke.align != StrokeAlign::Center && self.closed;
let kurbo_width = if aligned_renders { stroke.effective_width() } else { stroke.weight };
if kurbo_width <= 0. {
return path_bounds;
}
let join = match stroke.join {
StrokeJoin::Miter => kurbo::Join::Miter,
StrokeJoin::Bevel => kurbo::Join::Bevel,
StrokeJoin::Round => kurbo::Join::Round,
};
let cap = match stroke.cap {
StrokeCap::Butt => kurbo::Cap::Butt,
StrokeCap::Round => kurbo::Cap::Round,
StrokeCap::Square => kurbo::Cap::Square,
};
let stroke_style = kurbo::Stroke::new(kurbo_width)
.with_caps(cap)
.with_join(join)
.with_dashes(stroke.dash_offset, stroke.dash_lengths.clone())
.with_miter_limit(stroke.join_miter_limit);
let stroke_options = kurbo::StrokeOpts::default();
const STROKE_TOLERANCE: f64 = 0.25;
let stroke_local = Affine::new(stroke.transform.to_cols_array());
let stroke_local_inverse = (stroke.transform.matrix2.determinant() != 0.).then(|| Affine::new(stroke.transform.inverse().to_cols_array()));
let final_transform = Affine::new(transform.to_cols_array());
let stroke_bounds = self
.bezpaths
.iter()
.map(|bezpath| {
let mut bezpath = bezpath.clone();
bezpath.apply_affine(stroke_local);
let mut stroked = kurbo::stroke(bezpath, &stroke_style, &stroke_options, STROKE_TOLERANCE);
if let Some(inverse) = stroke_local_inverse {
stroked.apply_affine(inverse);
}
stroked.apply_affine(final_transform);
stroked.bounding_box()
})
.reduce(|r1, r2| r1.union(r2))
.map(|rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)]);
match (path_bounds, stroke_bounds) {
(Some(path), Some(stroke)) => Some([path[0].min(stroke[0]), path[1].max(stroke[1])]),
(path, stroke) => stroke.or(path),
}
}
/// The SVG path data of every subpath under `transform`, concatenated.
pub fn svg_path(&self, transform: DAffine2) -> String {
let mut path = String::new();
for bezpath in &self.bezpaths {
let mut bezpath = bezpath.clone();
bezpath.apply_affine(Affine::new(transform.to_cols_array()));
path.push_str(bezpath.to_svg().as_str());
}
path
}
}
+4
View File
@@ -41,8 +41,10 @@ fn intermediate_of<R: Render>(data: &R, render_params: &RenderParams) -> RenderI
RenderOutputTypeRequest::Svg => {
let mut render = SvgRender::new();
#[cfg(not(target_arch = "wasm32"))]
let started = std::time::Instant::now();
data.render_svg(&mut render, render_params);
#[cfg(not(target_arch = "wasm32"))]
core_types::record::note_render_nanos(started.elapsed().as_nanos() as u64);
RenderIntermediate {
@@ -96,11 +98,13 @@ fn render(
let logical_transform = glam::DAffine2::from_scale(glam::DVec2::splat(1.0 / render_params.scale)) * footprint.transform;
let logical_resolution = footprint.resolution.as_dvec2() / render_params.scale;
#[cfg(not(target_arch = "wasm32"))]
let started = std::time::Instant::now();
let mut render = SvgRender::from(data.as_ref());
render.wrap_with_transform(logical_transform, Some(logical_resolution));
let output = SvgRenderOutput::from(render);
#[cfg(not(target_arch = "wasm32"))]
core_types::record::note_render_nanos(started.elapsed().as_nanos() as u64);
assert!(output.svg_defs.is_empty());
+8 -7
View File
@@ -372,15 +372,15 @@ fn fill<'e>(
#[node_macro::node(category(""))]
fn fill_graphic_leveled<'e>(
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
(element, content_appearance): (Graphic<'static>, Attr<AppearanceMarker>),
(element, content_appearance): (&Graphic<'static>, Attr<AppearanceMarker>),
#[default(Color::BLACK)] paint: IList<Graphic<'static>>,
_backup_color: IList<Color>,
_backup_gradient: IList<Gradient>,
_gradient_form: GradientForm,
_has_transform: bool,
_transform: DAffine2,
) -> Result<(Graphic<'static>, Attr<'e, AppearanceMarker>), Interrupt> {
let bounds = match BoundingBox::bounding_box(&element, DAffine2::IDENTITY, false) {
) -> Result<(ElToken, Attr<'e, AppearanceMarker>), Interrupt> {
let bounds = match BoundingBox::bounding_box(element, DAffine2::IDENTITY, false) {
RenderBoundingBox::Rectangle(bounds) => Some(bounds),
_ => None,
};
@@ -388,7 +388,7 @@ fn fill_graphic_leveled<'e>(
default_gradient_paint(&mut paint, bounds, _gradient_form, _has_transform.then_some(_transform));
let appearance = stamped_appearance(*content_appearance, Coverage::new_fill(), &paint, CoverPlacement::Above);
let parked_appearance = park_appearance(ctx.arena(), appearance)?;
Ok((element, Attr(Some(parked_appearance))))
Ok((ElToken, Attr(Some(parked_appearance))))
}
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
@@ -447,7 +447,7 @@ fn stroke<'e>(
#[node_macro::node(category(""))]
fn stroke_graphic_leveled<'e>(
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
(element, content_transform, content_appearance): (Graphic<'static>, Attr<TransformAttr>, Attr<AppearanceMarker>),
(_element, content_transform, content_appearance): (&Graphic<'static>, Attr<TransformAttr>, Attr<AppearanceMarker>),
#[default(Color::BLACK)] paint: IList<Graphic<'static>>,
#[unit(" px")]
#[default(2.)]
@@ -458,7 +458,7 @@ fn stroke_graphic_leveled<'e>(
#[default(4.)] miter_limit: f64,
dash_pattern: DashPattern,
#[unit(" px")] dash_offset: f64,
) -> Result<(Graphic<'static>, Attr<TransformAttr>, Attr<'e, AppearanceMarker>), Interrupt> {
) -> Result<(ElToken, Attr<TransformAttr>, Attr<'e, AppearanceMarker>), Interrupt> {
let dash_lengths = dash_pattern.clamped_lengths();
let stroke = Stroke {
weight,
@@ -479,7 +479,7 @@ fn stroke_graphic_leveled<'e>(
// A below stroke is the chain running the stroke node before the fill, so the coverage appends above
let appearance = stamped_appearance(*content_appearance, Coverage::new_stroke(&coverage_stroke), &paint, CoverPlacement::Above);
let parked_appearance = park_appearance(ctx.arena(), appearance)?;
Ok((element, Attr(*content_transform), Attr(Some(parked_appearance))))
Ok((ElToken, Attr(*content_transform), Attr(Some(parked_appearance))))
}
pub use _fill_graphic_leveled_mod::fill_graphic_leveled_entries;
@@ -2183,6 +2183,7 @@ fn sample_polyline<'e, V: MapVectorContent + Clone + Send + Sync + CacheHash + '
point_domain: Default::default(),
segment_domain: Default::default(),
colinear_manipulators: Default::default(),
geometry_cell: Default::default(),
};
// Transfer the stroke transform from the input vector content to the result.