mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-24 13:58:12 +08:00
Shape boolean operation improvements (#547)
* changed path_intersection structure
* comment
* Removed do_if!
* Create project website with near-complete home page
* Added support for undoing
- i gotta say the undo system is quite nice
* Website responsive resizing improvements
* Add newsletter signup to website
* Pen tool fixes (#563)
Resolves 3 known bugs with the pen tool.
* Fixed crash pointed out by @caleb-ad
* Fixed issue with final path segment losing handle data
* Replace curves with lines when under a drag threshold, improves usability.
* Readability improvements, improved comments
* Color Input (#565)
* initial working prototype
* clean up component
* Fix alignment
* Code review tweaks
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Made the non-inclusive end of a pathseg less inclusive
Fixed Bug: When doing a closepath it is possible that the current and beginning edge are both None
Fixed Numerous other things
* changed how closepath works
modified how overlapping_curve_intersections is working
* Add "New Folder"/"Delete Selected" buttons to layer panel
Closes #532
* Update npm dependencies
* Set text color based on its fill when it's being edited
* Reorder tool icons, update favicon and logo, and other icon cleanup
* Bug Fix: Line-Line intersect origin wasn't being preserved
* Bug Fix: proper assignment of t_values in overlapping_curve_intersections
* Honestly, i don't even know what I was thinking when i wrote the logic for splitting a subcurve at endpoints, but it was wrong.
* Feature: overlapping rectangles behave properly, (except when intersections aren't found correctly)
* Remake node type icons (closes #483); color picker cleanup
* Change tool shelf icon colors to use classes not style
* Add Image node icon and rename node from Path to Shape
* Bug Fix: proper intersection construction in partial overlap case
* cleaned up log statements
* Add website revisions and many new pages
* Add features page and fixes to website
* Fix clippy lints and update packages (#568)
* Fix type error in Brave browser (#569)
* Small website text improvements
* Various website fixes
* Adjusted constants
Rearranged intersection algorithm
* Changed BooleanOperation::SubtractBack to use SubtractFront
Added composite_boolean_operation for operations with more than one shape
* Add node graph mockup to website
* Differentiate between scale and dimensions (#570)
* Differentiate between scale and dimensions
* Fix layout and naming of properties
* Add embedable images (#564)
* Add embedable bitmaps
* Initial work on blob urls
* Finish implementing data url
* Fix some bugs
* Rename bitmap to image
* Fix loading image on document load
* Add transform properties for image
* Remove some logging
* Add image dimensions
* Implement system copy and paste
* Fix pasting images
* Fix test
* Address code review
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Bump minimist from 1.2.5 to 1.2.6 in /frontend (#571)
Bumps [minimist](https://github.com/substack/minimist) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.5...1.2.6)
---
updated-dependencies:
- dependency-name: minimist
dependency-type: indirect
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Fix panic dialogue when handling a message (#573)
* Fix panic dialogue when handling a message
* Fix indents for github reporting
* More whitespace improvements
* Save: line_intersection
* Add documentation to many parts of the Rust codebase (#552)
* add lots of doccomments
* add conversion traits from layerdatatypes to layers
* add suggested doc improvements
* Code review changes
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Add additional stroke properties (#582)
* Add aditional stroke properties
* Add comment explaining clones for closure
* Improve labels
* Fix doc test
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Bug Fix: .y not .x
* Expand upon the "Announcing Graphite alpha" blog post
* All shapes now have a Fill in the properties panel; color inputs are now optional (#583)
* Add aditional stroke properties
* Make the colour input optional
* Fix fmt
* Apply code review changes
* Code review nitpicks
* Fix recursion
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* New blog post: "Distributed computing with the Graphene runtime"
* Fix gradient transformation (#588)
* Fix with perfect circle
* Actually fix rotated gradient
* Gradient transform & fix on rotated canvas
* Cleanup & remove logging
* Add properties panel entries for artboards (#572)
* Artboards can have properties
* fix crash when renaming artboards
* moved target document to utility types
* moved import and added test for file version information
* fixed missing import
* fix error from merging
* - typed properties message handler data
- removed name from WidgetRow
* clippy warnings
* artboards have seperate properties section
* - color input can be forced to have selection
- crop tool shows on switch
- select tool shows on switch
* variable renamed
* change to use PropType<boolean> instead of PropType<Boolean>
* Add an artboard icon
* Add the "Delete Artboard" hint
* fix unselect glitch
* even better
* Remove the Transform properties group
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Bug Fix: boolean union on multiple shapes
* Font selection for text layers (#585)
* Add font dropdown
* Add fonts
* Font tool options
* Fix tests
* Replace http with https
* Add variant selection
* Do not embed default font
* Use proxied font list API
* Change default font to Merriweather
* Remove outdated comment
* Specify font once & load font into foreignobject
* Fix tests
* Rename variant to font_style
* Change TextAreaInput to use FieldInput (WIP, breaks functionality)
* Fix textarea functionality
* Fix types
* Add weight name mapping
* Change labeling of "Italic"
* Remove commented HTML node
* Rename font "name" to "font_family" and "file" "font_file"
* Fix errors
* Fix fmt
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Improvements to the layer transform cage UX (#589)
* Allow input system to handle mousedown while dragging
* Fix abort
* Add apsect ratio
* Make comment more explicit
* Fix abort when dragging
* Constrain when dragging edge
* Rename Crop tool to Artboard tool
* Stop pointerdown event from properties panel (#600)
* Change stroke weight from ints to floats (#601)
Also rename stroke "width" to "weight" in some places. Closes #587
* Change stroke weight from ints to floats
* "miter_limit" -> "line_join_miter_limit"
* Bump file format version
* cargo update
Prevent iterating beyond list bounds
* Bug fix: proper composite intersection behavior
* fix warnings
* Improved ray casting and common intersection cases
Finding intersections near path segment endpoints was previously unreliable
because of imprecision, and the necessity of avoiding double counting any
intersections. And, because of snapping, intersections on the endpoints
of path segments are a common case.
This also improved the ray casting use case, which previously used a "fudge factor"
to mitigate the common problem of casting a ray into line endpoints.
* fixed warnings
* Fix properties deselect (#606)
* Fix properties panel deselect
* Fix arrow cursors on select tool
* Fix drag from UI to document causing mouse down
* Fix tests
* Cleanup
* cleanup messages
* Draw the outlines of shapes on hover and selection (#609)
* Add hover outline overlay
* Increase selection tolerance
* Increase weight
* Only check if top intersection is selected
* Outline selected paths
* Reduce outline weight
* Increase path tool outline thickness to match hover
* Update to use unreachable! instead of panic!
* Upgrade vue-cli to version 5 (#594)
* Upgrade to Vue CLI 5 (fails to compile)
* Upgrade versions with last few weeks of changes
* Updated to fork-ts-checker-webpack-plugin 7.2.3
* Remove package.json overrides in lieu of the fixed fork-ts-checker-webpack-plugin@6.5.1
* Fix svg importing
* Comments
* For debugging only: added infrastructureLogging to vue.config.js
* Now works on Windows, waiting on fork-ts-checker-webpack-plugin backport if possible
* Switch to the fixed fork-ts-checker-webpack-plugin@6.5.2
* Fix license checker build compilation
Co-authored-by: 0hypercube <0hypercube@gmail.com>
* Tidy up the full frontend codebase and use optional chaining where possible (#620)
* Tidy up the full frontend codebase and use optional chaining where possible
* Code review changes
* Add a hotkey to select a random primary color (#622)
* Add shortcut to select a random primary color (#549)
* Rename random primary color message and reduce the number of calls to
generate_uuid
* Add documentation for SelectRandomPrimaryColor message
* Set the alpha value to 255 instead of a random value #622
Co-authored-by: Florent Collin <florentcollin23@gmail.com>
* Move the Layer Tree panel's New Folder and Delete icons into the options bar
* Migrate dialogs to Rust and add a New File dialog (#623)
* Migrate coming soon and about dialog to Rust
* Migrate confirm close and close all
* Migrate dialog error
* Improve keyboard navigation throughout UI
* Cleanup and fix panic dialog
* Reduce css spacing to better match old dialogs
* Add new document modal
* Fix crash when generating default name
* Populate rust about graphite data on startup
* Code review changes
* Move one more :focus CSS rule into App.vue
* Add a dialog message and move dialogs
* Split out keyboard input navigation from this branch
* Improvements including simplifying panic dialog code
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Snapping system improvements and refactor (#621)
* Snap to points and refactor
* Improve dot position on bounds
* Add snap matrix
* Cleanup
* Code review
* Half axis fade rather than increase it
* Fix fmt
* Hide snap to point overlay when active
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Add the File > Export dialog and PNG/JPG downloading (#629)
* Add export dialog
* Code review changes
* More code review feedback
* Fix compilation on stable Rust
* Fixes to problems
Co-authored-by: Keavon Chambers <keavon@keavon.com>
* Code review
Co-authored-by: Keavon Chambers <keavon@keavon.com>
Co-authored-by: Oliver Davies <oliver@psyfer.io>
Co-authored-by: mfish33 <32677537+mfish33@users.noreply.github.com>
Co-authored-by: 0HyperCube <78500760+0HyperCube@users.noreply.github.com>
Co-authored-by: TrueDoctor <dennis@kobert.dev>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Alaska <simon.wuelker@arcor.de>
Co-authored-by: 0hypercube <0hypercube@gmail.com>
Co-authored-by: FlorentCollin <florentcollinpro@gmail.com>
Co-authored-by: Florent Collin <florentcollin23@gmail.com>
This commit is contained in:
committed by
Keavon Chambers
co-authored by
Florent Collin
Keavon Chambers
Oliver Davies
mfish33
0HyperCube
TrueDoctor
dependabot[bot]
Alaska
0hypercube
FlorentCollin
parent
8dec73c344
commit
bd997cef60
+139
-79
@@ -1,11 +1,13 @@
|
||||
use crate::consts::{F64PRECISE, RAY_FUDGE_FACTOR};
|
||||
use crate::consts::F64PRECISE;
|
||||
use crate::intersection::{intersections, line_curve_intersections, valid_t, Intersect, Origin};
|
||||
use crate::layers::shape_layer::ShapeLayer;
|
||||
use crate::layers::style::PathStyle;
|
||||
|
||||
use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveExtrema, PathEl, PathSeg, Point, QuadBez, Rect};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cell::RefCell;
|
||||
use std::fmt::{self, Debug, Formatter};
|
||||
use std::mem::swap;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq)]
|
||||
pub enum BooleanOperation {
|
||||
@@ -26,15 +28,6 @@ pub enum BooleanOperationError {
|
||||
Unexpected, // For debugging, when complete nothing should be unexpected
|
||||
}
|
||||
|
||||
/// A simple and idiomatic way to write short "if let Some(_)" statements which do nothing in the None case
|
||||
macro_rules! do_if {
|
||||
($option:expr, $name:ident{$todo:expr}) => {
|
||||
if let Some($name) = $option {
|
||||
$todo
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
struct Edge {
|
||||
pub from: Origin,
|
||||
pub destination: usize,
|
||||
@@ -55,7 +48,17 @@ struct Vertex {
|
||||
|
||||
impl Debug for Vertex {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(format!("\n Intersect@ {:?}", self.intersect.point).as_str())?;
|
||||
f.write_str(
|
||||
format!(
|
||||
"\n Intersect Point: {:?} Segment index of A: {:?}, Segment index of B: {:?} t value of A: {:?} t value of B: {:?}",
|
||||
self.intersect.point,
|
||||
self.intersect.segment_index(Origin::Alpha),
|
||||
self.intersect.segment_index(Origin::Beta),
|
||||
self.intersect.t_value(Origin::Alpha),
|
||||
self.intersect.t_value(Origin::Beta),
|
||||
)
|
||||
.as_str(),
|
||||
)?;
|
||||
f.debug_list().entries(self.edges.iter()).finish()
|
||||
}
|
||||
}
|
||||
@@ -158,7 +161,6 @@ struct PathGraph {
|
||||
/// Has somewhat (totally?) undefined behavior when shapes have self intersections.
|
||||
impl PathGraph {
|
||||
pub fn from_paths(alpha: &BezPath, beta: &BezPath) -> Result<PathGraph, BooleanOperationError> {
|
||||
// TODO: check for closed paths somewhere, maybe here?
|
||||
let mut new = PathGraph {
|
||||
vertices: intersections(alpha, beta).into_iter().map(|i| Vertex { intersect: i, edges: Vec::new() }).collect(),
|
||||
};
|
||||
@@ -219,7 +221,7 @@ impl PathGraph {
|
||||
for (vertex_id, sub_seg) in vertex_ids.into_iter().zip(subdivided.iter()) {
|
||||
match self.current_start {
|
||||
Some(index) => {
|
||||
do_if!(sub_seg, end_of_edge { self.current.push(*end_of_edge)});
|
||||
sub_seg.map(|end_of_edge| self.current.push(end_of_edge));
|
||||
graph.add_edge(origin, index, vertex_id, self.current.clone());
|
||||
self.current_start = Some(vertex_id);
|
||||
self.current = Vec::new();
|
||||
@@ -227,11 +229,11 @@ impl PathGraph {
|
||||
None => {
|
||||
self.current_start = Some(vertex_id);
|
||||
self.start_index = Some(vertex_id);
|
||||
do_if!(sub_seg, end_of_beginning {self.beginning.push(*end_of_beginning)});
|
||||
sub_seg.map(|end_of_beginning| self.beginning.push(end_of_beginning));
|
||||
}
|
||||
}
|
||||
}
|
||||
do_if!(subdivided.last().unwrap(), start_of_edge {self.current.push(*start_of_edge)});
|
||||
subdivided.last().unwrap().map(|start_of_edge| self.current.push(start_of_edge));
|
||||
} else {
|
||||
match self.current_start {
|
||||
Some(_) => self.current.push(seg),
|
||||
@@ -242,28 +244,44 @@ impl PathGraph {
|
||||
}
|
||||
|
||||
fn advance_by_closepath(&mut self, graph: &mut PathGraph, initial_point: &mut Point, origin: Origin) {
|
||||
// *when a curve ends in a closepath and its start point does not equal its endpoint they should be connected with a line
|
||||
let end_seg = match self.current.last() {
|
||||
Some(seg) => seg,
|
||||
None => self.beginning.last().unwrap(), // if both current and beginning are empty, the path is empty
|
||||
// When a curve ends in a closepath and its start point does not equal its endpoint they should be connected with a line
|
||||
let last_line = match self.current.last() {
|
||||
Some(start_of_final_edge) => Line {
|
||||
p0: start_of_final_edge.end(),
|
||||
p1: *initial_point,
|
||||
},
|
||||
None => {
|
||||
// When None occurs the current edge has been connected to a vertex.
|
||||
// Either self.beginning is Some or None, if self.beginning is Some there may be a dangling edge to connect
|
||||
// if self.beginning is None, the end of the current edge may not have closed the path
|
||||
match self.beginning.last() {
|
||||
Some(end_of_first_edge) => Line {
|
||||
p0: end_of_first_edge.end(),
|
||||
p1: *initial_point,
|
||||
},
|
||||
None => Line {
|
||||
// should never panic, either a intersection has been encountered, so self.current_start is Some.
|
||||
// or no vertex has been encountered so self.beginning.last() is Some
|
||||
p0: graph.vertex(self.current_start.unwrap()).intersect.point,
|
||||
p1: *initial_point,
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
let temp_copy = end_seg.end();
|
||||
if temp_copy != *initial_point {
|
||||
// a closepath implicitly defines a line which closes the path
|
||||
self.advance_by_seg(graph, PathSeg::Line(Line { p0: temp_copy, p1: *initial_point }), origin);
|
||||
if last_line.length() > F64PRECISE {
|
||||
// A closepath implicitly defines a line which closes the path and the closepath line may contain intersections
|
||||
self.advance_by_seg(graph, PathSeg::Line(last_line), origin);
|
||||
}
|
||||
// when a closepath is not followed by moveto, the next path starts at the end of the current path
|
||||
*initial_point = temp_copy;
|
||||
}
|
||||
|
||||
fn finalize_sub_path(&mut self, graph: &mut PathGraph, origin: Origin) {
|
||||
if let (Some(current_start_), Some(start_index_)) = (self.current_start, self.start_index) {
|
||||
//complete the current path
|
||||
// Complete the current path
|
||||
self.current.append(&mut self.beginning);
|
||||
graph.add_edge(origin, current_start_, start_index_, self.current.clone());
|
||||
} else {
|
||||
//path has a subpath with no intersects
|
||||
//create a dummy vertex with single edge which will be identified as cycle
|
||||
// Path has a subpath with no intersects.
|
||||
// Create a dummy vertex with single edge which will be identified as cycle.
|
||||
let dumb_id = graph.add_vertex(Intersect::new(self.beginning[0].start(), 0.0, 0.0, -1, -1));
|
||||
graph.add_edge(origin, dumb_id, dumb_id, self.beginning.clone());
|
||||
}
|
||||
@@ -272,6 +290,7 @@ impl PathGraph {
|
||||
|
||||
let mut algorithm_state = AlgorithmState::new();
|
||||
|
||||
// All valid SVG paths start with a moveto, so this will always be initialized
|
||||
let mut initial_point = Point::new(0.0, 0.0);
|
||||
|
||||
for (el_index, el) in path.iter().enumerate() {
|
||||
@@ -306,7 +325,7 @@ impl PathGraph {
|
||||
}
|
||||
|
||||
/// Returns the `Vertex` index and intersect `t_value` for all intersects in the segment identified by `seg_index` from `origin`.
|
||||
/// sorts both lists for ascending t_value
|
||||
/// Sorts both lists for ascending `t_value`.
|
||||
fn intersects_in_seg(&self, seg_index: i32, origin: Origin) -> (Vec<usize>, Vec<f64>) {
|
||||
let mut vertex_index = Vec::new();
|
||||
let mut t_values = Vec::new();
|
||||
@@ -323,7 +342,7 @@ impl PathGraph {
|
||||
(vertex_index, t_values)
|
||||
}
|
||||
|
||||
// Returns the number of vertices in the graph. This is equivalent to the number of intersections.
|
||||
/// Returns the number of vertices in the graph. This is equivalent to the number of intersections.
|
||||
pub fn size(&self) -> usize {
|
||||
self.vertices.len()
|
||||
}
|
||||
@@ -391,18 +410,18 @@ impl PathGraph {
|
||||
|
||||
/// If `t` is on `(0, 1)`, returns the split curve.
|
||||
/// If `t` is outside `[0, 1]`, returns `(None, None)`
|
||||
/// If `t` is 0 returns (None, `p`).
|
||||
/// If `t` is 1 returns (`p`, None).
|
||||
// TODO: test values outside 1
|
||||
/// If `t` is 0 returns `(None, p)`.
|
||||
/// If `t` is 1 returns `(p, None)`.
|
||||
pub fn split_path_seg(p: &PathSeg, t: f64) -> (Option<PathSeg>, Option<PathSeg>) {
|
||||
if t <= -F64PRECISE || t >= 1.0 + F64PRECISE {
|
||||
return (None, None);
|
||||
}
|
||||
if t <= F64PRECISE {
|
||||
if t >= 1.0 - F64PRECISE {
|
||||
return (None, None);
|
||||
}
|
||||
return (Some(*p), None);
|
||||
} else if t >= 1.0 - F64PRECISE {
|
||||
return (None, Some(*p));
|
||||
}
|
||||
if t >= 1.0 - F64PRECISE {
|
||||
return (Some(*p), None);
|
||||
}
|
||||
match p {
|
||||
PathSeg::Cubic(cubic) => {
|
||||
let a1 = Line::new(cubic.p0, cubic.p1).eval(t);
|
||||
@@ -453,12 +472,76 @@ pub fn subdivide_path_seg(p: &PathSeg, t_values: &mut [f64]) -> Vec<Option<PathS
|
||||
sub_segments
|
||||
}
|
||||
|
||||
pub fn composite_boolean_operation(mut select: BooleanOperation, shapes: &mut Vec<RefCell<ShapeLayer>>) -> Result<Vec<ShapeLayer>, BooleanOperationError> {
|
||||
if select == BooleanOperation::SubtractBack {
|
||||
select = BooleanOperation::SubtractFront;
|
||||
let temp_len = shapes.len();
|
||||
shapes.swap(0, temp_len - 1);
|
||||
}
|
||||
match select {
|
||||
BooleanOperation::Union | BooleanOperation::Intersection => {
|
||||
// We must attempt to union each shape with every other shape
|
||||
let mut subject_idx = 0;
|
||||
while subject_idx < shapes.len() {
|
||||
let mut shape_idx = 0;
|
||||
while shape_idx < shapes.len() && subject_idx < shapes.len() {
|
||||
if shape_idx == subject_idx {
|
||||
shape_idx += 1;
|
||||
continue;
|
||||
}
|
||||
let partial_union = boolean_operation(select, &mut shapes[subject_idx].borrow_mut(), &mut shapes[shape_idx].borrow_mut());
|
||||
match partial_union {
|
||||
Ok(temp_union) => {
|
||||
// The result of a successful union will be exactly one shape
|
||||
shapes.push(RefCell::new(temp_union.into_iter().next().unwrap()));
|
||||
shapes.swap_remove(subject_idx);
|
||||
shapes.swap_remove(shape_idx);
|
||||
}
|
||||
Err(BooleanOperationError::NothingDone) => shape_idx += 1,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
subject_idx += 1;
|
||||
}
|
||||
Ok(shapes.iter().map(|ref_shape_layer| ref_shape_layer.borrow().clone()).collect())
|
||||
}
|
||||
BooleanOperation::SubtractFront => {
|
||||
let mut result = vec![shapes[0].borrow().clone()];
|
||||
for shape_idx in 1..shapes.len() {
|
||||
let mut temp = Vec::new();
|
||||
for mut partial in result {
|
||||
match boolean_operation(select, &mut partial, &mut shapes[shape_idx].borrow_mut()) {
|
||||
Ok(mut partial_result) => temp.append(&mut partial_result),
|
||||
Err(BooleanOperationError::NothingDone) => temp.push(partial),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
result = temp; // This move should be done without copying
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
BooleanOperation::Difference => {
|
||||
let mut difference = Vec::new();
|
||||
for shape_idx in 0..shapes.len() {
|
||||
shapes.swap(0, shape_idx);
|
||||
difference.append(&mut composite_boolean_operation(BooleanOperation::SubtractFront, shapes)?);
|
||||
}
|
||||
Ok(difference)
|
||||
}
|
||||
BooleanOperation::SubtractBack => unreachable!("composite boolean operation: unreachable subtract from back"),
|
||||
}
|
||||
}
|
||||
|
||||
// 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(select: BooleanOperation, mut alpha: ShapeLayer, mut beta: ShapeLayer) -> Result<Vec<ShapeLayer>, BooleanOperationError> {
|
||||
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() {
|
||||
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));
|
||||
@@ -487,10 +570,10 @@ pub fn boolean_operation(select: BooleanOperation, mut alpha: ShapeLayer, mut be
|
||||
// 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 {
|
||||
Ok(vec![alpha])
|
||||
Ok(vec![alpha.clone()])
|
||||
} else if cast_horizontal_ray(point_on_curve(&alpha.path), &beta.path) % 2 != 0 {
|
||||
beta.style = alpha.style;
|
||||
Ok(vec![beta])
|
||||
beta.style = alpha.style.clone();
|
||||
Ok(vec![beta.clone()])
|
||||
} else {
|
||||
Err(BooleanOperationError::NothingDone)
|
||||
}
|
||||
@@ -528,10 +611,10 @@ pub fn boolean_operation(select: BooleanOperation, mut alpha: ShapeLayer, mut be
|
||||
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 {
|
||||
beta.style = alpha.style;
|
||||
Ok(vec![beta])
|
||||
beta.style = alpha.style.clone();
|
||||
Ok(vec![beta.clone()])
|
||||
} else if cast_horizontal_ray(point_on_curve(&alpha.path), &beta.path) % 2 != 0 {
|
||||
Ok(vec![alpha])
|
||||
Ok(vec![alpha.clone()])
|
||||
} else {
|
||||
Err(BooleanOperationError::NothingDone)
|
||||
}
|
||||
@@ -540,23 +623,7 @@ pub fn boolean_operation(select: BooleanOperation, mut alpha: ShapeLayer, mut be
|
||||
}
|
||||
}
|
||||
BooleanOperation::SubtractBack => {
|
||||
match if beta_dir != alpha_dir {
|
||||
PathGraph::from_paths(&alpha.path, &beta.path)
|
||||
} else {
|
||||
PathGraph::from_paths(&alpha.path, &beta_reverse)
|
||||
} {
|
||||
Ok(graph) => collect_shapes(&graph, &mut graph.get_cycles(), |dir| dir != alpha_dir, |_| &beta.style),
|
||||
Err(BooleanOperationError::NoIntersections) => {
|
||||
if cast_horizontal_ray(point_on_curve(&alpha.path), &beta.path) % 2 != 0 {
|
||||
add_subpath(&mut beta.path, if beta_dir == alpha_dir { reverse_path(&alpha.path) } else { alpha.path });
|
||||
beta.style = alpha.style;
|
||||
Ok(vec![beta])
|
||||
} else {
|
||||
Err(BooleanOperationError::NothingDone)
|
||||
}
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
unreachable!("Boolean operation: unreachable subtract from back");
|
||||
}
|
||||
BooleanOperation::SubtractFront => {
|
||||
match if beta_dir != alpha_dir {
|
||||
@@ -567,8 +634,8 @@ pub fn boolean_operation(select: BooleanOperation, mut alpha: ShapeLayer, mut be
|
||||
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 });
|
||||
Ok(vec![alpha])
|
||||
add_subpath(&mut alpha.path, if beta_dir == alpha_dir { reverse_path(&beta.path) } else { beta.path.clone() });
|
||||
Ok(vec![alpha.clone()])
|
||||
} else {
|
||||
Err(BooleanOperationError::NothingDone)
|
||||
}
|
||||
@@ -579,23 +646,16 @@ pub fn boolean_operation(select: BooleanOperation, mut alpha: ShapeLayer, mut be
|
||||
}
|
||||
}
|
||||
|
||||
// TODO less hacky way to handle double counts on shared endpoints
|
||||
// TODO check bounding boxes more rigorously
|
||||
pub fn cast_horizontal_ray(mut from: Point, into: &BezPath) -> usize {
|
||||
// In practice, this makes it less likely that a ray will intersect with shared point between two curves
|
||||
from.y += RAY_FUDGE_FACTOR;
|
||||
|
||||
let ray = Line {
|
||||
pub fn cast_horizontal_ray(from: Point, into: &BezPath) -> usize {
|
||||
let mut ray = PathSeg::Line(Line {
|
||||
p0: from,
|
||||
p1: Point {
|
||||
x: from.x + 1.0,
|
||||
y: from.y + RAY_FUDGE_FACTOR,
|
||||
},
|
||||
};
|
||||
p1: Point { x: from.x + 1.0, y: from.y },
|
||||
});
|
||||
let mut intersects = Vec::new();
|
||||
for ref seg in into.segments() {
|
||||
for ref mut seg in into.segments() {
|
||||
if seg.bounding_box().x1 > from.x {
|
||||
line_curve_intersections(&ray, seg, true, |_, b| valid_t(b), &mut intersects);
|
||||
line_curve_intersections((&mut ray, seg), |_, b| valid_t(b), &mut intersects);
|
||||
}
|
||||
}
|
||||
intersects.len()
|
||||
@@ -636,7 +696,8 @@ where
|
||||
shapes.push(graph.get_shape(cycle, style(dir)));
|
||||
}
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
// Exclude cycles with 0.0 area
|
||||
Err(_err) => (),
|
||||
}
|
||||
}
|
||||
Ok(shapes)
|
||||
@@ -675,7 +736,6 @@ pub fn reverse_path(path: &BezPath) -> BezPath {
|
||||
}
|
||||
}
|
||||
curve.append(&mut temp.into_iter().rev().collect());
|
||||
log::debug!("{:?}", BezPath::from_path_segments(curve.clone().into_iter()));
|
||||
BezPath::from_path_segments(curve.into_iter())
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user