-
Notifications
You must be signed in to change notification settings - Fork 4
/
mod.rs
1927 lines (1706 loc) · 78.3 KB
/
mod.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Everything related to the [`HalfEdgeMesh`].
// # Some notes for developers about this implementation
//
// - The twin half edges are stored implicitly: twins are always stored next to
// one another in the underlying vector and thus always have handle indices
// only one apart. Furthermore, since we start with the handle index 0, the
// indices of two twins are always 2k and 2k + 1 where k is an integer.
// - We map edge handles to half edge handles by multiplying by two. Half edge
// to edge is integer division by two. This works out very nicely: the edge
// handle space is contiguous and the conversion operations are a simple
// shift.
use std::{
fmt,
marker::PhantomData,
mem,
ops,
slice,
};
use optional::Optioned as Opt;
use typebool::True;
use crate::{
hsize,
prelude::*,
map::{DenseMap, set::DenseSet},
};
use super::{
Checked, OptionalField, StoreField, TriFaces, FaceKind, PolyFaces, SplitEdgeWithFacesResult,
util::FieldStorage,
};
use self::adj::{CwVertexCirculator, FaceCirculator};
mod adj;
#[cfg(test)]
mod tests;
const NON_MANIFOLD_VERTEX_ERR: &str =
"new face would add a non-manifold vertex (no hole found in cycle)";
const NON_MANIFOLD_EDGE_ERR: &str =
"new face would add a non-manifold edge";
// ===============================================================================================
// ===== Compile time configuration of HalfEdgeMesh
// ===============================================================================================
/// Compile-time configuration for [`HalfEdgeMesh`].
///
/// To configure a half edge mesh, either use one of the existing types
/// implementing this trait, or create your own (preferably inhabitable) type
/// and implement this trait.
pub trait Config: 'static {
/// What kind of faces are allowed in this half edge mesh.
///
/// The data structure supports poly meshes, but if you only need triangle
/// faces (and you really need a half edge mesh), restricting the faces to
/// triangles here can speed up a few operations.
///
/// The `HalfEdgeMesh` will forward this type to `Mesh::FaceKind` in the
/// `Mesh` implementation.
type FaceKind: FaceKind;
/// Specifies whether a `prev` handle is stored per half edge. This makes
/// some operations faster, but increases memory consumption.
type PrevEdge: OptionalField;
// TODO:
// - allow multi fan blades?
}
/// The standard configuration for the half edge mesh. Poly faces are
/// supported.
#[allow(missing_debug_implementations)]
pub enum PolyConfig {}
impl Config for PolyConfig {
type FaceKind = PolyFaces;
type PrevEdge = StoreField;
}
#[allow(missing_debug_implementations)]
pub enum TriConfig {}
impl Config for TriConfig {
type FaceKind = TriFaces;
type PrevEdge = StoreField;
}
// ===============================================================================================
// ===== HalfEdgeHandle
// ===============================================================================================
/// Handle to refer to half edges.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct HalfEdgeHandle(hsize);
impl HalfEdgeHandle {
/// Returns the half-edge of the given edge with the lower index value.
///
/// Again, due to our assumptions on how edges are stored, we just have to
/// multiply the edges handle with 2 to get a corresponding half edge
/// handle. This method does not check if the half edge actually exists.
#[inline(always)]
fn lower_half_of(edge: EdgeHandle) -> Self {
Self(edge.idx() * 2)
}
/// Returns the full edge this half-edge belongs to.
///
/// This works only because we know we store the half edges adjacent to one
/// another. Of one edge, the half edge with the smaller index always has
/// an even index, while the other one has an odd one. This means we can
/// just integer divide by 2 and get the edge index.
#[inline(always)]
fn full_edge(self) -> EdgeHandle {
EdgeHandle::new(self.0 / 2)
}
}
impl Handle for HalfEdgeHandle {
#[inline(always)]
fn new(id: hsize) -> Self {
HalfEdgeHandle(id)
}
#[inline(always)]
fn idx(&self) -> hsize {
self.0
}
}
impl Checked<HalfEdgeHandle> {
/// Returns the handle of the half edge twin (the half edge right next to
/// this half edge, but pointing in the opposite direction).
///
/// This method only works due to some assumptions about the data
/// structure, so this is only valid together with data structure in this
/// module! In particular, it assumes that two half edge twins are always
/// stored right next to each other and that the handles start counting at
/// an even number (0 in our case). Thus, we can simply flip the last bit
/// of the handle id to get the twin handle.
#[inline(always)]
fn twin(self) -> Checked<HalfEdgeHandle> {
// See function documentation on why this is safe. A pair of twins is
// always stored together.
unsafe { Self::new(HalfEdgeHandle::new(self.idx() ^ 1)) }
}
}
impl fmt::Debug for HalfEdgeHandle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "HE{}", self.idx())
}
}
// ===============================================================================================
// ===== Definition of types stored inside the data structure
// ===============================================================================================
/// Implementation of the *half edge mesh*. This data structure is widely used
/// in geometry processing due to its many capabilities paired with fairly good
/// speed and memory consumption.
///
/// This data structure allows you to represent polygon meshes where each face
/// can have differently many vertices. (However, you can restrict this mesh to
/// triangle meshes via the configuration.) Furthermore, it can answer all
/// adjacency queries and exposes full edges.
///
/// The half edge mesh is a half-edge based data structure, with most of the
/// connectivity stored per half edge. Each face and vertex just store one
/// arbitrary half edge handle. This diagram illustrates the fields stored per
/// half edge. (Not shown in the diagram: each half edge also stores the handle
/// of its face.)
///
#[doc = include_str!("diagram.svg")]
///
///
/// # References
///
/// Introduced in: Mäntylä, Martti. An introduction to solid modeling. Computer
/// science press, 1988.
#[derive(Empty)]
pub struct HalfEdgeMesh<C: Config = PolyConfig> {
vertices: DenseMap<VertexHandle, Vertex>,
faces: DenseMap<FaceHandle, Face>,
half_edges: DenseMap<HalfEdgeHandle, HalfEdge<C>>,
/// We box the cache to not increase the size of `Self` by too much.
cache: Box<OpCache>,
_config: PhantomData<C>,
}
/// Cache of memory needed for operations on the mesh. That way we avoid that
/// each operation has to allocate memory over and over again. For example,
/// `add_face` needs temporary memory, but allocating each call would be
/// wasteful.
#[derive(Empty)]
struct OpCache {
/// Used for `add_face`.
inner_half_edges: Vec<Checked<HalfEdgeHandle>>,
}
/// Data stored per `Face`.
#[derive(Clone, Copy)]
pub(crate) struct Face {
/// Handle of one (arbitrary) half edge adjacent to the face.
edge: Checked<HalfEdgeHandle>,
}
/// Data stored per `Vertex`.
#[derive(Clone, Copy)]
pub(crate) struct Vertex {
/// Handle of one outgoing half edge.
///
/// - If the vertex is isolated, this is `None`.
/// - If the vertex is a boundary vertex, this stores one arbitrary of the
/// boundary half edges. There only exists one such half edge per fan
/// blade.
/// - If the vertex is not on the boundary, the half edge is completely
/// arbitrary.
outgoing: Opt<Checked<HalfEdgeHandle>>,
}
/// Data stored per half edge.
struct HalfEdge<C: Config> {
/// The adjacent face, if one exists.
face: Opt<Checked<FaceHandle>>,
/// The vertex this half edge points to.
target: Checked<VertexHandle>,
/// The next half edge around the face or hole this half edge is adjacent
/// to (going counter clock wise).
next: Checked<HalfEdgeHandle>,
/// The previous half edge around the face or hole this half edge is
/// adjacent to (counter clock wise). This is only stored when the
/// configuration `C` says so.
prev: <C::PrevEdge as OptionalField>::Storage<Checked<HalfEdgeHandle>>,
}
impl<C: Config> Copy for HalfEdge<C> {}
impl<C: Config> Clone for HalfEdge<C> {
fn clone(&self) -> Self {
Self {
face: self.face.clone(),
target: self.target.clone(),
next: self.next.clone(),
prev: self.prev.clone(),
}
}
}
impl<C: Config> fmt::Debug for HalfEdgeMesh<C> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("HalfEdgeMesh")
.field("vertices", &self.vertices)
.field("faces", &self.faces)
.field("half_edges", &self.half_edges)
.finish()
}
}
impl<C: Config> Clone for HalfEdgeMesh<C> {
fn clone(&self) -> Self {
Self {
vertices: self.vertices.clone(),
faces: self.faces.clone(),
half_edges: self.half_edges.clone(),
// As it's cache, we do not actually clone it, but create a new one
cache: Box::new(OpCache::empty()),
_config: PhantomData,
}
}
}
impl fmt::Debug for Vertex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Vertex {{ outgoing: {:?} }}", self.outgoing)
}
}
impl fmt::Debug for Face {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Face {{ edge: {:?} }}", self.edge)
}
}
impl<C: Config> fmt::Debug for HalfEdge<C> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let prev = self.prev.into_option()
.map(|prev| format!(" prev: {:6}", format!("{:?},", prev)))
.unwrap_or("".into());
write!(
f,
"HalfEdge {{ target: {:5} next: {:6}{} face: {:?} }}",
format!("{:?},", self.target),
format!("{:?},", self.next),
prev,
self.face,
)
}
}
/// Helper macro to set the `next` and `prev` handles in one line. These two
/// handles always have to be set at the same time, so with this macro it's you
/// cannot forget.
macro_rules! set_next_prev {
($mesh:ident, $prev:tt -> $next:tt) => {{
$mesh[$prev].next = $next;
$mesh[$next].prev = $prev.into();
}};
}
// ===============================================================================================
// ===== Internal helper methods
// ===============================================================================================
impl<C: Config> HalfEdgeMesh<C> {
/// Makes sure the given handle points to an existing element. If that's
/// not the case, this method panics.
fn check_face(&self, fh: FaceHandle) -> Checked<FaceHandle> {
if self.faces.contains_handle(fh) {
// We just checked `fh` is valid, so `unsafe` is fine.
unsafe { Checked::new(fh) }
} else {
panic!(
"{:?} was passed to a half edge mesh, but this face does not exist in this mesh",
fh,
);
}
}
/// Makes sure the given handle points to an existing element. If that's
/// not the case, this method panics.
fn check_vertex(&self, vh: VertexHandle) -> Checked<VertexHandle> {
if self.vertices.contains_handle(vh) {
// We just checked `vh` is valid, so `unsafe` is fine.
unsafe { Checked::new(vh) }
} else {
panic!(
"{:?} was passed to a half edge mesh, but this vertex does not exist in this mesh",
vh,
);
}
}
/// Makes sure the given handle points to an existing element. If that's
/// not the case, this method panics. Otherwise, the half edge with the
/// lower index is returned.
fn checked_half_of(&self, eh: EdgeHandle) -> Checked<HalfEdgeHandle> {
let heh = HalfEdgeHandle::lower_half_of(eh);
if self.half_edges.contains_handle(heh) {
// We just checked `heh` is valid, so `unsafe` is fine.
unsafe { Checked::new(heh) }
} else {
panic!(
"{:?} was passed to a half edge mesh, but this edge does not exist in this mesh",
eh,
);
}
}
/// Returns an iterator the circulates around the face `center`. The
/// iterator yields inner half edges.
fn circulate_around_face(&self, center: Checked<FaceHandle>) -> FaceCirculator<'_, C> {
// TODO: optimize for tri mesh
let start_he = self[center].edge;
FaceCirculator::NonEmpty {
mesh: self,
current_he: start_he,
start_he,
}
}
/// Returns an iterator the circulates around the vertex `center`. The
/// iterator yields outgoing half edges.
fn circulate_around_vertex(&self, center: Checked<VertexHandle>) -> CwVertexCirculator<'_, C> {
match self[center].outgoing.into_option() {
None => CwVertexCirculator::Empty,
Some(start_he) => CwVertexCirculator::new(self, start_he),
}
}
/// Tries to find the half edge from `from` to `to`. Returns `None` if
/// there is no edge between the two vertices.
fn he_between(
&self,
from: Checked<VertexHandle>,
to: Checked<VertexHandle>,
) -> Option<Checked<HalfEdgeHandle>> {
self.circulate_around_vertex(from)
.find(|&outgoing| self[outgoing].target == to)
}
/// Returns the half edge whose `next` points to `he`.
///
/// If `prev` handles are stored, this is easy. Otherwise, we have to
/// circulate around the whole vertex.
fn prev(&self, he: Checked<HalfEdgeHandle>) -> Checked<HalfEdgeHandle> {
// Looks like runtime dispatch, but this will be optimized as the
// compiler already knows whether `into_option` returns `Some` or
// `None`.
match self[he].prev.into_option() {
Some(prev) => prev,
None => {
self.find_incoming_he(he.twin(), |incoming| self[incoming].next == he)
.expect("internal HEM error: could not find `prev` half edge")
}
}
}
/// Tries to find a half edge pointing towards `start_edge.target` that
/// satisfies the given predicate. Returns `None` if no edge around
/// `start_edge.target` satisfying `predicate` is found.
#[inline(always)]
fn find_incoming_he(
&self,
start_edge: Checked<HalfEdgeHandle>,
mut predicate: impl FnMut(Checked<HalfEdgeHandle>) -> bool,
) -> Option<Checked<HalfEdgeHandle>> {
let mut incoming = start_edge;
loop {
if predicate(incoming) {
return Some(incoming);
}
let next = self[incoming].next.twin();
if next == start_edge {
return None;
}
incoming = next;
}
}
/// Adds two half edges between `from` and `to`, partially filled with
/// dummy values. Returns the handle of the halfedge pointing to `to`.
///
/// This function:
/// - Correctly sets the `target` field of the half edges.
/// - Always sets the `face` field of the half edges to `None`.
/// - Sets the `next` field of the half edges to a dummy value. You
/// have to overwrite this value!
/// - Does not set the `outgoing` fields of the vertices.
unsafe fn add_edge_partially(
&mut self,
from: Checked<VertexHandle>,
to: Checked<VertexHandle>,
) -> Checked<HalfEdgeHandle> {
// Of course, wrapping a dummy handle into `Checked` is a bad idea.
// Unfortunately, this is necessary. All code using this method has to
// pay special attention anyway.
let face = Opt::none();
let next = Checked::new(HalfEdgeHandle::new(0));
let prev = Checked::new(HalfEdgeHandle::new(0)).into();
self.half_edges.push(HalfEdge { target: from, face, next, prev });
let out = self.half_edges.push(HalfEdge { target: to, face, next, prev });
Checked::new(out)
}
/// Adds a face defined by the given `vertices`.
///
/// The function works pretty much like `MeshMut::add_face`. The
/// `inner_half_edges` is just some storage this function can use. It is
/// completely overwritten before it is read, so it can (should) be
/// initialized with dummy values. It has to be the same length as
/// `vertices`!
fn add_face_impl<'a>(
&mut self,
vertices: &'a [VertexHandle],
inner_half_edges: &mut [Checked<HalfEdgeHandle>],
) -> FaceHandle {
// Check that all vertices are valid (the handles are referring to
// existing vertices).
for &vh in vertices {
self.check_vertex(vh);
}
// We want to reflect our checks in the type system. Therefore we
// change the type of `vertices` to `&[Checked<VertexHandle>]`. We
// could copy everything into a `Vec`, but that allocates memory and is
// a bit wasteful. Instead, we just reinterpret cast. This is actually
// safe because `VertexHandle` and `Checked<VertexHandle>` have the
// same memory layout, alignment requirements and everything (due to
// `repr(transparent)`).
let vertices = unsafe {
slice::from_raw_parts::<'a>(
vertices.as_ptr() as *const Checked<VertexHandle>,
vertices.len(),
)
};
// ===================================================================
// ===== Find edges between vertices
// ===================================================================
// In this step, we find the inner edges of the new face. If some edges
// are missing, we will add them in an incomplete form (e.g. `next` and
// `outgoing` handles won't be changed anywhere).
//
// We could do this step by simply circulating around each vertex and
// finding the connecting edges that way, but this is often not
// optimal. We want to avoid unnecessary cache misses at all cost. If
// we have found an edge between the previous pair of vertices already,
// we can simply check its `next` handle: it's not unlikely that it is
// already the edge we are looking for. If it's not the edge, we at
// least already have an edge that we can use to circulate around the
// vertex. That way we don't have to check the `outgoing` value of the
// vertex, avoiding one memory access of potentially cold memory.
//
// `inner_half_edges` will store the half edges between the vertices of
// the new face. The half edge at index `i` goes from `vertices[i]` to
// `vertices[(i + 1) % len]]`.
// If in the last iteration of the loop, an edge between the vertices
// was found, it's stored here.
let mut last_edge: Option<Checked<HalfEdgeHandle>> = None;
for vi in 0..vertices.len() {
let from = vertices[vi];
let to = vertices[(vi + 1) % vertices.len()];
let he = if let Some(last_edge) = last_edge {
// We know the edge going from `vertices[i - 1]` to `from`.
// That means we don't have to lookup `from` anymore to get an
// adjacent edge. Furthermore, `last_edge.next` is probably
// already the edge we are looking for!
// TODO: if we do not allow multi-blades we don't have to loop!
// Then the `next` has to be the edge we are looking for or we
// know that the edge does not exist.
// Edge starting at `from`.
let mut outgoing = self[last_edge].next;
loop {
// Check if we have found the edge we are looking for.
if self[outgoing].target == to {
break Some(outgoing);
}
// Check if we reached the starting point again (meaning
// there is no edge from `from` to `to`).
let ingoing = outgoing.twin();
if ingoing == last_edge {
break None;
}
outgoing = self[ingoing].next;
}
} else {
// We have no previous edge, so we have to start at the vertex.
self.he_between(from, to)
};
// Update the last edge
last_edge = he;
// Make sure the half edge we found is not connected to a face
// already. This would mean that we would create a non-manifold
// edge.
if let Some(he) = he {
assert!(self[he].face.is_none(), "{}", NON_MANIFOLD_EDGE_ERR);
}
// This `unsafe` is here because the `next` (and `prev`) field is
// set to a dummy value. We have to make sure to overwrite it
// before we read it. Well, this function's whole completeness is
// based on that fact.
let he = he.unwrap_or_else(|| unsafe { self.add_edge_partially(from, to) });
inner_half_edges[vi] = he;
}
// ===================================================================
// ===== Add face and fix `face` handle of inner edges
// ===================================================================
// Insert new face (it is `Checked` because we just added it).
let new_face = self.faces.push(Face {
edge: inner_half_edges[0], // just an arbitrary edge
});
let new_face = unsafe { Checked::new(new_face) };
// Set the `face` handle of the inner edges.
for he in &*inner_half_edges {
self[*he].face = Opt::some(new_face);
}
// ===================================================================
// ===== Fix `next` handles
// ===================================================================
// This fixes the next handles of the outer three edges plus additional
// edges not adjacent to this face, as necessary. We handle each corner
// seperately.
//
// So for each corner, we have this situation (the corner vertex `v`,
// the new face `F`, the two outer edges `incoming` and `outgoing` and
// we don't yet know what `v` is also connected too):
//
// ?
// ? ?
//
// (v)
// ^/ ^\
// // \\
// incoming // \\ outgoing
// // F \\
// /v \v
// ( ) ------> ( )
// <------
//
// This is difficult in particular, because there can be multiple fan
// blades around the vertex. Here is an example: there are three
// fan-blades around the central vertex X. One fan blade consists of
// two faces, the other two of only one face.
//
//
// o---------o
// \ /
// \ /
// \ /
// \ /
// o---------X---------o
// | ╱ | ╲ |
// | ╱ | ╲ |
// | ╱ | ╲ |
// | ╱ | ╲ |
// o o---------o
//
// The order of fan blades is ambigious. When inserting a new fan
// blade, we do not know where in the cycle to insert it. So we have to
// accept a bit of chaos while multiple blades still exist. But often,
// blades are reconnected (this is the `(true, true)` case below) in
// which case we need to take special care.
for vi in 0..vertices.len() {
let prev_idx = vi.checked_sub(1).unwrap_or(vertices.len() - 1);
let vh = vertices[vi];
let incoming = inner_half_edges[vi].twin();
let outgoing = inner_half_edges[prev_idx].twin();
let v = &self[vh];
let incoming_face = self[incoming].face;
let outgoing_face = self[outgoing].face;
// We have four different cases: it just depends whether incoming
// and/or outgoing are already adjacent to a face.
match (incoming_face.is_some(), outgoing_face.is_some()) {
// Both edge pairs were newly inserted. This is usually easy,
// but it can be a bit tricky when there are other edges (and
// thus a face) connected to that vertex.
(false, false) => {
if let Some(outgoing_from_v) = v.outgoing.into_option() {
// More difficult case: we are creating a multi
// fan-blade vertex here. In order to correctly set the
// `next` handles, we need to find the start of some
// blade and the end of some blade. We will insert the
// new blade between the two.
//
//
//
// ^ ? ? /
// \ /
// start \ ? / end
// \ /
// \ v
// (v)
// ^/ ^\
// // \\
// // \\
// // F \\
// /v \v
// ( ) ( )
//
// TODO: if we have `prev` pointer, we can simplify
// this. Since we know `outgoing_from_v` is a boundary
// half edge, we can use it as `start` and
// `prev(start)` as `end`.
// Find the end edge of some blade.
let end = self.find_incoming_he(
outgoing_from_v.twin(),
|incoming| self[incoming].face.is_none(),
).expect(NON_MANIFOLD_VERTEX_ERR);
// The start of another blade.
let start = self[end].next;
// Insert new blade in between.
set_next_prev!(self, incoming -> start);
set_next_prev!(self, end -> outgoing);
// Regarding the `outgoing` field of `v`: before adding
// this face, it was a boundary half edge. Since we
// didn't add a face adjacent to it, it still is. So we
// can keep it unchanged.
} else {
// This is the easy case: `incoming` and `outgoing` are
// the only edges adjacent to `v`. This also means that
// `v` was isolated before and we now need to set its
// `outgoing` handle.
set_next_prev!(self, incoming -> outgoing);
self[vh].outgoing = Opt::some(outgoing);
}
}
// The incoming edge is adjacent to another face (IF), but the
// outgoing is not. We have to find the edge `before_new` whose
// `next` handle points to `incoming`'s twin (a soon to be
// inner edge of our new face). Because that `next` handle now
// needs to point to `outgoing`.
//
// /
// ? ? /
// ? / before_new
// /
// v
// <-------- (v)
// ^/ ^\
// IF // \\
// // \\
// // F \\
// /v \v
// ( ) ( )
//
// ^-- this face and
// ^-- this edge are new in the cycle
//
(true, false) => {
// TODO: should we rather iterate around the vertex if the
// `prev` point is not stored?
let before_new = self.prev(incoming.twin());
set_next_prev!(self, before_new -> outgoing);
// The half edge `incoming.twin()` might have been
// `v.outgoing`. But this is bad because it's not a
// boundary half edge anymore (which we require). Therefore
// we update it to `outgoing` which is certainly a boundary
// half edge.
self[vh].outgoing = Opt::some(outgoing);
}
// The outgoing edge is adjacent to another face (OF), but the
// incoming is not. This is fairly easy: the twin of outgoing
// points to some edge. The incoming edge just needs to point
// that edge now. The `next` of the outgoing twin will be set
// later (since it's an inner edge of our new face).
//
// ^
// \ ?
// \ ?
// \ ?
// \
// (v)<---------
// ^/ ^\
// // \\ OF
// // \\
// // F \\
// /v \v
// ( ) ( )
//
// ^-- this face and
// ^-- this edge are new in the cycle
//
(false, true) => {
let blade_start = self[outgoing.twin()].next;
set_next_prev!(self, incoming -> blade_start);
// We don't need to update `v.outgoing` here because the
// only old half edge that won't be boundary anymore is
// `outgoing.twin()`. But this is not an outgoing edge for
// `v`.
}
// This can be easy or the ugliest case. The incoming and
// outgoing edge are both adjacent to a face. That means we are
// connecting two fan blades. If the fan blade of `incoming` is
// already directly after the fan blade of `outgoing` (speaking
// about the "circulate around vertex" order), then everything
// is fine.
//
// ?
// ? ?
//
// <-------- (v) <--------
// ^/ ^\
// IF // \\ OF
// // \\
// // F \\
// /v \v
// ( ) ( )
//
// ^-- this face is new,
// the edges already exist
//
// BUT, if that is not the case, we need to change the order of
// fan blades to match the "good" situation described above.
//
// Additionally, we might need to update `v.outgoing` because
// it might have been `incoming.twin()` which is not a boundary
// half edge anymore (after this method).
(true, true) => {
// Find the end of the fan blade "IB". See below for
// explanation of the important fan blades.
//
// TODO: this should always find an edge or else the new
// face would introduce a non-manifold edge. Right?
let ib_end_opt = self.find_incoming_he(
incoming,
|incoming| self[incoming].face.is_none(),
);
if self[outgoing.twin()].next != incoming.twin() {
// Here we need to conceptually delete one fan blade
// from the `next` circle around `v` and re-insert it
// into the right position. We choose to "move" the fan
// blade starting with `incoming` (IB).
//
// We have to deal with four fan blades:
// - IB: the blade containing `incoming` (where
// `incoming.twin()` is its start).
// - OB: the blade containing `outgoing` (where
// `outgoing.twin()` is its end)
// - BIB (before incoming blade): the blade before IB
// - AOB (after outgoing blade): the blade after OB
// (outgoing.twin.next is its start).
//
// Current situation:
//
// ┌────┐ ┌─────┐ ┌─────┐ ┌────┐
// +--> │ OB │ -> │ AOB │ -> ? -> │ BIB │ -> │ IB │ -> ?
// | └────┘ └─────┘ └─────┘ └────┘ |
// +---------------------------------------------------+
//
// TODO: if we have `prev` pointer, we want to say
// `incoming.prev`. If not, however, we want to
// circulate around `v` to find the `bib_end` to avoid
// the worst case of finding the `prev` by walking
// around a huge part of the mesh.
// Find the end half edges of the blades BIB and IB.
let ib_end = ib_end_opt.expect("internal HEM error: cannot find `ib_end`");
let bib_end = self.prev(incoming.twin());
// Here we remove the "incoming blade" from the cycle.
// Situation after this assignment:
//
// ┌────┐
// │ IB │ -------+
// └────┘ |
// v
// ┌────┐ ┌─────┐ ┌─────┐
// +--> │ OB │ -> │ AOB │ -> ? -> │ BIB │ -----> ?
// | └────┘ └─────┘ └─────┘ |
// +---------------------------------------------+
//
let after_ib = self[ib_end].next;
set_next_prev!(self, bib_end -> after_ib);
// Now we reinsert it again, right after the "outgoing
// blade". Situation after assignment:
//
//
// ┌────┐
// │ IB │ ------+
// └────┘ |
// v
// ┌────┐ ┌─────┐ ┌─────┐
// +--> │ OB │ -> │ AOB │ -> ? -> │ BIB │ -----> ?
// | └────┘ └─────┘ └─────┘ |
// +---------------------------------------------+
//
let aob_start = self[outgoing.twin()].next;
set_next_prev!(self, ib_end -> aob_start);
// Right now, the cycle is still a bit broken, but that
// doesn't matter, because (a) the cycle will be
// repaired by setting the `next` link of the inner
// edges below, and (b) the broken cycle won't be
// accessed (in this direction) before it is repaired.
// To update `v.outgoing`, we luckily already know a
// boundary outgoing half edge of `v`: it's the start
// of AOB.
self[vh].outgoing = Opt::some(aob_start);
} else {
// The order of fan blades around the vertex is fine,
// but we might need to update `v.outgoing`. To do
// that, we try to find the end of IB. Its `next` half
// edge is the start of the next blade (which is an
// outgoing edge). However, we might not find the end
// of that blade because there might only be one blade
// left. In that case, we don't update `outgoing`
// because it can be an arbitrary half edge in that
// case (the vertex won't be boundary anymore after
// this method call).
if let Some(ib_end) = ib_end_opt {
let new_outgoing = self[ib_end].next;
self[vh].outgoing = Opt::some(new_outgoing);
}
}
}
}
}
// Now we only need to set the `next` handles of the inner half edges.
// This is easy.
for he_i in 0..inner_half_edges.len() {
let curr = inner_half_edges[he_i];
let next = inner_half_edges[(he_i + 1) % inner_half_edges.len()];
set_next_prev!(self, curr -> next);
}
*new_face
}
}
macro_rules! impl_index {
($handle:ident, $field:ident, |$c:ident| $out:ty) => {
impl<$c: Config> ops::Index<Checked<$handle>> for HalfEdgeMesh<$c> {
type Output = $out;
#[inline(always)]
fn index(&self, idx: Checked<$handle>) -> &Self::Output {
// &self.$field[*idx]
unsafe { self.$field.get_unchecked(*idx) }
}
}
impl<$c: Config> ops::IndexMut<Checked<$handle>> for HalfEdgeMesh<$c> {
#[inline(always)]
fn index_mut(&mut self, idx: Checked<$handle>) -> &mut Self::Output {
// &mut self.$field[*idx]
unsafe { self.$field.get_unchecked_mut(*idx) }
}
}
}
}
impl_index!(VertexHandle, vertices, |C| Vertex);
impl_index!(FaceHandle, faces, |C| Face);
impl_index!(HalfEdgeHandle, half_edges, |C| HalfEdge<C>);
// ===============================================================================================
// ===== Mesh trait implementations
// ===============================================================================================
impl<C: Config> Mesh for HalfEdgeMesh<C> {
type FaceKind = C::FaceKind;
type Orientable = True;
fn num_vertices(&self) -> hsize {
self.vertices.num_elements()
}
fn next_vertex_handle_from(&self, start: VertexHandle) -> Option<VertexHandle> {
// TODO: optimize
(start.idx()..self.vertices.next_push_handle().idx())
.map(VertexHandle::new)
.find(|&vh| self.vertices.contains_handle(vh))
}
fn next_face_handle_from(&self, start: FaceHandle) -> Option<FaceHandle> {
// TODO: optimize
(start.idx()..self.faces.next_push_handle().idx())
.map(FaceHandle::new)
.find(|&fh| self.faces.contains_handle(fh))
}
fn last_vertex_handle(&self) -> Option<VertexHandle> {
self.vertices.last_handle()
}
fn last_face_handle(&self) -> Option<FaceHandle> {
self.faces.last_handle()
}
fn contains_vertex(&self, vertex: VertexHandle) -> bool {
self.vertices.contains_handle(vertex)
}
fn num_faces(&self) -> hsize {
self.faces.num_elements()
}
fn contains_face(&self, face: FaceHandle) -> bool {