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

//!
//! An index based half-edge mesh implementation.
//!

use std::fmt;


/// An interface for asserting the validity of components in the mesh.
pub trait Validation {
    /// A general blanket test for validity
    fn is_valid(&self) -> bool;
}


/// Our default value for uninitialized or unconnected components in the mesh.
pub const INVALID_COMPONENT_INDEX: usize = 0;

/// Type alias for indices into vertex storage
pub type VertexIndex = usize;

/// Type alias for indices into vertex attribute storage
pub type VertexAttributeIndex = usize;

/// Type alias for indices into edge storage
pub type EdgeIndex = usize;

/// Type alias for indices into face storage
pub type FaceIndex = usize;


/// Represents the point where two edges meet.
#[derive(Default, Debug)]
pub struct Vertex {
    /// Index of the outgoing edge
    pub edge_index: EdgeIndex,
    /// Index of this vertex's attributes
    pub attr_index: VertexAttributeIndex,
}

impl Vertex {
    pub fn new(edge_index: EdgeIndex) -> Vertex {
        Vertex {
            edge_index: edge_index,
            attr_index: INVALID_COMPONENT_INDEX
        }
    }
}

impl Validation for Vertex {
    /// A vertex is considered "valid" as long as it as an edge index
    /// other than `INVALID_COMPONENT_INDEX`
    fn is_valid(&self) -> bool {
        self.edge_index != INVALID_COMPONENT_INDEX /*&&
            self.attr_index != INVALID_COMPONENT_INDEX*/
    }
}


/// The principle component in a half-edge mesh.
#[derive(Default, Debug)]
pub struct Edge {
    /// The adjacent or 'twin' half-edge
    pub twin_index: EdgeIndex,
    /// The index of the next edge in the loop
    pub next_index: EdgeIndex,
    /// The index of the previous edge in the loop
    pub prev_index: EdgeIndex,

    /// The index of the face this edge loop defines
    pub face_index: FaceIndex,

    /// The index of the Vertex for this edge.
    pub vertex_index: VertexIndex,
}

impl Validation for Edge {
    /// An edge is generally considered "valid" as long as it has a
    /// vertex and a face index other than `INVALID_COMPONENT_INDEX`
    fn is_valid(&self) -> bool {
        self.vertex_index != INVALID_COMPONENT_INDEX &&
            self.face_index != INVALID_COMPONENT_INDEX
    }
}


/// A face is defined by the looping connectivity of edges.
#[derive(Default, Debug)]
pub struct Face {
    /// The "root" of an edge loop that defines this face.
    pub edge_index: EdgeIndex,
}

impl Face {
    pub fn new(edge_index: EdgeIndex) -> Face {
        Face {
            edge_index
        }
    }
}

impl Validation for Face {
    /// A face is considered "valid" as long as it has an edge index
    /// other than `INVALID_COMPONENT_INDEX`
    fn is_valid(&self) -> bool {
        self.edge_index != INVALID_COMPONENT_INDEX
    }
}

/// Function set for operations related to the Face struct
#[derive(Debug)]
pub struct FaceFn<'mesh> {
    mesh: &'mesh Mesh,
    face: &'mesh Face,
    pub index: FaceIndex
}

impl<'mesh> FaceFn<'mesh> {

    pub fn new(index: FaceIndex, mesh: &'mesh Mesh) -> FaceFn {
        FaceFn {
            mesh: mesh,
            face: mesh.face(index),
            index: index
        }
    }

    /// Convert this `FaceFn` to an `EdgeFn`.
    pub fn edge(self) -> EdgeFn<'mesh> {
        EdgeFn::new(self.face.edge_index, self.mesh)
    }
}

/// Function set for operations related to the Vertex struct
#[derive(Debug)]
pub struct VertexFn<'mesh> {
    mesh: &'mesh Mesh,
    vertex: &'mesh Vertex,
    pub index: VertexIndex
}

impl<'mesh> VertexFn<'mesh> {

    pub fn new(index: VertexIndex, mesh: &'mesh Mesh) -> VertexFn {
        VertexFn {
            mesh: mesh,
            vertex: mesh.vertex(index),
            index: index
        }
    }

