-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
shell.rs
340 lines (300 loc) · 11.6 KB
/
shell.rs
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
use std::{
collections::{BTreeMap, HashMap},
iter::repeat,
};
use fj_math::{Point, Scalar};
use crate::{
geometry::SurfaceGeometry,
objects::{HalfEdge, Shell, Surface},
queries::BoundingVerticesOfEdge,
storage::{Handle, HandleWrapper, ObjectId},
};
use super::{Validate, ValidationConfig, ValidationError};
impl Validate for Shell {
fn validate_with_config(
&self,
config: &ValidationConfig,
errors: &mut Vec<ValidationError>,
) {
ShellValidationError::validate_edges_coincident(self, config, errors);
ShellValidationError::validate_watertight(self, config, errors);
}
}
/// [`Shell`] validation failed
#[derive(Clone, Debug, thiserror::Error)]
pub enum ShellValidationError {
/// [`Shell`] contains global_edges not referred to by two half-edges
#[error("Shell is not watertight")]
NotWatertight,
/// [`Shell`] contains half-edges that are coincident, but refer to
/// different global_edges
#[error(
"`Shell` contains `HalfEdge`s that are coincident but refer to \
different `GlobalEdge`s\n\
Edge 1: {0:#?}\n\
Edge 2: {1:#?}"
)]
CoincidentEdgesNotIdentical(Handle<HalfEdge>, Handle<HalfEdge>),
/// [`Shell`] contains half-edges that are identical, but do not coincide
#[error(
"Shell contains HalfEdges that are identical but do not coincide\n\
Edge 1: {edge_a:#?}\n\
Surface for edge 1: {surface_a:#?}\n\
Edge 2: {edge_b:#?}\n\
Surface for edge 2: {surface_b:#?}"
)]
IdenticalEdgesNotCoincident {
/// The first edge
edge_a: Handle<HalfEdge>,
/// The surface that the first edge is on
surface_a: Handle<Surface>,
/// The second edge
edge_b: Handle<HalfEdge>,
/// The surface that the second edge is on
surface_b: Handle<Surface>,
},
}
/// Sample two edges at various (currently 3) points in 3D along them.
///
/// Returns an [`Iterator`] of the distance at each sample.
fn distances(
config: &ValidationConfig,
edge_a: Handle<HalfEdge>,
surface_a: Handle<Surface>,
edge_b: Handle<HalfEdge>,
surface_b: Handle<Surface>,
) -> impl Iterator<Item = Scalar> {
fn sample(
percent: f64,
(edge, surface): (&Handle<HalfEdge>, SurfaceGeometry),
) -> Point<3> {
let [start, end] = edge.boundary().inner;
let path_coords = start + (end - start) * percent;
let surface_coords = edge.path().point_from_path_coords(path_coords);
surface.point_from_surface_coords(surface_coords)
}
// Check whether start positions do not match. If they don't treat second edge as flipped
let flip = sample(0.0, (&edge_a, surface_a.geometry()))
.distance_to(&sample(0.0, (&edge_b, surface_b.geometry())))
> config.identical_max_distance;
// Three samples (start, middle, end), are enough to detect weather lines
// and circles match. If we were to add more complicated curves, this might
// need to change.
let sample_count = 3;
let step = 1.0 / (sample_count as f64 - 1.0);
let mut distances = Vec::new();
for i in 0..sample_count {
let percent = i as f64 * step;
let sample1 = sample(percent, (&edge_a, surface_a.geometry()));
let sample2 = sample(
if flip { 1.0 - percent } else { percent },
(&edge_b, surface_b.geometry()),
);
distances.push(sample1.distance_to(&sample2))
}
distances.into_iter()
}
impl ShellValidationError {
fn validate_edges_coincident(
shell: &Shell,
config: &ValidationConfig,
errors: &mut Vec<ValidationError>,
) {
let edges_and_surfaces: Vec<_> = shell
.faces()
.into_iter()
.flat_map(|face| {
face.region()
.all_cycles()
.flat_map(|cycle| cycle.half_edges().cloned())
.zip(repeat(face.surface().clone()))
})
.collect();
// This is O(N^2) which isn't great, but we can't use a HashMap since we
// need to deal with float inaccuracies. Maybe we could use some smarter
// data-structure like an octree.
for (edge_a, surface_a) in &edges_and_surfaces {
for (edge_b, surface_b) in &edges_and_surfaces {
let identical_according_to_global_form =
edge_a.global_form().id() == edge_b.global_form().id();
let identical_according_to_curve = {
let on_same_curve =
edge_a.curve().id() == edge_b.curve().id();
let have_same_boundary = {
let bounding_vertices_of = |edge| {
shell
.bounding_vertices_of_edge(edge)
.expect("Expected edge to be part of shell")
.normalize()
};
bounding_vertices_of(edge_a)
== bounding_vertices_of(edge_b)
};
on_same_curve && have_same_boundary
};
assert_eq!(
identical_according_to_curve,
identical_according_to_global_form,
);
match identical_according_to_curve {
true => {
// All points on identical curves should be within
// identical_max_distance, so we shouldn't have any
// greater than the max
if distances(
config,
edge_a.clone(),
surface_a.clone(),
edge_b.clone(),
surface_b.clone(),
)
.any(|d| d > config.identical_max_distance)
{
errors.push(
Self::IdenticalEdgesNotCoincident {
edge_a: edge_a.clone(),
surface_a: surface_a.clone(),
edge_b: edge_b.clone(),
surface_b: surface_b.clone(),
}
.into(),
)
}
}
false => {
// If all points on distinct curves are within
// distinct_min_distance, that's a problem.
if distances(
config,
edge_a.clone(),
surface_a.clone(),
edge_b.clone(),
surface_b.clone(),
)
.all(|d| d < config.distinct_min_distance)
{
errors.push(
Self::CoincidentEdgesNotIdentical(
edge_a.clone(),
edge_b.clone(),
)
.into(),
)
}
}
}
}
}
}
fn validate_watertight(
shell: &Shell,
_: &ValidationConfig,
errors: &mut Vec<ValidationError>,
) {
let mut num_edges = BTreeMap::new();
for face in shell.faces() {
for cycle in face.region().all_cycles() {
for half_edge in cycle.half_edges() {
let curve = HandleWrapper::from(half_edge.curve().clone());
let bounding_vertices = cycle
.bounding_vertices_of_edge(half_edge)
.expect(
"Cycle should provide bounds of its own half-edge",
)
.normalize();
let edge = (curve, bounding_vertices);
*num_edges.entry(edge).or_insert(0) += 1;
}
}
}
// Every edge should have exactly one matching edge that shares a curve
// and boundary.
if num_edges.into_values().any(|num| num != 2) {
errors.push(Self::NotWatertight.into());
}
let mut half_edge_to_faces: HashMap<ObjectId, usize> = HashMap::new();
for face in shell.faces() {
for cycle in face.region().all_cycles() {
for half_edge in cycle.half_edges() {
let id = half_edge.global_form().id();
let entry = half_edge_to_faces.entry(id);
*entry.or_insert(0) += 1;
}
}
}
// Each global edge should have exactly two half edges that are part of
// the shell
if half_edge_to_faces.iter().any(|(_, c)| *c != 2) {
errors.push(Self::NotWatertight.into())
}
}
}
#[cfg(test)]
mod tests {
use crate::{
assert_contains_err,
objects::{Curve, GlobalEdge, Shell},
operations::{
BuildShell, Insert, UpdateCycle, UpdateFace, UpdateHalfEdge,
UpdateRegion, UpdateShell,
},
services::Services,
validate::{shell::ShellValidationError, Validate, ValidationError},
};
#[test]
fn coincident_not_identical() -> anyhow::Result<()> {
let mut services = Services::new();
let valid = Shell::tetrahedron(
[[0., 0., 0.], [0., 1., 0.], [1., 0., 0.], [0., 0., 1.]],
&mut services,
);
let invalid = valid.shell.replace_face(
&valid.abc.face,
valid
.abc
.face
.update_region(|region| {
region
.update_exterior(|cycle| {
cycle
.update_nth_half_edge(0, |half_edge| {
let curve =
Curve::new().insert(&mut services);
let global_form =
GlobalEdge::new().insert(&mut services);
half_edge
.replace_curve(curve)
.replace_global_form(global_form)
.insert(&mut services)
})
.insert(&mut services)
})
.insert(&mut services)
})
.insert(&mut services),
);
valid.shell.validate_and_return_first_error()?;
assert_contains_err!(
invalid,
ValidationError::Shell(
ShellValidationError::CoincidentEdgesNotIdentical(..)
)
);
Ok(())
}
#[test]
fn shell_not_watertight() -> anyhow::Result<()> {
let mut services = Services::new();
let valid = Shell::tetrahedron(
[[0., 0., 0.], [0., 1., 0.], [1., 0., 0.], [0., 0., 1.]],
&mut services,
);
let invalid = valid.shell.remove_face(&valid.abc.face);
valid.shell.validate_and_return_first_error()?;
assert_contains_err!(
invalid,
ValidationError::Shell(ShellValidationError::NotWatertight)
);
Ok(())
}
}