aboutsummaryrefslogtreecommitdiff
path: root/src/obj_import.rs
blob: 339c502ddc816cc51475be8f6dc9f0460687cff5 (plain)
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
use crate::*;
pub use obj;
use obj::raw::object::RawObj;

#[derive(Debug, Error)]
pub enum ObjImportError {
    #[error("vertex {0} position index out of bounds")]
    InvalidPositionIndex(usize),
    #[error("half-edge between vertices {0} and {1} appears twice")]
    SameHalfEdge(usize, usize),
    #[error("half-edge between vertices {0} and {1} does not have a twin")]
    UnclaimedHalfEdge(usize, usize),
    #[error("empty face")]
    EmptyFace,
    #[error("vertex {0} is not connected to any edges")]
    StandaloneVertex(usize),
}

use ObjImportError::*;

pub struct ObjImport<'tok, 'brand, 'arena, V> {
    dcel: &'tok mut Dcel<'brand, 'arena, V>,
    obj: &'tok RawObj,
    shell: ptr!(Shell),
    half_edges: HashMap<(usize, usize), Option<ptr!(HalfEdge)>>,
    vertices: Vec<ptr!(Vertex)>,
}

struct CyclicWindows<T, I> {
    first: Option<T>,
    last: Option<T>,
    iter: I,
}

fn cyclic_windows<T, I>(iter: I) -> CyclicWindows<T, I> {
    CyclicWindows {
        first: None,
        last: None,
        iter,
    }
}

impl<T, I> Iterator for CyclicWindows<T, I>
where
    T: Clone,
    I: Iterator<Item = T>,
{
    type Item = (T, T);

    fn next(&mut self) -> Option<Self::Item> {
        let Some(item) = self.iter.next() else {
            let first = self.first.take()?;
            let last = self.last.take()?;
            return Some((last, first));
        };

        self.first.get_or_insert_with(|| item.clone());
        let Some(last) = self.last.replace(item.clone()) else {
            return self.next();
        };

        Some((last, item))
    }
}

impl<'tok, 'brand, 'arena, V> ObjImport<'tok, 'brand, 'arena, V> {
    pub fn import(
        dcel: &'tok mut Dcel<'brand, 'arena, V>,
        obj: &'tok RawObj,
        fun: impl Fn((f32, f32, f32, f32)) -> V,
    ) -> Result<own!(Body), ObjImportError> {
        let body = dcel.new_body();
        let shell = *body.add_new_shell(dcel);

        let vertices = obj
            .positions
            .iter()
            .map(|&x| *shell.add_new_vertex(fun(x), dcel))
            .collect();

        let mut imp = ObjImport {
            dcel,
            obj,
            shell,
            half_edges: HashMap::new(),
            vertices,
        };

        match imp.import_faces() {
            Ok(_) => Ok(body),
            Err(x) => {
                body.destroy(dcel);
                Err(x)
            }
        }
    }

    fn iter_polygon(p: &obj::raw::object::Polygon) -> impl DoubleEndedIterator<Item = usize> + '_ {
        use either::{Left, Right};
        use obj::raw::object::Polygon::*;

        match p {
            P(v) => Left(Left(v.iter().cloned())),
            PT(v) => Left(Right(v.iter().map(|&(x, _)| x))),
            PN(v) => Right(Left(v.iter().map(|&(x, _)| x))),
            PTN(v) => Right(Right(v.iter().map(|&(x, _, _)| x))),
        }
    }

    fn import_faces(&mut self) -> Result<(), ObjImportError> {
        for p in self.obj.polygons.iter() {
            if cyclic_windows(Self::iter_polygon(p))
                .any(|(a, b)| matches!(self.half_edges.get(&(a, b)), Some(None)))
            {
                self.import_face(Self::iter_polygon(p).rev())?;
            } else {
                self.import_face(Self::iter_polygon(p))?;
            }
        }

        if let Some((k, _)) = self.half_edges.iter().find(|(_, v)| v.is_some()) {
            Err(UnclaimedHalfEdge(k.1 + 1, k.0 + 1))
        } else if let Some((i, _)) = self
            .vertices
            .iter()
            .enumerate()
            .find(|(_, x)| x.maybe_outgoing(self.dcel).is_none())
        {
            Err(StandaloneVertex(i + 1))
        } else {
            Ok(())
        }
    }

    fn add_half_edge(
        &mut self,
        loop_: ptr!(Loop),
        prev: Option<ptr!(HalfEdge)>,
        vertices: [usize; 2],
    ) -> Result<ptr!(HalfEdge), ObjImportError> {
        use std::collections::hash_map::Entry::*;

        let [a, b] = vertices;
        let v = *self.vertices.get(a).ok_or(InvalidPositionIndex(a + 1))?;

        let he = match self.half_edges.entry((a, b)) {
            Occupied(mut e) => e.get_mut().take().ok_or(SameHalfEdge(a + 1, b + 1))?,
            Vacant(e) => {
                let (_, [he1, he2]) = Edge::create(self.shell, self.dcel);
                e.insert(None);
                self.half_edges.insert((b, a), Some(he2));
                he1
            }
        };

        he.update_origin(v, self.dcel);
        he.set_loop_(loop_, self.dcel);

        if let Some(prev) = prev {
            self.dcel.follow(prev, he);
        }

        Ok(he)
    }

    fn import_face(&mut self, mut it: impl Iterator<Item = usize>) -> Result<(), ObjImportError> {
        let face = *self.shell.add_new_face(self.dcel);
        let loop_ = *Loop::new(self.dcel);
        loop_.set_face(face, self.dcel);
        face.set_outer_loop(loop_, self.dcel);

        let fv = it.next().ok_or(EmptyFace)?;
        let (fe, le, lv) = it.try_fold((None, None, fv), |(fe, le, a), b| {
            let he = self.add_half_edge(loop_, le, [a, b])?;
            Ok((fe.or(Some(he)), Some(he), b))
        })?;

        let fe = fe.ok_or(EmptyFace)?;
        let le = self.add_half_edge(loop_, le, [lv, fv])?;
        self.dcel.follow(le, fe);

        loop_.set_half_edges(fe, self.dcel);

        Ok(())
    }
}