    /// Convert this `VertexFn` to an `EdgeFn`
    pub fn edge(self) -> EdgeFn<'mesh> {
        EdgeFn::new(self.vertex.edge_index, self.mesh)
    }
}

/// Function set for operations related to the Edge struct
#[derive(Debug)]
pub struct EdgeFn<'mesh> {
    mesh: &'mesh Mesh,
    edge: &'mesh Edge,
    pub index: EdgeIndex
}

impl<'mesh> EdgeFn<'mesh> {
    pub fn new(index: EdgeIndex, mesh: &'mesh Mesh) -> EdgeFn {
        EdgeFn {
            mesh: mesh,
            edge: mesh.edge(index),
            index: index
        }
    }

    /// Convert this `EdgeFn` to an `EdgeFn` of it's next edge
    pub fn next(self) -> EdgeFn<'mesh> {
        EdgeFn::new(self.edge.next_index, self.mesh)
    }

    /// Convert this `EdgeFn` to an `EdgeFn` of it's prev edge
    pub fn prev(self) -> EdgeFn<'mesh> {
        EdgeFn::new(self.edge.prev_index, self.mesh)
    }

    /// Convert this `EdgeFn` to an `EdgeFn` of it's twin edge
    pub fn twin(self) -> EdgeFn<'mesh> {
        EdgeFn::new(self.edge.twin_index, self.mesh)
    }

    /// Convert this `EdgeFn` to an `FaceFn`
    pub fn face(self) -> FaceFn<'mesh> {
        FaceFn::new(self.edge.face_index, self.mesh)
    }

    /// Convert this `EdgeFn` to an `VertexFn`
    pub fn vertex(self) -> VertexFn<'mesh> {
        VertexFn::new(self.edge.vertex_index, self.mesh)
    }
}

/// Implements the fundamental storage operations and represents the principle
/// grouping of all components.
pub struct Mesh {
    pub edge_list: Vec<Edge>,
    pub vertex_list: Vec<Vertex>,
    pub face_list: Vec<Face>
}

impl fmt::Debug for Mesh {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Half-Edge Mesh {{ {} vertices, {} edges, {} faces }}",
               self.vertex_list.len(), self.edge_list.len(), self.face_list.len())
    }
}

impl Mesh {
    /// Creates a new Mesh with an initial component added to each Vec.
    ///
    /// The idea behind having a single invalid component at the front of each
    /// Vec comes from the blog http://ourmachinery.com/post/defaulting-to-zero/
    pub fn new() -> Mesh {
        Mesh {
            edge_list: vec! [
                Edge::default()
            ],
            vertex_list: vec! [
                Vertex::default()
            ],
            face_list: vec! [
                Face::default()
            ]
        }
    }

    /// Mark the two edges as adjacent twins.
    ///
    /// In order for this to be valid each edge should be connected in such a way
    /// that the vertex of each is the same as the vertex of the next edge of each.
    ///
    /// So: `A->Next->Vertex == B->Vertex` && `B->Next->Vertex == A->Vertex`
    ///
    /// _In debug builds we assert the provided indices are valid._
    pub fn set_twin_edges(&mut self, e1: EdgeIndex, e2: EdgeIndex) {
        debug_assert!(e1 != INVALID_COMPONENT_INDEX);
        debug_assert!(e2 != INVALID_COMPONENT_INDEX);
        // TODO: Disabling this for the moment because it would prevent the use
        //       of the `edge_from_twin` method.
        // debug_assert! {
        //     self.edge(e1).vertex_index == self.edge( self.edge(e2).next_index ).vertex_index
        // };
        // debug_assert! {
        //     self.edge(e2).vertex_index == self.edge( self.edge(e1).next_index ).vertex_index
        // };
        if let Some(ref mut edge1) = self.edge_mut(e1) {
            edge1.twin_index = e2;
        }
        if let Some(ref mut edge2) = self.edge_mut(e2) {
            edge2.twin_index = e1;
        }
    }

    /// Connects the two edges as part of an edge loop.
    ///
    /// _In debug builds we assert that neither index is not the default index._
    pub fn connect_edges(&mut self, prev: EdgeIndex, next: EdgeIndex) {
        debug_assert!(prev != INVALID_COMPONENT_INDEX);
        debug_assert!(next != INVALID_COMPONENT_INDEX);
        if let Some(ref mut prev_edge) = self.edge_mut(prev) {
            prev_edge.next_index = next;
        }
        if let Some(ref mut next_edge) = self.edge_mut(next) {
            next_edge.prev_index = prev;
        }
    }

