1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use crate::geom::vector;
use crate::path::{iterator::PathIterator, PathEvent};
pub fn approximate_signed_area<Iter>(tolerance: f32, path: Iter) -> f32
where
Iter: IntoIterator<Item = PathEvent>,
{
let mut path = path.into_iter();
let mut area = 0.0;
while let Some(sp_area) = approximate_sub_path_signed_area(tolerance, &mut path) {
area += sp_area;
}
area
}
pub fn approximate_sub_path_signed_area<Iter>(tolerance: f32, path: &mut Iter) -> Option<f32>
where
Iter: Iterator<Item = PathEvent>,
{
let first = if let Some(PathEvent::Begin { at }) = path.next() {
at
} else {
return None;
};
let mut doube_area = 0.0;
let mut v0 = vector(0.0, 0.0);
for evt in path.flattened(tolerance) {
match evt {
PathEvent::Begin { .. } => {
return None;
}
PathEvent::End { last, first, .. } => {
let v1 = last - first;
doube_area += v0.cross(v1);
return Some(doube_area * 0.5);
}
PathEvent::Line { to, .. } => {
let v1 = to - first;
doube_area += v0.cross(v1);
v0 = v1;
}
PathEvent::Quadratic { .. } | PathEvent::Cubic { .. } => {
debug_assert!(false, "Unexpected curve in a flattened path");
}
};
}
None
}
pub struct SignedAreas<Iter = PathEvent>(pub Iter, f32);
impl<Iter: Iterator<Item = PathEvent>> Iterator for SignedAreas<Iter> {
type Item = f32;
fn next(&mut self) -> Option<f32> {
approximate_sub_path_signed_area(self.1, &mut self.0)
}
}
#[test]
fn sub_path_signed_area() {
use crate::geom::point;
let mut path = crate::path::Path::builder();
path.begin(point(0.0, 0.0));
path.line_to(point(1.0, 0.0));
path.line_to(point(1.0, 1.0));
path.line_to(point(0.0, 1.0));
path.close();
path.begin(point(0.0, 0.0));
path.line_to(point(0.0, 1.0));
path.line_to(point(1.0, 1.0));
path.line_to(point(1.0, 0.0));
path.close();
let path = path.build();
let mut iter = path.iter();
assert_eq!(approximate_sub_path_signed_area(0.01, &mut iter), Some(1.0));
assert_eq!(
approximate_sub_path_signed_area(0.01, &mut iter),
Some(-1.0)
);
assert_eq!(approximate_sub_path_signed_area(0.01, &mut iter), None);
let mut path = crate::path::Path::builder();
path.begin(point(0.0, 1.0));
path.line_to(point(1.0, 1.0));
path.line_to(point(1.0, 0.0));
path.line_to(point(2.0, 0.0));
path.line_to(point(2.0, 1.0));
path.line_to(point(3.0, 1.0));
path.line_to(point(3.0, 2.0));
path.line_to(point(2.0, 2.0));
path.line_to(point(2.0, 3.0));
path.line_to(point(1.0, 3.0));
path.line_to(point(1.0, 2.0));
path.line_to(point(0.0, 2.0));
path.close();
assert_eq!(approximate_signed_area(0.01, path.build().iter()), 5.0);
}