Refactor internal shape and reduce reliance on Kurbo (#617)

* Dissolve Points from path

* Add handling for removing the first anchor

* Add function to turn handles into bez_paths

* Created overlay manager, wip

* WIP Refactor of VectorShape / Overlays / ShapeEditor

* WIP stripping vector shape, anchor, point.

* WIP Removed kurbo deps from vector shape, anchor, point

* WIP Further work to make vector shapes / anchors / points more standalone.

* WIP more pruning

* WIP Progress on overlay_renderer

* WIP more overlay_renderer work

* WIP more pruning, cleared warnings

* WIP decided ShapeRenderer wasn't an accurate name, ShapeAdapter now. Error squashing continues.

* WIP squashed more errors, now need to decide if anchors should have unique IDs

* WIP Errors squashed, now to actually make it work.

* WIP Moved vector structs to graphene, beginning to remove bezpath from shape_layer

* Refactoring: disentangle kurbo from apply_affine

* Refactor internal shape and remove reliance on Kurbo (PR #617) - Disentangle Kurbo (#619)

* Refactoring: disentangle kurbo from apply_affine

* Broke boolean operations, refactor in state which compiles

* "fixed" boolean operation refactor related errors

* fixed apply_affine, which would not have applied any type of affine

* Small Cleanup, readability

* Fix issue with overlay styles no longer showing selection state.

* Resolved error with point option

* WIP, figuring out how to have one source of truth for VectorShape. Trying to avoid cloning.

* WIP work on single source of truth vectorshapes

* More steps toward single source of truth VectorShape

* Continued wip on making VectorShapes mutably accessible without cloning

* Wip using paths to reference vectorshapes instead, need to restructure ShapeEditor

* Decided to allow temporary copies of vectorshapes.

* Removed HashSet for selected shape indices

* Added @TrueDoctor's id_storage.rs with some heavy modification. Added it to VectorShape. Isn't yet used for folders.

* Integrated UniqueElements<T> with VectorShape to store VectorAnchors

* Improved storage_id.rs perf and cleaned up it's interface

* Iterator Implementations and fixes (#637)

* Refactoring: disentangle kurbo from apply_affine

* Broke boolean operations, refactor in state which compiles

* "fixed" boolean operation refactor related errors

* fixed apply_affine, which would not have applied any type of affine

* implemented transforms for VectorAnchors
implemented Not for VectorControlPointType

* started adding Vector Shape implementations of shape prototypes

* added several useful implemtations to UniqueElements

* added another implemnation for UniqueElements to make working with iterators easier, fixed vector-shape errors

* package-lock.json

* clean up rebase, added back Layer paths

* added deref implementation for VectorShape

* unnecesary variable

* simplify code by removing levels of indirection

* fixed errors

* merge cleanup

* removed package-lock.json

* Removed .selected from VectorShape, it isn't needed as layers are selected not shapes specifically.

* Removed transform and layer_path from VectorShape

* Auto-saving tentitively working. Work toward Overlay transform issues.

* Overlays properly hiding and caching. Not clearing cache yet and some tool switching issues remain, but progress.

* Putting layers in folders changes their unique ID. This is problematic. Assumed this was not the case.

* Removed need for closed bool, changed VectorShape to a tuple struct.

* WIP Switched to layer paths as opposed to VectorShapes. Next up add messages for changing VectorShapes.

* Added initial messages to edit VectorShape points.

* DeleteSelectedPoints messages implemented, selection isn't working currently though.

* Selection messages arriving in document, but transform is wrong.

* Selection, Deselection working, delete working for first point.

* Working towards moving points again

* Removed extra vec from UniqueElements, attempting to squash ordering bug. Still appears to occur though.

* Delete more stable, clean up, renamed to HandleIn, HandleOut

* Further vec_unique cleanup

* Further cleanup

* Removed Deref / DerefMut from VectorShape

* Document version++, will likely revert before merge into master

* Seleting / deleting handles tentitively working again.

* Version number bump, fixed tests.

* Fixed comment in VecUnique

* Improved VecUnique descriptor comment

* Renamed VecUnique to IdBackedVec to further clarify usage.

* Resolved formatting.

* WIP Fixing dragging points

* Fixed an instance where an OverlayMessage could be sent to the main document incorrectly.

* Deleting all of a shapes points now gracefully deletes the layer instead of crashing.

* Fixed handle configurations that would panic on deletion

* Single anchor dragging restored with multi-dragging next plus handles

* sides.into()

* Handle and Multi-point dragging working

* WIP Handle symmetry working again

* Handle mirroring functional again.

* Cleaned up warnings

* Fixed overlay outline not matching shape

* Git branch fix of compatibility with new master

* Fixed closed shape bug, replaced kurbo ellipse

* Removed unused func, updated comments

* Deleting points can undo, multiple shape selection deletes now working

* Removed AddOverlay* operations

* Partial fix for select drift, added helpers

* Don't snap against dragging points

* Properly cleanup path outline with multiple shapes

* Clear all points in other selected shapes

* Actually don't snap against dragging points

* Fix path tool & add snap angle and break handle

* Fix handle being set to NaN causing render issues

* Fix cached overlays not showing line -> curve

* Add operations for modifying paths

* Remove kurbo from pen tool

* Do not snap against handles when anchor selected

* Fix overlays not being cleaned up on path tool

* Fix handle position after dragging

* Use `Anchor` for text & no kurbo in operations

* Replace kurbo to_svg function

* Ngon no longer center scales by default, still some weird behaviour when holding alt

* Cleanup overlays

* Fix render and bounding box doctests

* Fix fun to_svg error

* Fix compile error

* Some code review

* Remove legacy `SelectPoint` on doubleclick

* Remove font from test document

* Fix the pen tool selection changed

* Reorder imports

Co-authored-by: Dennis <dennis@kobert.dev>
Co-authored-by: Caleb Dennis <caleb.dennis429@gmail.com>
Co-authored-by: caleb <56044292+caleb-ad@users.noreply.github.com>
Co-authored-by: Keavon Chambers <keavon@keavon.com>
Co-authored-by: 0hypercube <0hypercube@gmail.com>
Co-authored-by: 0HyperCube <78500760+0HyperCube@users.noreply.github.com>
This commit is contained in:
Oliver Davies
2022-07-05 15:02:18 -07:00
committed by Keavon Chambers
parent 6042b32a86
commit 20cfd5f600
48 changed files with 2461 additions and 1807 deletions

View File

@@ -404,7 +404,7 @@ impl PathGraph {
concat_paths(&mut curve, &self.edge(vertices[index - 1].0, vertices[index].0, vertices[index].1).unwrap().curve);
}
curve.push(PathEl::ClosePath);
ShapeLayer::from_bez_path(BezPath::from_vec(curve), style.clone(), false)
ShapeLayer::new(BezPath::from_vec(curve).iter().into(), style.clone())
}
}
@@ -535,24 +535,24 @@ pub fn composite_boolean_operation(mut select: BooleanOperation, shapes: &mut Ve
// TODO: check if shapes are filled
// TODO: Bug: shape with at least two subpaths and comprised of many unions sometimes has erroneous movetos embedded in edges
pub fn boolean_operation(mut select: BooleanOperation, alpha: &mut ShapeLayer, beta: &mut ShapeLayer) -> Result<Vec<ShapeLayer>, BooleanOperationError> {
if alpha.path.is_empty() || beta.path.is_empty() {
if alpha.shape.anchors().is_empty() || beta.shape.anchors().is_empty() {
return Err(BooleanOperationError::InvalidSelection);
}
if select == BooleanOperation::SubtractBack {
select = BooleanOperation::SubtractFront;
swap(alpha, beta);
}
alpha.path = close_path(&alpha.path);
beta.path = close_path(&beta.path);
let beta_reverse = close_path(&reverse_path(&beta.path));
let alpha_dir = Cycle::direction_for_path(&alpha.path)?;
let beta_dir = Cycle::direction_for_path(&beta.path)?;
let mut alpha_shape = close_path(&(&alpha.shape).into());
let beta_shape = close_path(&(&beta.shape).into());
let beta_reverse = close_path(&reverse_path(&beta_shape));
let alpha_dir = Cycle::direction_for_path(&alpha_shape)?;
let beta_dir = Cycle::direction_for_path(&beta_shape)?;
match select {
BooleanOperation::Union => {
match if beta_dir == alpha_dir {
PathGraph::from_paths(&alpha.path, &beta.path)
PathGraph::from_paths(&alpha_shape, &beta_shape)
} else {
PathGraph::from_paths(&alpha.path, &beta_reverse)
PathGraph::from_paths(&alpha_shape, &beta_reverse)
} {
Ok(graph) => {
let mut cycles = graph.get_cycles();
@@ -562,16 +562,20 @@ pub fn boolean_operation(mut select: BooleanOperation, alpha: &mut ShapeLayer, b
&alpha.style,
);
for interior in collect_shapes(&graph, &mut cycles, |dir| dir != alpha_dir, |_| &alpha.style)? {
add_subpath(&mut boolean_union.path, interior.path);
//TODO: this is not very efficient or nice to read
let mut a_path: BezPath = (&boolean_union.shape).into();
let b_path: BezPath = (&interior.shape).into();
add_subpath(&mut a_path, b_path);
boolean_union.shape = a_path.iter().into();
}
Ok(vec![boolean_union])
}
Err(BooleanOperationError::NoIntersections) => {
// If shape is inside the other the Union is just the larger
// Check could also be done with area and single ray cast
if cast_horizontal_ray(point_on_curve(&beta.path), &alpha.path) % 2 != 0 {
if cast_horizontal_ray(point_on_curve(&beta_shape), &alpha_shape) % 2 != 0 {
Ok(vec![alpha.clone()])
} else if cast_horizontal_ray(point_on_curve(&alpha.path), &beta.path) % 2 != 0 {
} else if cast_horizontal_ray(point_on_curve(&alpha_shape), &beta_shape) % 2 != 0 {
beta.style = alpha.style.clone();
Ok(vec![beta.clone()])
} else {
@@ -583,17 +587,17 @@ pub fn boolean_operation(mut select: BooleanOperation, alpha: &mut ShapeLayer, b
}
BooleanOperation::Difference => {
let graph = if beta_dir != alpha_dir {
PathGraph::from_paths(&alpha.path, &beta.path)?
PathGraph::from_paths(&alpha_shape, &beta_shape)?
} else {
PathGraph::from_paths(&alpha.path, &beta_reverse)?
PathGraph::from_paths(&alpha_shape, &beta_reverse)?
};
collect_shapes(&graph, &mut graph.get_cycles(), |_| true, |dir| if dir == alpha_dir { &alpha.style } else { &beta.style })
}
BooleanOperation::Intersection => {
match if beta_dir == alpha_dir {
PathGraph::from_paths(&alpha.path, &beta.path)
PathGraph::from_paths(&alpha_shape, &beta_shape)
} else {
PathGraph::from_paths(&alpha.path, &beta_reverse)
PathGraph::from_paths(&alpha_shape, &beta_reverse)
} {
Ok(graph) => {
let mut cycles = graph.get_cycles();
@@ -610,10 +614,10 @@ pub fn boolean_operation(mut select: BooleanOperation, alpha: &mut ShapeLayer, b
}
Err(BooleanOperationError::NoIntersections) => {
// Check could also be done with area and single ray cast
if cast_horizontal_ray(point_on_curve(&beta.path), &alpha.path) % 2 != 0 {
if cast_horizontal_ray(point_on_curve(&beta_shape), &alpha_shape) % 2 != 0 {
beta.style = alpha.style.clone();
Ok(vec![beta.clone()])
} else if cast_horizontal_ray(point_on_curve(&alpha.path), &beta.path) % 2 != 0 {
} else if cast_horizontal_ray(point_on_curve(&alpha_shape), &beta_shape) % 2 != 0 {
Ok(vec![alpha.clone()])
} else {
Err(BooleanOperationError::NothingDone)
@@ -627,14 +631,14 @@ pub fn boolean_operation(mut select: BooleanOperation, alpha: &mut ShapeLayer, b
}
BooleanOperation::SubtractFront => {
match if beta_dir != alpha_dir {
PathGraph::from_paths(&alpha.path, &beta.path)
PathGraph::from_paths(&alpha_shape, &beta_shape)
} else {
PathGraph::from_paths(&alpha.path, &beta_reverse)
PathGraph::from_paths(&alpha_shape, &beta_reverse)
} {
Ok(graph) => collect_shapes(&graph, &mut graph.get_cycles(), |dir| dir == alpha_dir, |_| &alpha.style),
Err(BooleanOperationError::NoIntersections) => {
if cast_horizontal_ray(point_on_curve(&beta.path), &alpha.path) % 2 != 0 {
add_subpath(&mut alpha.path, if beta_dir == alpha_dir { reverse_path(&beta.path) } else { beta.path.clone() });
if cast_horizontal_ray(point_on_curve(&beta_shape), &alpha_shape) % 2 != 0 {
add_subpath(&mut alpha_shape, if beta_dir == alpha_dir { reverse_path(&beta_shape) } else { beta_shape });
Ok(vec![alpha.clone()])
} else {
Err(BooleanOperationError::NothingDone)
@@ -654,7 +658,7 @@ pub fn cast_horizontal_ray(from: Point, into: &BezPath) -> usize {
});
let mut intersects = Vec::new();
for ref mut seg in into.segments() {
if seg.bounding_box().x1 > from.x {
if kurbo::ParamCurveExtrema::bounding_box(seg).x1 > from.x {
line_curve_intersections((&mut ray, seg), |_, b| valid_t(b), &mut intersects);
}
}

View File

@@ -1,16 +1,15 @@
use crate::boolean_ops::composite_boolean_operation;
use crate::intersection::Quad;
use crate::layers;
use crate::layers::folder_layer::FolderLayer;
use crate::layers::image_layer::ImageLayer;
use crate::layers::layer_info::{Layer, LayerData, LayerDataType, LayerDataTypeDiscriminant};
use crate::layers::shape_layer::ShapeLayer;
use crate::layers::style::RenderData;
use crate::layers::text_layer::{Font, FontCache, TextLayer};
use crate::layers::vector::vector_shape::VectorShape;
use crate::{DocumentError, DocumentResponse, Operation};
use glam::{DAffine2, DVec2};
use kurbo::Affine;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::cmp::max;
@@ -100,7 +99,7 @@ impl Document {
}
/// Returns a mutable reference to the layer or folder at the path.
fn layer_mut(&mut self, path: &[LayerId]) -> Result<&mut Layer, DocumentError> {
pub fn layer_mut(&mut self, path: &[LayerId]) -> Result<&mut Layer, DocumentError> {
if path.is_empty() {
return Ok(&mut self.root);
}
@@ -117,7 +116,7 @@ impl Document {
match (self.multiply_transforms(path), &self.layer(path)?.data) {
(Ok(shape_transform), LayerDataType::Shape(shape)) => {
let mut new_shape = shape.clone();
new_shape.path.apply_affine(Affine::new((undo_viewport * shape_transform).to_cols_array()));
new_shape.shape.apply_affine(undo_viewport * shape_transform);
shapes.push(new_shape);
}
(Ok(_), _) => return Err(DocumentError::InvalidPath),
@@ -127,6 +126,43 @@ impl Document {
Ok(shapes)
}
/// Return a copy of all VectorShapes currently in the document.
pub fn all_vector_shapes(&self) -> Vec<VectorShape> {
self.root.iter().flat_map(|layer| layer.as_vector_shape_copy()).collect::<Vec<VectorShape>>()
}
/// Returns references to all VectorShapes currently in the document.
pub fn all_vector_shapes_ref(&self) -> Vec<&VectorShape> {
self.root.iter().flat_map(|layer| layer.as_vector_shape()).collect::<Vec<&VectorShape>>()
}
/// Returns a reference to the requested VectorShape by providing a path to its owner layer.
pub fn vector_shape_ref<'a>(&'a self, path: &[LayerId]) -> Option<&'a VectorShape> {
self.layer(path).ok()?.as_vector_shape()
}
/// Returns a mutable reference of the requested VectorShape by providing a path to its owner layer.
pub fn vector_shape_mut<'a>(&'a mut self, path: &'a [LayerId]) -> Option<&'a mut VectorShape> {
self.layer_mut(path).ok()?.as_vector_shape_mut()
}
/// Set a VectorShape at the specified path.
pub fn set_vector_shape(&mut self, path: &[LayerId], shape: VectorShape) {
let layer = self.layer_mut(path);
if let Ok(layer) = layer {
if let LayerDataType::Shape(shape_layer) = &mut layer.data {
shape_layer.shape = shape;
// Is this needed?
layer.cache_dirty = true;
}
}
}
/// Set VectorShapes for multiple paths at once.
pub fn set_vector_shapes<'a>(&'a mut self, paths: impl Iterator<Item = &'a [LayerId]>, shapes: Vec<VectorShape>) {
paths.zip(shapes).for_each(|(path, shape)| self.set_vector_shape(path, shape));
}
pub fn common_layer_path_prefix<'a>(&self, layers: impl Iterator<Item = &'a [LayerId]>) -> &'a [LayerId] {
layers.reduce(|a, b| &a[..a.iter().zip(b.iter()).take_while(|&(a, b)| a == b).count()]).unwrap_or_default()
}
@@ -467,15 +503,6 @@ impl Document {
Some([vec![DocumentChanged, CreatedLayer { path: path.clone() }], update_thumbnails_upstream(&path)].concat())
}
Operation::AddOverlayEllipse { path, transform, style } => {
let mut ellipse = ShapeLayer::ellipse(style);
ellipse.render_index = -1;
let layer = Layer::new(LayerDataType::Shape(ellipse), transform);
self.set_layer(&path, layer, -1)?;
Some([vec![DocumentChanged, CreatedLayer { path }]].concat())
}
Operation::AddRect { path, insert_index, transform, style } => {
let layer = Layer::new(LayerDataType::Shape(ShapeLayer::rectangle(style)), transform);
@@ -483,15 +510,6 @@ impl Document {
Some([vec![DocumentChanged, CreatedLayer { path: path.clone() }], update_thumbnails_upstream(&path)].concat())
}
Operation::AddOverlayRect { path, transform, style } => {
let mut rect = ShapeLayer::rectangle(style);
rect.render_index = -1;
let layer = Layer::new(LayerDataType::Shape(rect), transform);
self.set_layer(&path, layer, -1)?;
Some([vec![DocumentChanged, CreatedLayer { path }]].concat())
}
Operation::AddLine { path, insert_index, transform, style } => {
let layer = Layer::new(LayerDataType::Shape(ShapeLayer::line(style)), transform);
@@ -499,15 +517,6 @@ impl Document {
Some([vec![DocumentChanged, CreatedLayer { path: path.clone() }], update_thumbnails_upstream(&path)].concat())
}
Operation::AddOverlayLine { path, transform, style } => {
let mut line = ShapeLayer::line(style);
line.render_index = -1;
let layer = Layer::new(LayerDataType::Shape(line), transform);
self.set_layer(&path, layer, -1)?;
Some([vec![DocumentChanged, CreatedLayer { path }]].concat())
}
Operation::AddText {
path,
insert_index,
@@ -577,24 +586,14 @@ impl Document {
Some([vec![DocumentChanged, CreatedLayer { path: path.clone() }], update_thumbnails_upstream(&path)].concat())
}
Operation::AddOverlayShape { path, style, bez_path, closed } => {
let mut shape = ShapeLayer::from_bez_path(bez_path, style, closed);
shape.render_index = -1;
let layer = Layer::new(LayerDataType::Shape(shape), DAffine2::IDENTITY.to_cols_array());
self.set_layer(&path, layer, -1)?;
Some([vec![DocumentChanged, CreatedLayer { path }]].concat())
}
Operation::AddShape {
path,
transform,
insert_index,
style,
bez_path,
closed,
vector_path,
} => {
let shape = ShapeLayer::from_bez_path(bez_path, style, closed);
let shape = ShapeLayer::new(vector_path, style);
self.set_layer(&path, Layer::new(LayerDataType::Shape(shape), transform), insert_index)?;
Some([vec![DocumentChanged, CreatedLayer { path }]].concat())
}
@@ -759,36 +758,57 @@ impl Document {
self.mark_as_dirty(&path)?;
Some([vec![DocumentChanged], update_thumbnails_upstream(&path)].concat())
}
Operation::SetShapePath { path, bez_path } => {
Operation::SetShapePath { path, vector_path } => {
self.mark_as_dirty(&path)?;
if let LayerDataType::Shape(shape) = &mut self.layer_mut(&path)?.data {
shape.path = bez_path;
shape.shape = vector_path;
}
Some(vec![DocumentChanged, LayerChanged { path }])
}
Operation::SetShapePathInViewport { path, bez_path, transform } => {
let transform = DAffine2::from_cols_array(&transform);
self.set_transform_relative_to_viewport(&path, transform)?;
self.mark_as_dirty(&path)?;
// Not using Document::layer_mut is necessary because we also need to borrow the font cache
let mut current_folder = &mut self.root;
let (folder_path, id) = split_path(&path)?;
for id in folder_path {
current_folder = current_folder.as_folder_mut()?.layer_mut(*id).ok_or_else(|| DocumentError::LayerNotFound(folder_path.into()))?;
Operation::InsertVectorAnchor { layer_path, anchor, after_id } => {
if let Ok(Some(shape)) = self.layer_mut(&layer_path).map(|layer| layer.as_vector_shape_mut()) {
shape.anchors_mut().insert(anchor, after_id);
self.mark_as_dirty(&layer_path)?;
}
let layer_mut = current_folder.as_folder_mut()?.layer_mut(id).ok_or_else(|| DocumentError::LayerNotFound(folder_path.into()))?;
if let LayerDataType::Text(t) = &mut layer_mut.data {
let bezpath = t.to_bez_path(t.load_face(font_cache));
layer_mut.data = layers::layer_info::LayerDataType::Shape(ShapeLayer::from_bez_path(bezpath, t.path_style.clone(), true));
Some([update_thumbnails_upstream(&layer_path), vec![DocumentChanged, LayerChanged { path: layer_path }]].concat())
}
Operation::PushVectorAnchor { layer_path, anchor } => {
if let Ok(Some(shape)) = self.layer_mut(&layer_path).map(|layer| layer.as_vector_shape_mut()) {
shape.anchors_mut().push(anchor);
self.mark_as_dirty(&layer_path)?;
}
if let LayerDataType::Shape(shape) = &mut layer_mut.data {
shape.path = bez_path;
Some([update_thumbnails_upstream(&layer_path), vec![DocumentChanged, LayerChanged { path: layer_path }]].concat())
}
Operation::RemoveVectorAnchor { layer_path, id } => {
if let Ok(Some(shape)) = self.layer_mut(&layer_path).map(|layer| layer.as_vector_shape_mut()) {
shape.anchors_mut().remove(id);
self.mark_as_dirty(&layer_path)?;
}
Some([vec![DocumentChanged, LayerChanged { path: path.clone() }], update_thumbnails_upstream(&path)].concat())
Some([update_thumbnails_upstream(&layer_path), vec![DocumentChanged, LayerChanged { path: layer_path }]].concat())
}
Operation::MoveVectorPoint {
layer_path,
id,
control_type,
position,
} => {
if let Ok(Some(shape)) = self.layer_mut(&layer_path).map(|layer| layer.as_vector_shape_mut()) {
if let Some(anchor) = shape.anchors_mut().by_id_mut(id) {
anchor.set_point_position(control_type as usize, position.into());
self.mark_as_dirty(&layer_path)?;
}
}
Some([update_thumbnails_upstream(&layer_path), vec![DocumentChanged, LayerChanged { path: layer_path }]].concat())
}
Operation::RemoveVectorPoint { layer_path, id, control_type } => {
if let Ok(Some(shape)) = self.layer_mut(&layer_path).map(|layer| layer.as_vector_shape_mut()) {
if let Some(anchor) = shape.anchors_mut().by_id_mut(id) {
anchor.points[control_type as usize] = None;
self.mark_as_dirty(&layer_path)?;
}
}
Some([update_thumbnails_upstream(&layer_path), vec![DocumentChanged, LayerChanged { path: layer_path }]].concat())
}
Operation::TransformLayerInScope { path, transform, scope } => {
let transform = DAffine2::from_cols_array(&transform);
@@ -864,6 +884,84 @@ impl Document {
self.mark_as_dirty(&path)?;
Some([vec![DocumentChanged], update_thumbnails_upstream(&path)].concat())
}
// We may not want the concept of selection here. For now leaving though.
Operation::SelectVectorPoints { layer_path, point_ids, add } => {
let layer = self.layer_mut(&layer_path)?;
if let Some(shape) = layer.as_vector_shape_mut() {
if !add {
shape.clear_selected_anchors();
}
shape.select_points(&point_ids, true);
}
Some(vec![LayerChanged { path: layer_path.clone() }])
}
Operation::DeselectVectorPoints { layer_path, point_ids } => {
let layer = self.layer_mut(&layer_path)?;
if let Some(shape) = layer.as_vector_shape_mut() {
shape.select_points(&point_ids, false);
}
Some(vec![LayerChanged { path: layer_path.clone() }])
}
Operation::DeselectAllVectorPoints { layer_path } => {
let layer = self.layer_mut(&layer_path)?;
if let Some(shape) = layer.as_vector_shape_mut() {
shape.clear_selected_anchors();
}
Some(vec![LayerChanged { path: layer_path.clone() }])
}
Operation::DeleteSelectedVectorPoints { layer_paths } => {
let mut responses = vec![];
for layer_path in layer_paths {
let layer = self.layer_mut(&layer_path)?;
if let Some(shape) = layer.as_vector_shape_mut() {
// Delete the selected points.
shape.delete_selected();
// Delete the layer if there are no longer any anchors
if (shape.anchors().len() - 1) == 0 {
self.delete(&layer_path)?;
responses.push(DocumentChanged);
responses.push(DocumentResponse::DeletedLayer { path: layer_path });
return Ok(Some(responses));
}
// If we still have anchors, update the layer and thumbnails
self.mark_as_dirty(&layer_path)?;
responses.push(DocumentChanged);
responses.push(LayerChanged { path: layer_path.clone() });
responses.append(&mut update_thumbnails_upstream(&layer_path));
}
}
Some(responses)
}
Operation::MoveSelectedVectorPoints { layer_path, delta, absolute_position } => {
if let Ok(viewspace) = self.generate_transform_relative_to_viewport(&layer_path) {
let objectspace = &viewspace.inverse();
let delta = objectspace.transform_vector2(DVec2::new(delta.0, delta.1));
let absolute_position = objectspace.transform_point2(DVec2::new(absolute_position.0, absolute_position.1));
let layer = self.layer_mut(&layer_path)?;
if let Some(shape) = layer.as_vector_shape_mut() {
shape.move_selected(delta, absolute_position, &viewspace);
}
}
self.mark_as_dirty(&layer_path)?;
Some([vec![DocumentChanged, LayerChanged { path: layer_path.clone() }], update_thumbnails_upstream(&layer_path)].concat())
}
Operation::SetSelectedHandleMirroring {
layer_path,
toggle_distance,
toggle_angle,
} => {
let layer = self.layer_mut(&layer_path)?;
if let Some(shape) = layer.as_vector_shape_mut() {
for anchor in shape.selected_anchors_any_points_mut() {
anchor.toggle_mirroring(toggle_distance, toggle_angle);
}
}
// This does nothing visually so we don't need to send any messages
None
}
};
Ok(responses)
}

View File

@@ -1,5 +1,6 @@
use crate::boolean_ops::{split_path_seg, subdivide_path_seg};
use crate::consts::{F64LOOSE, F64PRECISE};
use crate::layers::vector::vector_shape::VectorShape;
use glam::{DAffine2, DMat2, DVec2};
use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveDeriv, ParamCurveExtrema, PathSeg, Point, QuadBez, Rect, Shape, Vec2};
@@ -37,6 +38,24 @@ impl Quad {
path.close_path();
path
}
/// Generates a [VectorShape] of the quad
pub fn vector_shape(&self) -> VectorShape {
VectorShape::from_points(self.0.into_iter(), true)
}
/// Generates the axis aligned bounding box of the quad
pub fn bounding_box(&self) -> [DVec2; 2] {
[
self.0.into_iter().reduce(|a, b| a.min(b)).unwrap_or_default(),
self.0.into_iter().reduce(|a, b| a.max(b)).unwrap_or_default(),
]
}
/// Gets the center of a quad
pub fn center(&self) -> DVec2 {
self.0.iter().sum::<DVec2>() / 4.
}
}
impl Mul<Quad> for DAffine2 {
@@ -73,7 +92,7 @@ pub fn intersect_quad_bez_path(quad: Quad, shape: &BezPath, filled: bool) -> boo
return true;
}
// Check if selection is entirely within the shape
if filled && shape.contains(to_point(quad.0[0])) {
if filled && shape.contains(to_point(quad.center())) {
return true;
}
@@ -843,8 +862,11 @@ mod tests {
use super::*;
#[allow(unused_imports)]
use crate::boolean_ops::point_on_curve;
#[allow(unused_imports)]
use std::{fs::File, io::Write};
use std::fs::File;
#[allow(unused_imports)]
use std::io::Write;
/// Two intersect points, on different `PathSegs`.
#[ignore]

View File

@@ -0,0 +1,172 @@
use serde::{Deserialize, Serialize};
use std::ops::{Deref, DerefMut};
/// Brief description: A vec that allows indexing elements by both index and an assigned unique ID
/// Goals of this Data Structure:
/// - Drop-in replacement for a Vec.
/// - Provide an auto-assigned Unique ID per element upon insertion.
/// - Add elements to the start or end.
/// - Insert element by Unique ID. Insert directly after an existing element by its Unique ID.
/// - Access data by providing Unique ID.
/// - Maintain ordering among the elements.
/// - Remove elements without changing Unique IDs.
/// This data structure is somewhat similar to a linked list in terms of invarients.
/// The downside is that currently it requires a lot of iteration.
type ElementId = u64;
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct IdBackedVec<T> {
/// Contained elements
elements: Vec<T>,
/// The IDs of the [Elements] contained within this
element_ids: Vec<ElementId>,
/// The ID that will be assigned to the next element that is added to this
#[serde(skip)]
next_id: ElementId,
}
impl<T> IdBackedVec<T> {
/// Push a new element to the start of the vector
pub fn push_front(&mut self, element: T) -> Option<ElementId> {
self.next_id += 1;
self.elements.insert(0, element);
self.element_ids.insert(0, self.next_id);
Some(self.next_id)
}
// Push an element to the end of the vector
pub fn push_end(&mut self, element: T) -> Option<ElementId> {
self.next_id += 1;
self.elements.push(element);
self.element_ids.push(self.next_id);
Some(self.next_id)
}
/// Insert an element adjacent to the given ID
pub fn insert(&mut self, element: T, id: ElementId) -> Option<ElementId> {
if let Some(index) = self.index_from_id(id) {
self.next_id += 1;
self.elements.insert(index, element);
self.element_ids.insert(index, self.next_id);
return Some(self.next_id);
}
None
}
/// Push an element to the end of the vector
/// Overriden from Vec, so adding values without creating an id cannot occur
pub fn push(&mut self, element: T) -> Option<ElementId> {
self.push_end(element)
}
/// Add a range of elements of elements to the end of this vector
pub fn push_range<I>(&mut self, elements: I) -> Vec<ElementId>
where
I: IntoIterator<Item = T>,
{
let mut ids = vec![];
for element in elements {
if let Some(id) = self.push_end(element) {
ids.push(id);
}
}
ids
}
/// Remove an element with a given element ID from the within this container.
/// This operation will return false if the element ID is not found.
/// Preserve unique ID lookup by using swap end and updating hashmap
pub fn remove(&mut self, to_remove_id: ElementId) -> Option<T> {
if let Some(index) = self.index_from_id(to_remove_id) {
self.element_ids.remove(index);
return Some(self.elements.remove(index));
}
None
}
/// Get a single element with a given element ID from the within this container.
pub fn by_id(&self, id: ElementId) -> Option<&T> {
let index = self.index_from_id(id)?;
Some(&self.elements[index])
}
/// Get a mutable reference to a single element with a given element ID from the within this container.
pub fn by_id_mut(&mut self, id: ElementId) -> Option<&mut T> {
let index = self.index_from_id(id)?;
Some(&mut self.elements[index])
}
/// Get an element based on its index
pub fn by_index(&self, index: usize) -> Option<&T> {
self.elements.get(index)
}
/// Get a mutable element based on its index
pub fn by_index_mut(&mut self, index: usize) -> Option<&mut T> {
self.elements.get_mut(index)
}
/// Clear the elements and unique ids
pub fn clear(&mut self) {
self.elements.clear();
self.element_ids.clear();
}
/// Enumerate the ids and elements in this container `(&ElementId, &T)`
pub fn enumerate(&self) -> impl Iterator<Item = (&ElementId, &T)> {
self.element_ids.iter().zip(self.elements.iter())
}
/// Mutably Enumerate the ids and elements in this container `(&ElementId, &mut T)`
pub fn enumerate_mut(&mut self) -> impl Iterator<Item = (&ElementId, &mut T)> {
self.element_ids.iter().zip(self.elements.iter_mut())
}
/// If this container contains an element with the given ID
pub fn contains(&self, id: ElementId) -> bool {
self.element_ids.contains(&id)
}
/// Get the index of an element with the given ID
pub fn index_from_id(&self, element_id: ElementId) -> Option<usize> {
// Though this is a linear traversal, it is still likely faster than using a hashmap
self.element_ids.iter().position(|&id| id == element_id)
}
}
impl<T> Default for IdBackedVec<T> {
fn default() -> Self {
IdBackedVec {
elements: vec![],
element_ids: vec![],
next_id: 0,
}
}
}
/// Allows for usage of UniqueElements as a Vec<T>
impl<T> Deref for IdBackedVec<T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
&self.elements
}
}
// TODO Consider removing this, it could allow for ElementIds and Elements to get out of sync
/// Allows for mutable usage of UniqueElements as a Vec<T>
impl<T> DerefMut for IdBackedVec<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.elements
}
}
/// Allows use with iterators
/// Also allows constructing UniqueElements with collect
impl<A> FromIterator<A> for IdBackedVec<A> {
fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
let mut new = IdBackedVec::default();
// Add to the end of the existing elements
new.push_range(iter);
new
}
}

View File

@@ -4,6 +4,7 @@ use super::image_layer::ImageLayer;
use super::shape_layer::ShapeLayer;
use super::style::{PathStyle, RenderData};
use super::text_layer::TextLayer;
use super::vector::vector_shape::VectorShape;
use crate::intersection::Quad;
use crate::layers::text_layer::FontCache;
use crate::DocumentError;
@@ -103,7 +104,7 @@ pub trait LayerData {
/// assert_eq!(
/// svg,
/// "<g transform=\"matrix(\n1,-0,-0,1,-0,-0)\">\
/// <path d=\"M0 0L1 0L1 1L0 1Z\" fill=\"none\" />\
/// <path d=\"M0,0L0,1L1,1L1,0Z\" fill=\"none\" />\
/// </g>"
/// );
/// ```
@@ -371,6 +372,27 @@ impl Layer {
}
}
pub fn as_vector_shape(&self) -> Option<&VectorShape> {
match &self.data {
LayerDataType::Shape(s) => Some(&s.shape),
_ => None,
}
}
pub fn as_vector_shape_copy(&self) -> Option<VectorShape> {
match &self.data {
LayerDataType::Shape(s) => Some(s.shape.clone()),
_ => None,
}
}
pub fn as_vector_shape_mut(&mut self) -> Option<&mut VectorShape> {
match &mut self.data {
LayerDataType::Shape(s) => Some(&mut s.shape),
_ => None,
}
}
/// Get a reference to the Folder wrapped by the layer.
/// This operation will fail if the [Layer type](Layer::data) is not `LayerDataType::Folder`.
pub fn as_folder(&self) -> Result<&FolderLayer, DocumentError> {

View File

@@ -18,6 +18,7 @@
pub mod blend_mode;
/// Contains the [FolderLayer](folder_layer::FolderLayer) type that encapsulates other layers, including more folders.
pub mod folder_layer;
pub mod id_vec;
/// Contains the [ImageLayer](image_layer::ImageLayer) type that contains a bitmap image.
pub mod image_layer;
/// Contains the base [Layer](layer_info::Layer) type, an abstraction over the different types of layers.
@@ -27,3 +28,4 @@ pub mod shape_layer;
pub mod style;
/// Contains the [TextLayer](text_layer::TextLayer) type.
pub mod text_layer;
pub mod vector;

View File

@@ -1,18 +1,14 @@
use super::layer_info::LayerData;
use super::style::{self, PathStyle, RenderData, ViewMode};
use super::vector::vector_shape::VectorShape;
use crate::intersection::{intersect_quad_bez_path, Quad};
use crate::layers::text_layer::FontCache;
use crate::LayerId;
use glam::{DAffine2, DMat2, DVec2};
use kurbo::{Affine, BezPath, Shape as KurboShape};
use serde::{Deserialize, Serialize};
use std::fmt::Write;
fn glam_to_kurbo(transform: DAffine2) -> Affine {
Affine::new(transform.to_cols_array())
}
/// A generic SVG element defined using Bezier paths.
/// Shapes are rendered as
/// [`<path>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path)
@@ -21,21 +17,19 @@ fn glam_to_kurbo(transform: DAffine2) -> Affine {
/// group that the transformation matrix is applied to.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ShapeLayer {
/// A Bezier path.
pub path: BezPath,
/// The geometry of the layer.
pub shape: VectorShape,
/// The visual style of the shape.
pub style: style::PathStyle,
// TODO: We might be able to remove this in a future refactor
pub render_index: i32,
/// Whether or not the [path](ShapeLayer::path) connects to itself.
pub closed: bool,
}
impl LayerData for ShapeLayer {
fn render(&mut self, svg: &mut String, svg_defs: &mut String, transforms: &mut Vec<DAffine2>, render_data: RenderData) {
let mut path = self.path.clone();
let mut vector_shape = self.shape.clone();
let kurbo::Rect { x0, y0, x1, y1 } = path.bounding_box();
let kurbo::Rect { x0, y0, x1, y1 } = vector_shape.bounding_box();
let layer_bounds = [(x0, y0).into(), (x1, y1).into()];
let transform = self.transform(transforms, render_data.view_mode);
@@ -44,9 +38,9 @@ impl LayerData for ShapeLayer {
let _ = write!(svg, "<!-- SVG shape has an invalid transform -->");
return;
}
path.apply_affine(glam_to_kurbo(transform));
vector_shape.apply_affine(transform);
let kurbo::Rect { x0, y0, x1, y1 } = path.bounding_box();
let kurbo::Rect { x0, y0, x1, y1 } = vector_shape.bounding_box();
let transformed_bounds = [(x0, y0).into(), (x1, y1).into()];
let _ = writeln!(svg, r#"<g transform="matrix("#);
@@ -57,33 +51,37 @@ impl LayerData for ShapeLayer {
let _ = write!(
svg,
r#"<path d="{}" {} />"#,
path.to_svg(),
vector_shape.to_svg(),
self.style.render(render_data.view_mode, svg_defs, transform, layer_bounds, transformed_bounds)
);
let _ = svg.write_str("</g>");
}
fn bounding_box(&self, transform: glam::DAffine2, _font_cache: &FontCache) -> Option<[DVec2; 2]> {
use kurbo::Shape;
let mut path = self.path.clone();
let mut vector_shape = self.shape.clone();
if transform.matrix2 == DMat2::ZERO {
return None;
}
path.apply_affine(glam_to_kurbo(transform));
vector_shape.apply_affine(transform);
let kurbo::Rect { x0, y0, x1, y1 } = path.bounding_box();
let kurbo::Rect { x0, y0, x1, y1 } = vector_shape.bounding_box();
Some([(x0, y0).into(), (x1, y1).into()])
}
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, _font_cache: &FontCache) {
if intersect_quad_bez_path(quad, &self.path, self.style.fill().is_some()) {
let filled = self.style.fill().is_some() || self.shape.anchors().last().filter(|anchor| anchor.is_close()).is_some();
if intersect_quad_bez_path(quad, &(&self.shape).into(), filled) {
intersections.push(path.clone());
}
}
}
impl ShapeLayer {
/// Construct a new [ShapeLayer] with the specified [VectorShape] and [PathStyle]
pub fn new(shape: VectorShape, style: PathStyle) -> Self {
Self { shape, style, render_index: 1 }
}
pub fn transform(&self, transforms: &[DAffine2], mode: ViewMode) -> DAffine2 {
let start = match (mode, self.render_index) {
(ViewMode::Outline, _) => 0,
@@ -93,15 +91,7 @@ impl ShapeLayer {
transforms.iter().skip(start).fold(DAffine2::IDENTITY, |a, b| a * *b)
}
pub fn from_bez_path(bez_path: BezPath, style: PathStyle, closed: bool) -> Self {
Self {
path: bez_path,
style,
render_index: 1,
closed,
}
}
/// TODO The behavior of ngon changed from the previous iteration slightly, match original behavior
/// Create an N-gon.
///
/// # Panics
@@ -132,136 +122,55 @@ impl ShapeLayer {
path.close_path();
Self {
path,
shape: VectorShape::new_ngon(DVec2::new(0., 0.), sides.into(), 1.),
style,
render_index: 1,
closed: true,
}
}
/// Create a rectangular shape.
pub fn rectangle(style: PathStyle) -> Self {
Self {
path: kurbo::Rect::new(0., 0., 1., 1.).to_path(0.01),
shape: VectorShape::new_rect(DVec2::new(0., 0.), DVec2::new(1., 1.)),
style,
render_index: 1,
closed: true,
}
}
/// Create an elliptical shape.
pub fn ellipse(style: PathStyle) -> Self {
Self {
path: kurbo::Ellipse::from_rect(kurbo::Rect::new(0., 0., 1., 1.)).to_path(0.01),
shape: VectorShape::new_ellipse(DVec2::new(0., 0.), DVec2::new(1., 1.)),
style,
render_index: 1,
closed: true,
}
}
/// Create a straight line from (0, 0) to (1, 0).
pub fn line(style: PathStyle) -> Self {
Self {
path: kurbo::Line::new((0., 0.), (1., 0.)).to_path(0.01),
shape: VectorShape::new_line(DVec2::new(0., 0.), DVec2::new(1., 0.)),
style,
render_index: 1,
closed: false,
}
}
/// Create a polygonal line that visits each provided point.
pub fn poly_line(points: Vec<impl Into<glam::DVec2>>, style: PathStyle) -> Self {
let mut path = kurbo::BezPath::new();
points
.into_iter()
.map(|v| v.into())
.map(|v: DVec2| kurbo::Point { x: v.x, y: v.y })
.enumerate()
.for_each(|(i, p)| if i == 0 { path.move_to(p) } else { path.line_to(p) });
Self {
path,
shape: VectorShape::new_poly_line(points),
style,
render_index: 0,
closed: false,
}
}
/// Creates a smooth bezier spline that passes through all given points.
/// The algorithm used in this implementation is described here: <https://www.particleincell.com/2012/bezier-splines/>
pub fn spline(points: Vec<impl Into<glam::DVec2>>, style: PathStyle) -> Self {
let mut path = kurbo::BezPath::new();
// Creating a bezier spline is only necessary for 3 or more points.
// For 2 given points a line segment is created instead.
if points.len() > 2 {
let points: Vec<_> = points.into_iter().map(|v| v.into()).map(|v: DVec2| kurbo::Vec2 { x: v.x, y: v.y }).collect();
// Number of bezier segments
let n = points.len() - 1;
// Control points for each bezier segment
let mut p1 = vec![kurbo::Vec2::ZERO; n];
let mut p2 = vec![kurbo::Vec2::ZERO; n];
// Tri-diagonal matrix coefficients a, b and c (see https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm)
let mut a = vec![1.0; n];
a[0] = 0.0;
a[n - 1] = 2.0;
let mut b = vec![4.0; n];
b[0] = 2.0;
b[n - 1] = 7.0;
let mut c = vec![1.0; n];
c[n - 1] = 0.0;
let mut r: Vec<_> = (0..n).map(|i| 4.0 * points[i] + 2.0 * points[i + 1]).collect();
r[0] = points[0] + (2.0 * points[1]);
r[n - 1] = 8.0 * points[n - 1] + points[n];
// Solve with Thomas algorithm (see https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm)
for i in 1..n {
let m = a[i] / b[i - 1];
b[i] -= m * c[i - 1];
let last_iteration_r = r[i - 1];
r[i] -= m * last_iteration_r;
}
// Determine first control point for each segment
p1[n - 1] = r[n - 1] / b[n - 1];
for i in (0..n - 1).rev() {
p1[i] = (r[i] - c[i] * p1[i + 1]) / b[i];
}
// Determine second control point per segment from first
for i in 0..n - 1 {
p2[i] = 2.0 * points[i + 1] - p1[i + 1];
}
p2[n - 1] = 0.5 * (points[n] + p1[n - 1]);
// Create bezier path from given points and computed control points
points.into_iter().enumerate().for_each(|(i, p)| {
if i == 0 {
path.move_to(p.to_point())
} else {
path.curve_to(p1[i - 1].to_point(), p2[i - 1].to_point(), p.to_point())
}
});
} else {
points
.into_iter()
.map(|v| v.into())
.map(|v: DVec2| kurbo::Point { x: v.x, y: v.y })
.enumerate()
.for_each(|(i, p)| if i == 0 { path.move_to(p) } else { path.line_to(p) });
}
Self {
path,
shape: VectorShape::new_spline(points),
style,
render_index: 0,
closed: false,
}
}
}

View File

@@ -1,21 +1,17 @@
use super::layer_info::LayerData;
use super::style::{PathStyle, RenderData, ViewMode};
use super::vector::vector_shape::VectorShape;
use crate::intersection::{intersect_quad_bez_path, Quad};
use crate::LayerId;
pub use font_cache::{Font, FontCache};
use glam::{DAffine2, DMat2, DVec2};
use kurbo::{Affine, BezPath, Rect, Shape};
use rustybuzz::Face;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
mod font_cache;
mod to_kurbo;
fn glam_to_kurbo(transform: DAffine2) -> Affine {
Affine::new(transform.to_cols_array())
}
mod to_path;
/// A line, or multiple lines, of text drawn in the document.
/// Like [ShapeLayers](super::shape_layer::ShapeLayer), [TextLayer] are rendered as
@@ -33,7 +29,7 @@ pub struct TextLayer {
#[serde(skip)]
pub editable: bool,
#[serde(skip)]
pub cached_path: Option<BezPath>,
pub cached_path: Option<VectorShape>,
}
impl LayerData for TextLayer {
@@ -72,12 +68,12 @@ impl LayerData for TextLayer {
} else {
let buzz_face = self.load_face(render_data.font_cache);
let mut path = self.to_bez_path(buzz_face);
let mut path = self.to_vector_path(buzz_face);
let kurbo::Rect { x0, y0, x1, y1 } = path.bounding_box();
let bounds = [(x0, y0).into(), (x1, y1).into()];
path.apply_affine(glam_to_kurbo(transform));
path.apply_affine(transform);
let kurbo::Rect { x0, y0, x1, y1 } = path.bounding_box();
let transformed_bounds = [(x0, y0).into(), (x1, y1).into()];
@@ -95,21 +91,17 @@ impl LayerData for TextLayer {
fn bounding_box(&self, transform: glam::DAffine2, font_cache: &FontCache) -> Option<[DVec2; 2]> {
let buzz_face = Some(self.load_face(font_cache)?);
let mut path = self.bounding_box(&self.text, buzz_face).to_path(0.1);
if transform.matrix2 == DMat2::ZERO {
return None;
}
path.apply_affine(glam_to_kurbo(transform));
let kurbo::Rect { x0, y0, x1, y1 } = path.bounding_box();
Some([(x0, y0).into(), (x1, y1).into()])
Some((transform * self.bounding_box(&self.text, buzz_face)).bounding_box())
}
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, font_cache: &FontCache) {
let buzz_face = self.load_face(font_cache);
if intersect_quad_bez_path(quad, &self.bounding_box(&self.text, buzz_face).to_path(0.), true) {
if intersect_quad_bez_path(quad, &self.bounding_box(&self.text, buzz_face).path(), true) {
intersections.push(path.clone());
}
}
@@ -144,10 +136,10 @@ impl TextLayer {
new
}
/// Converts to a [BezPath], populating the cache if necessary.
/// Converts to a [VectorShape], populating the cache if necessary.
#[inline]
pub fn to_bez_path(&mut self, buzz_face: Option<Face>) -> BezPath {
if self.cached_path.as_ref().filter(|x| !x.is_empty()).is_none() {
pub fn to_vector_path(&mut self, buzz_face: Option<Face>) -> VectorShape {
if self.cached_path.as_ref().filter(|x| !x.anchors().is_empty()).is_none() {
let path = self.generate_path(buzz_face);
self.cached_path = Some(path.clone());
return path;
@@ -155,23 +147,23 @@ impl TextLayer {
self.cached_path.clone().unwrap()
}
/// Converts to a [BezPath], without populating the cache.
/// Converts to a [VectorShape], without populating the cache.
#[inline]
pub fn to_bez_path_nonmut(&self, font_cache: &FontCache) -> BezPath {
pub fn to_vector_path_nonmut(&self, font_cache: &FontCache) -> VectorShape {
let buzz_face = self.load_face(font_cache);
self.cached_path.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| self.generate_path(buzz_face))
self.cached_path.clone().filter(|x| !x.anchors().is_empty()).unwrap_or_else(|| self.generate_path(buzz_face))
}
#[inline]
pub fn generate_path(&self, buzz_face: Option<Face>) -> BezPath {
to_kurbo::to_kurbo(&self.text, buzz_face, self.size, self.line_width)
pub fn generate_path(&self, buzz_face: Option<Face>) -> VectorShape {
to_path::to_path(&self.text, buzz_face, self.size, self.line_width)
}
#[inline]
pub fn bounding_box(&self, text: &str, buzz_face: Option<Face>) -> Rect {
let far = to_kurbo::bounding_box(text, buzz_face, self.size, self.line_width);
Rect::new(0., 0., far.x, far.y)
pub fn bounding_box(&self, text: &str, buzz_face: Option<Face>) -> Quad {
let far = to_path::bounding_box(text, buzz_face, self.size, self.line_width);
Quad::from_box([DVec2::ZERO, far])
}
pub fn update_text(&mut self, text: String, font_cache: &FontCache) {

View File

@@ -1,42 +1,55 @@
use crate::layers::vector::constants::ControlPointType;
use crate::layers::vector::vector_anchor::VectorAnchor;
use crate::layers::vector::vector_control_point::VectorControlPoint;
use crate::layers::vector::vector_shape::VectorShape;
use glam::DVec2;
use kurbo::{BezPath, Point, Vec2};
use rustybuzz::{GlyphBuffer, UnicodeBuffer};
use ttf_parser::{GlyphId, OutlineBuilder};
struct Builder {
path: BezPath,
pos: Point,
offset: Vec2,
path: VectorShape,
pos: DVec2,
offset: DVec2,
ascender: f64,
scale: f64,
}
impl Builder {
fn point(&self, x: f32, y: f32) -> DVec2 {
self.pos + self.offset + DVec2::new(x as f64, self.ascender - y as f64) * self.scale
}
}
impl OutlineBuilder for Builder {
fn move_to(&mut self, x: f32, y: f32) {
self.path.move_to(self.pos + self.offset + Vec2::new(x as f64, self.ascender - y as f64) * self.scale);
let anchor = self.point(x, y);
if self.path.anchors().last().filter(|el| el.points.iter().any(Option::is_some)).is_some() {
self.path.anchors_mut().push_end(VectorAnchor::closed());
}
self.path.anchors_mut().push_end(VectorAnchor::new(anchor));
}
fn line_to(&mut self, x: f32, y: f32) {
self.path.line_to(self.pos + self.offset + Vec2::new(x as f64, self.ascender - y as f64) * self.scale);
let anchor = self.point(x, y);
self.path.anchors_mut().push_end(VectorAnchor::new(anchor));
}
fn quad_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32) {
self.path.quad_to(
self.pos + self.offset + Vec2::new(x1 as f64, self.ascender - y1 as f64) * self.scale,
self.pos + self.offset + Vec2::new(x2 as f64, self.ascender - y2 as f64) * self.scale,
);
let [handle, anchor] = [self.point(x1, y1), self.point(x2, y2)];
self.path.anchors_mut().last_mut().unwrap().points[ControlPointType::OutHandle] = Some(VectorControlPoint::new(handle, ControlPointType::OutHandle));
self.path.anchors_mut().push_end(VectorAnchor::new(anchor));
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) {
self.path.curve_to(
self.pos + self.offset + Vec2::new(x1 as f64, self.ascender - y1 as f64) * self.scale,
self.pos + self.offset + Vec2::new(x2 as f64, self.ascender - y2 as f64) * self.scale,
self.pos + self.offset + Vec2::new(x3 as f64, self.ascender - y3 as f64) * self.scale,
);
let [handle1, handle2, anchor] = [self.point(x1, y1), self.point(x2, y2), self.point(x3, y3)];
self.path.anchors_mut().last_mut().unwrap().points[ControlPointType::OutHandle] = Some(VectorControlPoint::new(handle1, ControlPointType::OutHandle));
self.path.anchors_mut().push_end(VectorAnchor::new(anchor));
self.path.anchors_mut().last_mut().unwrap().points[ControlPointType::InHandle] = Some(VectorControlPoint::new(handle2, ControlPointType::InHandle));
}
fn close(&mut self) {
self.path.close_path();
self.path.anchors_mut().push_end(VectorAnchor::closed());
}
}
@@ -67,19 +80,19 @@ fn wrap_word(line_width: Option<f64>, glyph_buffer: &GlyphBuffer, scale: f64, x_
false
}
pub fn to_kurbo(str: &str, buzz_face: Option<rustybuzz::Face>, font_size: f64, line_width: Option<f64>) -> BezPath {
pub fn to_path(str: &str, buzz_face: Option<rustybuzz::Face>, font_size: f64, line_width: Option<f64>) -> VectorShape {
let buzz_face = match buzz_face {
Some(face) => face,
// Show blank layer if font has not loaded
None => return BezPath::default(),
None => return VectorShape::default(),
};
let (scale, line_height, mut buffer) = font_properties(&buzz_face, font_size);
let mut builder = Builder {
path: BezPath::new(),
pos: Point::ZERO,
offset: Vec2::ZERO,
path: VectorShape::new(),
pos: DVec2::ZERO,
offset: DVec2::ZERO,
ascender: (buzz_face.ascender() as f64 / buzz_face.height() as f64) * font_size / scale,
scale,
};
@@ -91,23 +104,23 @@ pub fn to_kurbo(str: &str, buzz_face: Option<rustybuzz::Face>, font_size: f64, l
let glyph_buffer = rustybuzz::shape(&buzz_face, &[], buffer);
if wrap_word(line_width, &glyph_buffer, scale, builder.pos.x) {
builder.pos = Point::new(0., builder.pos.y + line_height);
builder.pos = DVec2::new(0., builder.pos.y + line_height);
}
for (glyph_position, glyph_info) in glyph_buffer.glyph_positions().iter().zip(glyph_buffer.glyph_infos()) {
if let Some(line_width) = line_width {
if builder.pos.x + (glyph_position.x_advance as f64 * builder.scale) >= line_width {
builder.pos = Point::new(0., builder.pos.y + line_height);
builder.pos = DVec2::new(0., builder.pos.y + line_height);
}
}
builder.offset = Vec2::new(glyph_position.x_offset as f64, glyph_position.y_offset as f64) * builder.scale;
builder.offset = DVec2::new(glyph_position.x_offset as f64, glyph_position.y_offset as f64) * builder.scale;
buzz_face.outline_glyph(GlyphId(glyph_info.glyph_id as u16), &mut builder);
builder.pos += Vec2::new(glyph_position.x_advance as f64, glyph_position.y_advance as f64) * builder.scale;
builder.pos += DVec2::new(glyph_position.x_advance as f64, glyph_position.y_advance as f64) * builder.scale;
}
buffer = glyph_buffer.clear();
}
builder.pos = Point::new(0., builder.pos.y + line_height);
builder.pos = DVec2::new(0., builder.pos.y + line_height);
}
builder.path
}

View File

@@ -0,0 +1,50 @@
use std::ops::{Index, IndexMut, Not};
use serde::{Deserialize, Serialize};
#[repr(usize)]
#[derive(PartialEq, Eq, Clone, Debug, Copy, Serialize, Deserialize)]
pub enum ControlPointType {
Anchor = 0,
InHandle = 1,
OutHandle = 2,
}
impl ControlPointType {
pub fn from_index(index: usize) -> ControlPointType {
match index {
0 => ControlPointType::Anchor,
1 => ControlPointType::InHandle,
2 => ControlPointType::OutHandle,
_ => ControlPointType::Anchor,
}
}
}
impl Not for ControlPointType {
type Output = Self;
fn not(self) -> Self::Output {
match self {
ControlPointType::InHandle => ControlPointType::OutHandle,
ControlPointType::OutHandle => ControlPointType::InHandle,
_ => ControlPointType::Anchor,
}
}
}
// Allows us to use ManipulatorType for indexing
impl<T> Index<ControlPointType> for [T; 3] {
type Output = T;
fn index(&self, mt: ControlPointType) -> &T {
&self[mt as usize]
}
}
// Allows us to use ControlPointType for indexing, mutably
impl<T> IndexMut<ControlPointType> for [T; 3] {
fn index_mut(&mut self, mt: ControlPointType) -> &mut T {
&mut self[mt as usize]
}
}
// Remove when no longer needed
pub const SELECTION_THRESHOLD: f64 = 10.;

View File

@@ -0,0 +1,4 @@
pub mod constants;
pub mod vector_anchor;
pub mod vector_control_point;
pub mod vector_shape;

View File

@@ -0,0 +1,301 @@
use super::{
constants::{ControlPointType, SELECTION_THRESHOLD},
vector_control_point::VectorControlPoint,
};
use glam::{DAffine2, DVec2};
use serde::{Deserialize, Serialize};
/// Brief overview of VectorAnchor
/// VectorAnchor <- Container for the anchor metadata and optional VectorControlPoints
/// /
/// [Option<VectorControlPoint>; 3] <- [0] is the anchor's draggable point (but not metadata), [1] is the InHandle's draggable point, [2] is the OutHandle's draggable point
/// / | \
/// "Anchor" "InHandle" "OutHandle" <- These are VectorControlPoints and the only editable "primitive"
/// VectorAnchor is used to represent an anchor point + handles on the path that can be moved.
/// It contains 0-2 handles that are optionally available.
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct VectorAnchor {
// Editable points for the anchor & handles
pub points: [Option<VectorControlPoint>; 3],
#[serde(skip)]
// The editor state of the anchor and handles
pub editor_state: VectorAnchorState,
}
impl VectorAnchor {
/// Create a new anchor with the given position
pub fn new(anchor_pos: DVec2) -> Self {
Self {
// An anchor and 2x None's which represent non-existent handles
points: [Some(VectorControlPoint::new(anchor_pos, ControlPointType::Anchor)), None, None],
editor_state: VectorAnchorState::default(),
}
}
/// Create a new anchor with the given anchor position and handles
pub fn new_with_handles(anchor_pos: DVec2, handle_in_pos: Option<DVec2>, handle_out_pos: Option<DVec2>) -> Self {
Self {
points: match (handle_in_pos, handle_out_pos) {
(Some(pos1), Some(pos2)) => [
Some(VectorControlPoint::new(anchor_pos, ControlPointType::Anchor)),
Some(VectorControlPoint::new(pos1, ControlPointType::InHandle)),
Some(VectorControlPoint::new(pos2, ControlPointType::OutHandle)),
],
(None, Some(pos2)) => [
Some(VectorControlPoint::new(anchor_pos, ControlPointType::Anchor)),
None,
Some(VectorControlPoint::new(pos2, ControlPointType::OutHandle)),
],
(Some(pos1), None) => [
Some(VectorControlPoint::new(anchor_pos, ControlPointType::Anchor)),
Some(VectorControlPoint::new(pos1, ControlPointType::InHandle)),
None,
],
(None, None) => [Some(VectorControlPoint::new(anchor_pos, ControlPointType::Anchor)), None, None],
},
editor_state: VectorAnchorState::default(),
}
}
/// Create a VectorAnchor that represents a close path signal
pub fn closed() -> Self {
Self {
// An anchor being None indicates a ClosePath (aka a path end)
points: [None, None, None],
editor_state: VectorAnchorState::default(),
}
}
/// Does this [VectorAnchor] represent a close signal?
pub fn is_close(&self) -> bool {
self.points[ControlPointType::Anchor].is_none() && self.points[ControlPointType::InHandle].is_none()
}
/// Finds the closest VectorControlPoint owned by this anchor. This can be the handles or the anchor itself
pub fn closest_point(&self, transform_space: &DAffine2, target: glam::DVec2) -> usize {
let mut closest_index: usize = 0;
let mut closest_distance_squared: f64 = f64::MAX; // Not ideal
for (index, point) in self.points.iter().enumerate() {
if let Some(point) = point {
let distance_squared = transform_space.transform_point2(point.position).distance_squared(target);
if distance_squared < closest_distance_squared {
closest_distance_squared = distance_squared;
closest_index = index;
}
}
}
closest_index
}
/// Move the selected points by the provided transform
pub fn move_selected_points(&mut self, delta: DVec2, absolute_position: DVec2, viewspace: &DAffine2) {
let mirror_angle = self.editor_state.mirror_angle_between_handles;
// Invert distance since we want it to start disabled
let mirror_distance = !self.editor_state.mirror_distance_between_handles;
// TODO Use an ID as opposed to distance, stopgap for now
// Transformed into viewspace so SELECTION_THRESHOLD is in pixels
let is_drag_target = |point: &mut VectorControlPoint| -> bool { viewspace.transform_point2(absolute_position).distance(viewspace.transform_point2(point.position)) < SELECTION_THRESHOLD };
// Move the point absolutely or relatively depending on if the point is under the cursor (the last selected point)
let move_point = |point: &mut VectorControlPoint, delta: DVec2, absolute_position: DVec2| {
if is_drag_target(point) {
point.position = absolute_position;
} else {
point.position += delta;
}
assert!(point.position.is_finite(), "Point is not finite")
};
// Find the correctly mirrored handle position based on mirroring settings
let move_symmetrical_handle = |position: DVec2, opposing_handle: Option<&mut VectorControlPoint>, center: DVec2| {
// Early out for cases where we can't mirror
if !mirror_angle || opposing_handle.is_none() {
return;
}
let opposing_handle = opposing_handle.unwrap();
// Keep rotational similarity, but distance variable
let radius = if mirror_distance { center.distance(position) } else { center.distance(opposing_handle.position) };
if let Some(offset) = (position - center).try_normalize() {
opposing_handle.position = center - offset * radius;
assert!(opposing_handle.position.is_finite(), "Oposing handle not finite")
}
};
// If no points are selected, why are we here at all?
if !self.any_points_selected() {
return;
}
// If the anchor is selected ignore any handle mirroring / dragging
// Drag all points
if self.is_anchor_selected() {
for point in self.points_mut() {
move_point(point, delta, absolute_position);
}
return;
}
// If the anchor isn't selected, but both handles are
// Drag only handles
if self.both_handles_selected() {
for point in self.selected_handles_mut() {
move_point(point, delta, absolute_position);
}
return;
}
// If the anchor isn't selected, and only one handle is selected
// Drag the single handle
let reflect_center = self.points[ControlPointType::Anchor].as_ref().unwrap().position;
let selected_handle = self.selected_handles_mut().next().unwrap();
move_point(selected_handle, delta, absolute_position);
// Move the opposing handle symmetrically if our mirroring flags allow
let selected_handle = &selected_handle.clone();
let opposing_handle = self.opposing_handle_mut(selected_handle);
move_symmetrical_handle(selected_handle.position, opposing_handle, reflect_center);
}
/// Delete any VectorControlPoint that are selected, this includes handles or the anchor
pub fn delete_selected(&mut self) {
for point_option in self.points.iter_mut() {
if let Some(point) = point_option {
if point.editor_state.is_selected {
*point_option = None;
}
}
}
}
/// Returns true if any points in this anchor are selected
pub fn any_points_selected(&self) -> bool {
self.points.iter().flatten().any(|pnt| pnt.editor_state.is_selected)
}
/// Returns true if the anchor point is selected
pub fn is_anchor_selected(&self) -> bool {
if let Some(anchor) = &self.points[0] {
anchor.editor_state.is_selected
} else {
false
}
}
/// Determines if two handle points are selected
pub fn both_handles_selected(&self) -> bool {
self.points.iter().skip(1).flatten().filter(|pnt| pnt.editor_state.is_selected).count() == 2
}
/// Set a point to selected by ID
pub fn select_point(&mut self, point_id: usize, selected: bool) -> Option<&mut VectorControlPoint> {
if let Some(point) = self.points[point_id].as_mut() {
point.set_selected(selected);
}
self.points[point_id].as_mut()
}
/// Clear the selected points for this anchor
pub fn clear_selected_points(&mut self) {
for point in self.points.iter_mut().flatten() {
point.set_selected(false);
}
}
/// Provides the points in this anchor
pub fn points(&self) -> impl Iterator<Item = &VectorControlPoint> {
self.points.iter().flatten()
}
/// Provides the points in this anchor
pub fn points_mut(&mut self) -> impl Iterator<Item = &mut VectorControlPoint> {
self.points.iter_mut().flatten()
}
/// Provides the selected points in this anchor
pub fn selected_points(&self) -> impl Iterator<Item = &VectorControlPoint> {
self.points.iter().flatten().filter(|pnt| pnt.editor_state.is_selected)
}
/// Provides mutable selected points in this anchor
pub fn selected_points_mut(&mut self) -> impl Iterator<Item = &mut VectorControlPoint> {
self.points.iter_mut().flatten().filter(|pnt| pnt.editor_state.is_selected)
}
/// Provides the selected handles attached to this anchor
pub fn selected_handles(&self) -> impl Iterator<Item = &VectorControlPoint> {
self.points.iter().skip(1).flatten().filter(|pnt| pnt.editor_state.is_selected)
}
/// Provides the mutable selected handles attached to this anchor
pub fn selected_handles_mut(&mut self) -> impl Iterator<Item = &mut VectorControlPoint> {
self.points.iter_mut().skip(1).flatten().filter(|pnt| pnt.editor_state.is_selected)
}
/// Angle between handles in radians
pub fn angle_between_handles(&self) -> f64 {
if let [Some(a1), Some(h1), Some(h2)] = &self.points {
return (a1.position - h1.position).angle_between(a1.position - h2.position);
}
0.0
}
/// Returns the opposing handle to the handle provided
/// Returns the anchor handle if the anchor is provided
pub fn opposing_handle(&self, handle: &VectorControlPoint) -> Option<&VectorControlPoint> {
self.points[!handle.manipulator_type].as_ref()
}
/// Returns the opposing handle to the handle provided, mutable
/// Returns the anchor handle if the anchor is provided, mutable
pub fn opposing_handle_mut(&mut self, handle: &VectorControlPoint) -> Option<&mut VectorControlPoint> {
self.points[!handle.manipulator_type].as_mut()
}
/// Set the mirroring state
pub fn toggle_mirroring(&mut self, toggle_distance: bool, toggle_angle: bool) {
if toggle_distance {
self.editor_state.mirror_distance_between_handles = !self.editor_state.mirror_distance_between_handles;
}
if toggle_angle {
self.editor_state.mirror_angle_between_handles = !self.editor_state.mirror_angle_between_handles;
}
}
/// Helper function to more easily set position of VectorControlPoints
pub fn set_point_position(&mut self, point_index: usize, position: DVec2) {
assert!(position.is_finite(), "Tried to set_point_position to non finite");
if let Some(point) = &mut self.points[point_index] {
point.position = position;
} else {
self.points[point_index] = Some(VectorControlPoint::new(position, ControlPointType::from_index(point_index)))
}
}
/// Apply an affine transformation the points
pub fn transform(&mut self, transform: &DAffine2) {
for point in self.points_mut() {
point.transform(transform);
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VectorAnchorState {
// If we should maintain the angle between the handles
pub mirror_angle_between_handles: bool,
// If we should make the handles equidistance from the anchor?
pub mirror_distance_between_handles: bool,
}
impl Default for VectorAnchorState {
fn default() -> Self {
Self {
mirror_angle_between_handles: true,
mirror_distance_between_handles: true,
}
}
}

View File

@@ -0,0 +1,76 @@
use super::constants::ControlPointType;
use glam::{DAffine2, DVec2};
use serde::{Deserialize, Serialize};
/// VectorControlPoint represents any editable point, anchor or handle
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub struct VectorControlPoint {
/// The sibling element if this is a handle
pub position: glam::DVec2,
/// The type of manipulator this point is
pub manipulator_type: ControlPointType,
#[serde(skip)]
/// The state specific to the editor
pub editor_state: VectorControlPointState,
}
impl Default for VectorControlPoint {
fn default() -> Self {
Self {
position: DVec2::ZERO,
manipulator_type: ControlPointType::Anchor,
editor_state: VectorControlPointState::default(),
}
}
}
impl VectorControlPoint {
/// Initialize a new control point
pub fn new(position: glam::DVec2, manipulator_type: ControlPointType) -> Self {
assert!(position.is_finite(), "tried to create point with non finite position");
Self {
position,
manipulator_type,
editor_state: VectorControlPointState::default(),
}
}
/// Sets if this point is selected
pub fn set_selected(&mut self, selected: bool) {
self.editor_state.is_selected = selected;
}
pub fn is_selected(&self) -> bool {
self.editor_state.is_selected
}
/// Apply given transform to this point
pub fn transform(&mut self, delta: &DAffine2) {
self.position = delta.transform_point2(self.position);
assert!(self.position.is_finite(), "tried to transform point to non finite position");
}
/// Move by a delta amount
pub fn move_by(&mut self, delta: &DVec2) {
self.position += *delta;
assert!(self.position.is_finite(), "tried to move point to non finite position");
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct VectorControlPointState {
/// If this control point can be selected
pub can_be_selected: bool,
/// Is this control point currently selected
pub is_selected: bool,
}
impl Default for VectorControlPointState {
fn default() -> Self {
Self {
can_be_selected: true,
is_selected: false,
}
}
}

View File

@@ -0,0 +1,529 @@
use super::constants::ControlPointType;
use super::vector_anchor::VectorAnchor;
use super::vector_control_point::VectorControlPoint;
use crate::layers::id_vec::IdBackedVec;
use crate::layers::layer_info::{Layer, LayerDataType};
use glam::{DAffine2, DVec2};
use kurbo::{BezPath, PathEl, Rect, Shape};
use serde::{Deserialize, Serialize};
/// VectorShape represents a single vector shape, containing many anchors
/// For each closed shape we keep a VectorShape which contains the handles and anchors that define that shape.
#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]
pub struct VectorShape(IdBackedVec<VectorAnchor>);
impl VectorShape {
// ** SHAPE INITIALIZATION **
/// Create a new VectorShape with no anchors or handles
pub fn new() -> Self {
VectorShape { ..Default::default() }
}
/// Construct a [VectorShape] from a point iterator
pub fn from_points(points: impl Iterator<Item = DVec2>, closed: bool) -> Self {
let anchors = points.map(VectorAnchor::new);
let mut p_line = VectorShape(IdBackedVec::default());
p_line.0.push_range(anchors);
if closed {
p_line.0.push(VectorAnchor::closed());
}
p_line
}
/// Create a new VectorShape from a kurbo Shape
/// This exists to smooth the transition away from Kurbo
pub fn from_kurbo_shape<T: Shape>(shape: &T) -> Self {
shape.path_elements(0.1).into()
}
// ** PRIMITIVE CONSTRUCTION **
/// constructs a rectangle with `p1` as the lower left and `p2` as the top right
pub fn new_rect(p1: DVec2, p2: DVec2) -> Self {
VectorShape(
vec![
VectorAnchor::new(p1),
VectorAnchor::new(DVec2::new(p1.x, p2.y)),
VectorAnchor::new(p2),
VectorAnchor::new(DVec2::new(p2.x, p1.y)),
VectorAnchor::closed(),
]
.into_iter()
.collect(),
)
}
pub fn new_ellipse(p1: DVec2, p2: DVec2) -> Self {
let x_height = DVec2::new((p2.x - p1.x).abs(), 0.);
let y_height = DVec2::new(0., (p2.y - p1.y).abs());
let center = (p1 + p2) * 0.5;
let top = center + y_height * 0.5;
let bottom = center - y_height * 0.5;
let left = center + x_height * 0.5;
let right = center - x_height * 0.5;
// Constant explained here https://stackoverflow.com/a/27863181
let curve_constant = 0.55228_3;
let handle_offset_x = x_height * curve_constant * 0.5;
let handle_offset_y = y_height * curve_constant * 0.5;
VectorShape(
vec![
VectorAnchor::new_with_handles(top, Some(top + handle_offset_x), Some(top - handle_offset_x)),
VectorAnchor::new_with_handles(right, Some(right + handle_offset_y), Some(right - handle_offset_y)),
VectorAnchor::new_with_handles(bottom, Some(bottom - handle_offset_x), Some(bottom + handle_offset_x)),
VectorAnchor::new_with_handles(left, Some(left - handle_offset_y), Some(left + handle_offset_y)),
VectorAnchor::closed(),
]
.into_iter()
.collect(),
)
}
/// constructs an ngon
/// `radius` is the distance from the `center` to any vertex, or the radius of the circle the ngon may be inscribed inside
/// `sides` is the number of sides
pub fn new_ngon(center: DVec2, sides: u64, radius: f64) -> Self {
let mut anchors = vec![];
for i in 0..sides {
let angle = (i as f64) * std::f64::consts::TAU / (sides as f64);
let center = center + DVec2::ONE * radius;
let position = VectorAnchor::new(DVec2::new(center.x + radius * f64::cos(angle), center.y + radius * f64::sin(angle)) * 0.5);
anchors.push(position);
}
anchors.push(VectorAnchor::closed());
VectorShape(anchors.into_iter().collect())
}
/// Constructs a line from `p1` to `p2`
pub fn new_line(p1: DVec2, p2: DVec2) -> Self {
VectorShape(vec![VectorAnchor::new(p1), VectorAnchor::new(p2)].into_iter().collect())
}
/// Constructs a set of lines from `p1` to `pN`
pub fn new_poly_line<T: Into<glam::DVec2>>(points: Vec<T>) -> Self {
let anchors = points.into_iter().map(|point| VectorAnchor::new(point.into()));
let mut p_line = VectorShape(IdBackedVec::default());
p_line.0.push_range(anchors);
p_line
}
pub fn new_spline<T: Into<glam::DVec2>>(points: Vec<T>) -> Self {
let mut new = Self::default();
// shadow `points`
let points: Vec<DVec2> = points.into_iter().map(Into::<glam::DVec2>::into).collect();
// Number of points = number of points to find handles for
let n = points.len();
// matrix coefficients a, b and c (see https://mathworld.wolfram.com/CubicSpline.html)
// because the 'a' coefficients are all 1 they need not be stored
// this algorithm does a variation of the above algorithm.
// Instead of using the traditional cubic: a + bt + ct^2 + dt^3, we use the bezier cubic.
let mut b = vec![DVec2::new(4.0, 4.0); n];
b[0] = DVec2::new(2.0, 2.0);
b[n - 1] = DVec2::new(2.0, 2.0);
let mut c = vec![DVec2::new(1.0, 1.0); n];
// 'd' is the the second point in a cubic bezier, which is what we solve for
let mut d = vec![DVec2::ZERO; n];
d[0] = DVec2::new(2.0 * points[1].x + points[0].x, 2.0 * points[1].y + points[0].y);
d[n - 1] = DVec2::new(3.0 * points[n - 1].x, 3.0 * points[n - 1].y);
for idx in 1..(n - 1) {
d[idx] = DVec2::new(4.0 * points[idx].x + 2.0 * points[idx + 1].x, 4.0 * points[idx].y + 2.0 * points[idx + 1].y);
}
// Solve with Thomas algorithm (see https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm)
// do row operations to eliminate `a` coefficients
c[0] /= -b[0];
d[0] /= -b[0];
for i in 1..n {
b[i] += c[i - 1];
// for some reason the below line makes the borrow checker mad
//d[i] += d[i-1]
d[i] = d[i] + d[i - 1];
c[i] /= -b[i];
d[i] /= -b[i];
}
// at this point b[i] == -a[i + 1], a[i] == 0,
// do row operations to eliminate 'c' coefficients and solve
d[n - 1] *= -1.0;
for i in (0..n - 1).rev() {
d[i] = d[i] - (c[i] * d[i + 1]);
d[i] *= -1.0; //d[i] /= b[i]
}
// given the second point in the n'th cubic bezier, the third point is given by 2 * points[n+1] - b[n+1].
// to find 'handle1_pos' for the n'th point we need the n-1 cubic bezier
new.0.push_end(VectorAnchor::new_with_handles(points[0], None, Some(d[0])));
for i in 1..n - 1 {
new.0.push_end(VectorAnchor::new_with_handles(points[i], Some(2.0 * points[i] - d[i]), Some(d[i])));
}
new.0.push_end(VectorAnchor::new_with_handles(points[n - 1], Some(2.0 * points[n - 1] - d[n - 1]), None));
new
}
/// Move the selected points by the delta vector
pub fn move_selected(&mut self, delta: DVec2, absolute_position: DVec2, viewspace: &DAffine2) {
self.selected_anchors_any_points_mut()
.for_each(|anchor| anchor.move_selected_points(delta, absolute_position, viewspace));
}
/// Delete the selected points from the VectorShape
pub fn delete_selected(&mut self) {
let mut ids_to_delete: Vec<u64> = vec![];
for (id, anchor) in self.anchors_mut().enumerate_mut() {
if anchor.is_anchor_selected() {
ids_to_delete.push(*id);
} else {
anchor.delete_selected();
}
}
for id in ids_to_delete {
self.anchors_mut().remove(id);
}
}
// Apply a transformation to all of the VectorShape points
pub fn apply_affine(&mut self, affine: DAffine2) {
for anchor in self.anchors_mut().iter_mut() {
anchor.transform(&affine);
}
}
// ** SELECTION OF POINTS **
/// Select a single point by providing (AnchorId, ControlPointType)
pub fn select_point(&mut self, point: (u64, ControlPointType), selected: bool) -> Option<&mut VectorAnchor> {
let (anchor_id, point_id) = point;
if let Some(anchor) = self.anchors_mut().by_id_mut(anchor_id) {
anchor.select_point(point_id as usize, selected);
return Some(anchor);
}
None
}
/// Select points in the VectorShape, given by (AnchorId, ControlPointType)
pub fn select_points(&mut self, points: &[(u64, ControlPointType)], selected: bool) {
points.iter().for_each(|point| {
self.select_point(*point, selected);
});
}
/// Select all the anchors in this shape
pub fn select_all_anchors(&mut self) {
for anchor in self.anchors_mut().iter_mut() {
anchor.select_point(ControlPointType::Anchor as usize, true);
}
}
/// Select an anchor by index
pub fn select_anchor_by_index(&mut self, anchor_index: usize) -> Option<&mut VectorAnchor> {
if let Some(anchor) = self.anchors_mut().by_index_mut(anchor_index) {
anchor.select_point(ControlPointType::Anchor as usize, true);
return Some(anchor);
}
None
}
/// The last anchor in the shape
pub fn select_last_anchor(&mut self) -> Option<&mut VectorAnchor> {
if let Some(anchor) = self.anchors_mut().last_mut() {
anchor.select_point(ControlPointType::Anchor as usize, true);
return Some(anchor);
}
None
}
/// Clear all the selected anchors, and clear the selected points on the anchors
pub fn clear_selected_anchors(&mut self) {
for anchor in self.anchors_mut().iter_mut() {
anchor.clear_selected_points();
}
}
// ** ACCESSING ANCHORS **
/// Return all the selected anchors, reference
pub fn selected_anchors(&self) -> impl Iterator<Item = &VectorAnchor> {
self.anchors().iter().filter(|anchor| anchor.is_anchor_selected())
}
/// Return all the selected anchors, mutable
pub fn selected_anchors_mut(&mut self) -> impl Iterator<Item = &mut VectorAnchor> {
self.anchors_mut().iter_mut().filter(|anchor| anchor.is_anchor_selected())
}
/// Return all the selected anchors that have any children points selected, reference
pub fn selected_anchors_any_points(&self) -> impl Iterator<Item = &VectorAnchor> {
self.anchors().iter().filter(|anchor| anchor.any_points_selected())
}
/// Return all the selected anchors that have any children points selected, mutable
pub fn selected_anchors_any_points_mut(&mut self) -> impl Iterator<Item = &mut VectorAnchor> {
self.anchors_mut().iter_mut().filter(|anchor| anchor.any_points_selected())
}
/// An alias for `self.0`
pub fn anchors(&self) -> &IdBackedVec<VectorAnchor> {
&self.0
}
/// Returns a [VectorControlPoint] from the last [VectorAnchor]
pub fn last_point(&self, control_type: ControlPointType) -> Option<&VectorControlPoint> {
self.anchors().last().and_then(|anchor| anchor.points[control_type].as_ref())
}
/// Returns a [VectorControlPoint] from the last [VectorAnchor], mutably
pub fn last_point_mut(&mut self, control_type: ControlPointType) -> Option<&mut VectorControlPoint> {
self.anchors_mut().last_mut().and_then(|anchor| anchor.points[control_type].as_mut())
}
/// Returns a [VectorControlPoint] from the first [VectorAnchor]
pub fn first_point(&self, control_type: ControlPointType) -> Option<&VectorControlPoint> {
self.anchors().first().and_then(|anchor| anchor.points[control_type].as_ref())
}
/// Returns a [VectorControlPoint] from the first [VectorAnchor]
pub fn first_point_mut(&mut self, control_type: ControlPointType) -> Option<&mut VectorControlPoint> {
self.anchors_mut().first_mut().and_then(|anchor| anchor.points[control_type].as_mut())
}
/// Should we close the shape?
pub fn should_close_shape(&self) -> bool {
if self.last_point(ControlPointType::Anchor).is_none() {
return false;
}
self.first_point(ControlPointType::Anchor)
.unwrap()
.position
.distance(self.last_point(ControlPointType::Anchor).unwrap().position)
< 0.001 // TODO Replace with constant, a small epsilon
}
/// Close the shape if able
pub fn close_shape(&mut self) {
if self.should_close_shape() {
self.anchors_mut().push_end(VectorAnchor::closed());
}
}
/// An alias for `self.0` mutable
pub fn anchors_mut(&mut self) -> &mut IdBackedVec<VectorAnchor> {
&mut self.0
}
// ** INTERFACE WITH KURBO **
// TODO Implement our own a local bounding box calculation
/// Return the bounding box of the shape
pub fn bounding_box(&self) -> Rect {
<&Self as Into<BezPath>>::into(self).bounding_box()
}
/// Use kurbo to convert this shape into an SVG path
pub fn to_svg(&mut self) -> String {
fn write_positions(result: &mut String, values: [Option<DVec2>; 3]) {
use std::fmt::Write;
let count = values.into_iter().flatten().count();
for (index, pos) in values.into_iter().flatten().enumerate() {
write!(result, "{},{}", pos.x, pos.y).unwrap();
if index != count - 1 {
result.push(' ');
}
}
}
let mut result = String::new();
// The out position from the previous VectorAnchor
let mut last_out_handle = None;
// The values from the last moveto (for closing the path)
let (mut first_in_handle, mut first_in_anchor) = (None, None);
// Should the next element be a moveto?
let mut start_new_contour = true;
for vector_anchor in self.anchors().iter() {
let in_handle = vector_anchor.points[ControlPointType::InHandle].as_ref().map(|anchor| anchor.position);
let anchor = vector_anchor.points[ControlPointType::Anchor].as_ref().map(|anchor| anchor.position);
let out_handle = vector_anchor.points[ControlPointType::OutHandle].as_ref().map(|anchor| anchor.position);
let command = match (last_out_handle.is_some(), in_handle.is_some(), anchor.is_some()) {
(_, _, true) if start_new_contour => 'M',
(true, false, true) | (false, true, true) => 'Q',
(true, true, true) => 'C',
(false, false, true) => 'L',
(_, false, false) => 'Z',
_ => panic!("Invalid shape {:#?}", self),
};
// Complete the last curve
if command == 'Z' {
if last_out_handle.is_some() && first_in_handle.is_some() {
result.push('C');
write_positions(&mut result, [last_out_handle, first_in_handle, first_in_anchor]);
} else if last_out_handle.is_some() || first_in_handle.is_some() {
result.push('Q');
write_positions(&mut result, [last_out_handle, first_in_handle, first_in_anchor]);
} else {
result.push('Z');
}
} else if command == 'M' {
// Update the last moveto position
(first_in_handle, first_in_anchor) = (in_handle, anchor);
result.push(command);
write_positions(&mut result, [None, None, anchor]);
} else {
result.push(command);
write_positions(&mut result, [last_out_handle, in_handle, anchor]);
}
start_new_contour = command == 'Z';
last_out_handle = out_handle;
}
result
}
}
// ** CONVERSIONS **
/// Convert a mutable layer into a mutable VectorShape
impl<'a> TryFrom<&'a mut Layer> for &'a mut VectorShape {
type Error = &'static str;
fn try_from(layer: &'a mut Layer) -> Result<&'a mut VectorShape, Self::Error> {
match &mut layer.data {
LayerDataType::Shape(layer) => Ok(&mut layer.shape),
// TODO Resolve converting text into a VectorShape at the layer level
// LayerDataType::Text(text) => Some(VectorShape::new(path_to_shape.to_vec(), viewport_transform, true)),
_ => Err("Did not find any shape data in the layer"),
}
}
}
/// Convert a reference to a layer into a reference of a VectorShape
impl<'a> TryFrom<&'a Layer> for &'a VectorShape {
type Error = &'static str;
fn try_from(layer: &'a Layer) -> Result<&'a VectorShape, Self::Error> {
match &layer.data {
LayerDataType::Shape(layer) => Ok(&layer.shape),
// TODO Resolve converting text into a VectorShape at the layer level
// LayerDataType::Text(text) => Some(VectorShape::new(path_to_shape.to_vec(), viewport_transform, true)),
_ => Err("Did not find any shape data in the layer"),
}
}
}
/// Create a BezPath from a VectorShape
impl From<&VectorShape> for BezPath {
fn from(vector_shape: &VectorShape) -> Self {
// Take anchors and create path elements: line, quad or curve, or a close indicator
let anchors_to_path_el = |first: &VectorAnchor, second: &VectorAnchor| -> (PathEl, bool) {
match [
&first.points[ControlPointType::OutHandle],
&second.points[ControlPointType::InHandle],
&second.points[ControlPointType::Anchor],
] {
[None, None, Some(anchor)] => (PathEl::LineTo(point_to_kurbo(anchor)), false),
[None, Some(in_handle), Some(anchor)] => (PathEl::QuadTo(point_to_kurbo(in_handle), point_to_kurbo(anchor)), false),
[Some(out_handle), None, Some(anchor)] => (PathEl::QuadTo(point_to_kurbo(out_handle), point_to_kurbo(anchor)), false),
[Some(out_handle), Some(in_handle), Some(anchor)] => (PathEl::CurveTo(point_to_kurbo(out_handle), point_to_kurbo(in_handle), point_to_kurbo(anchor)), false),
[Some(out_handle), None, None] => {
if let Some(first_anchor) = vector_shape.anchors().first() {
(
if let Some(in_handle) = &first_anchor.points[ControlPointType::InHandle] {
PathEl::CurveTo(
point_to_kurbo(out_handle),
point_to_kurbo(in_handle),
point_to_kurbo(first_anchor.points[ControlPointType::Anchor].as_ref().unwrap()),
)
} else {
PathEl::QuadTo(point_to_kurbo(out_handle), point_to_kurbo(first_anchor.points[ControlPointType::Anchor].as_ref().unwrap()))
},
true,
)
} else {
(PathEl::ClosePath, true)
}
}
[None, None, None] => (PathEl::ClosePath, true),
_ => panic!("Invalid path element {:#?}", vector_shape),
}
};
if vector_shape.anchors().is_empty() {
return BezPath::new();
}
let mut bez_path = vec![];
let mut start_new_shape = true;
for elements in vector_shape.anchors().windows(2) {
let first = &elements[0];
let second = &elements[1];
// Tell kurbo cursor to move to the first anchor
if start_new_shape {
if let Some(anchor) = &first.points[ControlPointType::Anchor] {
bez_path.push(PathEl::MoveTo(point_to_kurbo(anchor)));
}
}
// Create a path element from our first, second anchors in the window
let (path_el, should_start_new_shape) = anchors_to_path_el(first, second);
start_new_shape = should_start_new_shape;
bez_path.push(path_el);
if should_start_new_shape && bez_path.last().filter(|&&el| el == PathEl::ClosePath).is_none() {
bez_path.push(PathEl::ClosePath)
}
}
BezPath::from_vec(bez_path)
}
}
/// Create a VectorShape from a BezPath
impl<T: Iterator<Item = PathEl>> From<T> for VectorShape {
fn from(path: T) -> Self {
let mut vector_shape = VectorShape::new();
for path_el in path {
match path_el {
PathEl::MoveTo(p) => {
vector_shape.anchors_mut().push_end(VectorAnchor::new(kurbo_point_to_dvec2(p)));
}
PathEl::LineTo(p) => {
vector_shape.anchors_mut().push_end(VectorAnchor::new(kurbo_point_to_dvec2(p)));
}
PathEl::QuadTo(p0, p1) => {
vector_shape.anchors_mut().push_end(VectorAnchor::new(kurbo_point_to_dvec2(p1)));
vector_shape.anchors_mut().last_mut().unwrap().points[ControlPointType::InHandle] = Some(VectorControlPoint::new(kurbo_point_to_dvec2(p0), ControlPointType::InHandle));
}
PathEl::CurveTo(p0, p1, p2) => {
vector_shape.anchors_mut().last_mut().unwrap().points[ControlPointType::OutHandle] = Some(VectorControlPoint::new(kurbo_point_to_dvec2(p0), ControlPointType::OutHandle));
vector_shape.anchors_mut().push_end(VectorAnchor::new(kurbo_point_to_dvec2(p2)));
vector_shape.anchors_mut().last_mut().unwrap().points[ControlPointType::InHandle] = Some(VectorControlPoint::new(kurbo_point_to_dvec2(p1), ControlPointType::InHandle));
}
PathEl::ClosePath => {
vector_shape.anchors_mut().push_end(VectorAnchor::closed());
}
}
}
vector_shape
}
}
#[inline]
fn point_to_kurbo(point: &VectorControlPoint) -> kurbo::Point {
kurbo::Point::new(point.position.x, point.position.y)
}
#[inline]
fn kurbo_point_to_dvec2(point: kurbo::Point) -> DVec2 {
DVec2::new(point.x, point.y)
}

View File

@@ -2,6 +2,9 @@ use crate::boolean_ops::BooleanOperation as BooleanOperationType;
use crate::layers::blend_mode::BlendMode;
use crate::layers::layer_info::Layer;
use crate::layers::style::{self, Stroke};
use crate::layers::vector::constants::ControlPointType;
use crate::layers::vector::vector_anchor::VectorAnchor;
use crate::layers::vector::vector_shape::VectorShape;
use crate::LayerId;
use serde::{Deserialize, Serialize};
@@ -19,33 +22,18 @@ pub enum Operation {
transform: [f64; 6],
style: style::PathStyle,
},
AddOverlayEllipse {
path: Vec<LayerId>,
transform: [f64; 6],
style: style::PathStyle,
},
AddRect {
path: Vec<LayerId>,
insert_index: isize,
transform: [f64; 6],
style: style::PathStyle,
},
AddOverlayRect {
path: Vec<LayerId>,
transform: [f64; 6],
style: style::PathStyle,
},
AddLine {
path: Vec<LayerId>,
insert_index: isize,
transform: [f64; 6],
style: style::PathStyle,
},
AddOverlayLine {
path: Vec<LayerId>,
transform: [f64; 6],
style: style::PathStyle,
},
AddText {
path: Vec<LayerId>,
transform: [f64; 6],
@@ -97,19 +85,12 @@ pub enum Operation {
sides: u32,
style: style::PathStyle,
},
AddOverlayShape {
path: Vec<LayerId>,
bez_path: kurbo::BezPath,
style: style::PathStyle,
closed: bool,
},
AddShape {
path: Vec<LayerId>,
transform: [f64; 6],
insert_index: isize,
bez_path: kurbo::BezPath,
vector_path: VectorShape,
style: style::PathStyle,
closed: bool,
},
BooleanOperation {
operation: BooleanOperationType,
@@ -118,6 +99,16 @@ pub enum Operation {
DeleteLayer {
path: Vec<LayerId>,
},
DeleteSelectedVectorPoints {
layer_paths: Vec<Vec<LayerId>>,
},
DeselectVectorPoints {
layer_path: Vec<LayerId>,
point_ids: Vec<(u64, ControlPointType)>,
},
DeselectAllVectorPoints {
layer_path: Vec<LayerId>,
},
DuplicateLayer {
path: Vec<LayerId>,
},
@@ -127,6 +118,11 @@ pub enum Operation {
font_style: String,
size: f64,
},
MoveSelectedVectorPoints {
layer_path: Vec<LayerId>,
delta: (f64, f64),
absolute_position: (f64, f64),
},
RenameLayer {
layer_path: Vec<LayerId>,
new_name: String,
@@ -151,14 +147,38 @@ pub enum Operation {
path: Vec<LayerId>,
transform: [f64; 6],
},
SelectVectorPoints {
layer_path: Vec<LayerId>,
point_ids: Vec<(u64, ControlPointType)>,
add: bool,
},
SetShapePath {
path: Vec<LayerId>,
bez_path: kurbo::BezPath,
vector_path: VectorShape,
},
SetShapePathInViewport {
path: Vec<LayerId>,
bez_path: kurbo::BezPath,
transform: [f64; 6],
InsertVectorAnchor {
layer_path: Vec<LayerId>,
anchor: VectorAnchor,
after_id: u64,
},
PushVectorAnchor {
layer_path: Vec<LayerId>,
anchor: VectorAnchor,
},
RemoveVectorAnchor {
layer_path: Vec<LayerId>,
id: u64,
},
MoveVectorPoint {
layer_path: Vec<LayerId>,
id: u64,
control_type: ControlPointType,
position: (f64, f64),
},
RemoveVectorPoint {
layer_path: Vec<LayerId>,
id: u64,
control_type: ControlPointType,
},
TransformLayerInScope {
path: Vec<LayerId>,
@@ -205,6 +225,11 @@ pub enum Operation {
path: Vec<LayerId>,
stroke: Stroke,
},
SetSelectedHandleMirroring {
layer_path: Vec<LayerId>,
toggle_distance: bool,
toggle_angle: bool,
},
}
impl Operation {