    /// Create a new edge from the specified vertex.
    ///
    /// _In debug builds we assert that the vertex index is not the default index._
    pub fn edge_from_vertex(&mut self, vert: VertexIndex) -> EdgeIndex {
        debug_assert!(vert != INVALID_COMPONENT_INDEX);
        self.add_edge(Edge {
            twin_index: INVALID_COMPONENT_INDEX,
            next_index: INVALID_COMPONENT_INDEX,
            prev_index: INVALID_COMPONENT_INDEX,
            face_index: INVALID_COMPONENT_INDEX,
            vertex_index: vert
        })
    }

    /// Create a new edge as a twin of the specified edge
    ///
    /// _In debug builds we assert that the twin index is not the default index
    /// and that the twins next index is not the default index (since we need
    /// that edge to find the correct vertex index)._
    pub fn edge_from_twin(&mut self, twin: EdgeIndex) -> EdgeIndex {
        debug_assert!(twin != INVALID_COMPONENT_INDEX);
        debug_assert!(self.edge(twin).next_index != INVALID_COMPONENT_INDEX);
        let vert = self.edge( self.edge(twin).next_index ).vertex_index;
        let result = self.edge_from_vertex(vert);
        self.set_twin_edges(result, twin);
        return result;
    }

    /// Create a new edge connected to the previous edge specified.
    ///
    /// _In debug builds we assert that the indices specified are valid._
    pub fn extend_edge_loop(&mut self, vert: VertexIndex, prev: EdgeIndex) -> EdgeIndex {
        debug_assert!(vert != INVALID_COMPONENT_INDEX);
        debug_assert!(prev != INVALID_COMPONENT_INDEX);
        let result = match vert {
            INVALID_COMPONENT_INDEX => {
                debug_assert!(self.edge(prev).twin_index != INVALID_COMPONENT_INDEX);
                let vert = self.edge( self.edge(prev).twin_index ).vertex_index;
                self.edge_from_vertex(vert)
            },
            _ => self.edge_from_vertex(vert)
        };
        self.connect_edges(prev, result);
        return result;
    }

    /// Create a new edge, closing an edge loop, using the `prev` and `next` indices provided.
    ///
    /// _In debug builds we assert that all specified indices are valid._
    pub fn close_edge_loop(&mut self, vert: VertexIndex, prev: EdgeIndex, next: EdgeIndex) -> EdgeIndex {
        debug_assert! {
            vert != INVALID_COMPONENT_INDEX &&
                prev != INVALID_COMPONENT_INDEX &&
                next != INVALID_COMPONENT_INDEX
        };
        let result = self.edge_from_vertex(vert);
        self.connect_edges(prev, result);
        self.connect_edges(result, next);
        return result;
    }

    /// Adds the provided `Edge` to the mesh and returns it's `EdgeIndex`
    pub fn add_edge(&mut self, edge: Edge) -> EdgeIndex {
        let result: EdgeIndex = self.edge_list.len();
        self.edge_list.push(edge);
        debug_assert!(result != INVALID_COMPONENT_INDEX);
        return result;
    }

    /// Adds the provided `Vertex` to the mesh and returns it's `VertexIndex`
    pub fn add_vertex(&mut self, vert: Vertex) -> VertexIndex {
        let result: VertexIndex = self.vertex_list.len();
        self.vertex_list.push(vert);
        debug_assert!(result != INVALID_COMPONENT_INDEX);
        return result;
    }

    /// Creates a new face and associated edges with the given vertex indices.
    /// Returns the index of the newly added face.
    ///
    /// _In debug builds we assert that all provided indices are valid._
    pub fn add_triangle(&mut self, a: VertexIndex, b: VertexIndex, c: VertexIndex) -> FaceIndex {
        debug_assert! {
            a != INVALID_COMPONENT_INDEX &&
                b != INVALID_COMPONENT_INDEX &&
                c != INVALID_COMPONENT_INDEX
        };
        let result: FaceIndex = self.face_list.len();

        let e1 = self.edge_from_vertex(a);
        let e2 = self.extend_edge_loop(b, e1);
        let e3 = self.close_edge_loop(c, e2, e1);

        self.edge_mut(e1).map(|e| e.face_index = result);
        self.edge_mut(e2).map(|e| e.face_index = result);
        self.edge_mut(e3).map(|e| e.face_index = result);

        self.face_list.push(Face::new(e1));

        return result;
    }

    /// Creates a new face and associated edges with the given a vertex index and a twin edge index.
    /// Returns the index of the newly added face.
    ///
    /// _In debug builds we assert that the all provided indices are valid._
    pub fn add_adjacent_triangle(&mut self, c: VertexIndex, twin_edge: EdgeIndex) -> FaceIndex {
        debug_assert!(c != INVALID_COMPONENT_INDEX);
        debug_assert!(twin_edge != INVALID_COMPONENT_INDEX);
        let result: FaceIndex = self.face_list.len();

        let e1 = self.edge_from_twin(twin_edge);
        let b = self.edge(twin_edge).vertex_index;
        let e2 = self.extend_edge_loop(b, e1);
        let e3 = self.close_edge_loop(c, e2, e1);

        self.edge_mut(e1).map(|e| e.face_index = result);
        self.edge_mut(e2).map(|e| e.face_index = result);
        self.edge_mut(e3).map(|e| e.face_index = result);

        self.face_list.push(Face::new(e1));

        return result;
    }

    /// Returns a `Faces` iterator for this mesh.
    ///
    /// ```
    /// let mesh = hedge::Mesh::new();
    /// for index in mesh.faces() {
    ///    let face = mesh.face(index);
    /// }
    /// ```
    pub fn faces(&self) -> Faces {
        Faces::new(self.face_list.len())
    }

    /// Returns an `EdgeLoop` iterator for the edges around the specified face.
    ///
    /// ```
    /// let mesh = hedge::Mesh::new();
    /// for findex in mesh.faces() {
    ///    let face = mesh.face(findex);
    ///    for eindex in mesh.edges(face) {
    ///        let edge = mesh.edge(eindex);
    ///    }
    /// }
    /// ```
    pub fn edges(&self, face: &Face) -> EdgeLoop {
        EdgeLoop::new(face.edge_index, &self.edge_list)
    }

    /// Returns an `EdgeLoopVertices` iterator for the vertices around the specified face.
    ///
    /// ```
    /// let mesh = hedge::Mesh::new();
    /// for findex in mesh.faces() {
    ///    let face = mesh.face(findex);
    ///    for vindex in mesh.vertices(face) {
    ///        let vertex = mesh.vertex(vindex);
    ///    }
    /// }
    /// ```
    pub fn vertices(&self, face: &Face) -> EdgeLoopVertices {
        EdgeLoopVertices::new(face.edge_index, &self.edge_list)
    }

    pub fn face(&self, index: FaceIndex) -> &Face {
        if let Some(result) = self.face_list.get(index) {
            result
        } else {
            &self.face_list[0]
        }
    }

    /// Returns a `FaceFn` for the given index.
    ///
    /// ```
    /// use hedge::{Mesh, Vertex};
    /// let mut mesh = Mesh::new();
    ///
    /// let v1 = mesh.add_vertex(Vertex::default());
    /// let v2 = mesh.add_vertex(Vertex::default());
    /// let v3 = mesh.add_vertex(Vertex::default());
    ///
    /// let f1 = mesh.add_triangle(v1, v2, v3);
    ///
    /// assert!(mesh.face_fn(f1).edge().next().vertex().index == v2);
    /// ```
    pub fn face_fn(&self, index: FaceIndex) -> FaceFn {
        FaceFn::new(index, &self)
    }

    /// Obtains a mutable reference to the `Face` for the provided index.
    pub fn face_mut(&mut self, index: FaceIndex) -> Option<&mut Face> {
        if index == INVALID_COMPONENT_INDEX {
            None
        } else {
            self.face_list.get_mut(index)
        }
    }

    pub fn edge(&self, index: EdgeIndex) -> &Edge {
        if let Some(result) = self.edge_list.get(index) {
            result
        } else {
            &self.edge_list[0]
        }
    }

    /// Returns an `EdgeFn` for the given index.
    pub fn edge_fn(&self, index: EdgeIndex) -> EdgeFn {
        EdgeFn::new(index, &self)
    }

    /// Obtains a mutable reference to the `Edge` for the provided index.
    pub fn edge_mut(&mut self, index: EdgeIndex) -> Option<&mut Edge> {
        if index == INVALID_COMPONENT_INDEX {
            None
        } else {
            self.edge_list.get_mut(index)
        }
    }

    pub fn vertex(&self, index: VertexIndex) -> &Vertex {
        if let Some(result) = self.vertex_list.get(index) {
            result
        } else {
            &self.vertex_list[0]
        }
    }

    /// Returns a `VertexFn` for the given index.
    pub fn vertex_fn(&self, index: VertexIndex) -> VertexFn {
        VertexFn::new(index, &self)
    }

    /// Obtains a mutable reference to the `Vertex` for the provided index.
    pub fn vertex_mut(&mut self, index: VertexIndex) -> Option<&mut Vertex> {
        if index == INVALID_COMPONENT_INDEX {
            None
        } else {
            self.vertex_list.get_mut(index)
        }
    }
}

/// An iterator that walks an edge loop around a face returning each `VertexIndex` in the loop.
// yeah yeah yeah, I know this is copypasta...
pub struct EdgeLoopVertices<'mesh> {
    edge_list: &'mesh Vec<Edge>,
    initial_index: EdgeIndex,
    current_index: EdgeIndex
}

impl<'mesh> EdgeLoopVertices<'mesh> {
    pub fn new(index: EdgeIndex, edge_list: &'mesh Vec<Edge>) -> EdgeLoopVertices {
        EdgeLoopVertices {
            edge_list: edge_list,
            initial_index: index,
            current_index: INVALID_COMPONENT_INDEX
        }
    }
}

impl<'mesh> Iterator for EdgeLoopVertices<'mesh> {
    type Item = VertexIndex;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current_index == INVALID_COMPONENT_INDEX {
            self.current_index = self.initial_index;
            Some(self.current_index)
        } else {
            self.edge_list.get(self.current_index)
                .and_then(|last_edge| {
                    self.current_index = last_edge.next_index;
                    if self.current_index == self.initial_index {
                        None
                    } else {
                        self.edge_list.get(self.current_index)
                            .map(|current_edge| current_edge.vertex_index)
                    }
                })
        }
    }
}

/// An iterator that walks an edge loop around a face returning each `EdgeIndex` in the loop.
pub struct EdgeLoop<'mesh> {
    edge_list: &'mesh Vec<Edge>,
    initial_index: EdgeIndex,
    current_index: EdgeIndex
}

impl<'mesh> EdgeLoop<'mesh> {
    pub fn new(index: EdgeIndex, edge_list: &'mesh Vec<Edge>) -> EdgeLoop {
        EdgeLoop {
            edge_list: edge_list,
            initial_index: index,
            current_index: INVALID_COMPONENT_INDEX
        }
    }
}

impl<'mesh> Iterator for EdgeLoop<'mesh> {
    type Item = EdgeIndex;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current_index == INVALID_COMPONENT_INDEX {
            self.current_index = self.initial_index;
            Some(self.current_index)
        } else {
            self.edge_list.get(self.current_index).and_then(|current_edge| {
                self.current_index = current_edge.next_index;
                if self.current_index == self.initial_index {
                    None
                } else {
                    Some(self.current_index)
                }
            })
        }
    }
}

/// An iterator that returns the `FaceIndex` of every Face in the mesh.
///
/// Currently this does not iterate using connectivity information but will
/// perhaps do this in the future.
pub struct Faces {
    face_count: usize,
    previous_index: FaceIndex
}

impl Faces {
    pub fn new(face_count: usize) -> Faces {
        Faces {
            face_count: face_count,
            previous_index: 0
        }
    }
}

// TODO: iterate over faces based on connectivity?
impl Iterator for Faces {
    type Item = FaceIndex;

    fn next(&mut self) -> Option<Self::Item> {
        self.previous_index += 1;
        if self.previous_index >= self.face_count {
            None
        } else {
            Some(self.previous_index)
        }
    }
}


#[cfg(test)]
mod tests;