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
use core::slice;
use std::ops::Deref;

use glam::Vec2;
use slotmap::{secondary::Iter, SecondaryMap};
use smallvec::SmallVec;

use crate::{util::face_intersect, BSPTree, Face, NodeIndex, Portal, PortalRef, Side, TOLERANCE};

#[derive(Copy, Debug, Clone, PartialEq)]
#[doc(hidden)]
pub struct ClippedFace {
    face: Face,
    // Used to determine if a face is completely inside
    pub(crate) sides: [Side; 2],

    pub src: NodeIndex,
    pub dst: NodeIndex,
}

impl ClippedFace {
    pub fn new(vertices: [Vec2; 2], sides: [Side; 2], src: NodeIndex, dst: NodeIndex) -> Self {
        Self {
            face: Face::new(vertices),
            sides,
            src,
            dst,
        }
    }

    pub(crate) fn split_nondestructive(&self, p: Vec2, normal: Vec2) -> [Self; 2] {
        let intersection = face_intersect(self.into_tuple(), p, normal);
        let a = (self.vertices[0] - p).dot(normal);

        // a is in front
        if a >= -TOLERANCE {
            [
                Self::new(
                    [self.vertices[0], intersection.point],
                    [Side::Front, Side::Front],
                    self.src,
                    self.dst,
                ),
                Self::new(
                    [intersection.point, self.vertices[1]],
                    [Side::Front, Side::Front],
                    self.src,
                    self.dst,
                ),
            ]
        } else {
            // a is behind
            [
                Self::new(
                    [intersection.point, self.vertices[1]],
                    [Side::Front, Side::Front],
                    self.src,
                    self.dst,
                ),
                Self::new(
                    [self.vertices[0], intersection.point],
                    [Side::Front, Side::Front],
                    self.src,
                    self.dst,
                ),
            ]
        }
    }

    /// Split the face. The first face is in front
    pub(crate) fn split(&self, p: Vec2, normal: Vec2, double_planar: bool) -> [Self; 2] {
        let intersection = face_intersect(self.into_tuple(), p, normal);
        let a = (self.vertices[0] - p).dot(normal);

        let front = if double_planar {
            Side::Back
        } else {
            Side::Front
        };

        // a is in front
        if a >= -TOLERANCE {
            [
                Self::new(
                    [self.vertices[0], intersection.point],
                    [self.sides[0], front],
                    self.src,
                    self.dst,
                ),
                Self::new(
                    [intersection.point, self.vertices[1]],
                    [Side::Back, self.sides[1]],
                    self.src,
                    self.dst,
                ),
            ]
        } else {
            // a is behind
            [
                Self::new(
                    [intersection.point, self.vertices[1]],
                    [front, self.sides[1]],
                    self.src,
                    self.dst,
                ),
                Self::new(
                    [self.vertices[0], intersection.point],
                    [self.sides[0], Side::Back],
                    self.src,
                    self.dst,
                ),
            ]
        }
    }

    /// Get the portal's src.
    pub fn src(&self) -> NodeIndex {
        self.src
    }

    /// Get the portal's dst.
    pub fn dst(&self) -> NodeIndex {
        self.dst
    }

    /// Get the portal's sides.
    pub fn sides(&self) -> [Side; 2] {
        self.sides
    }

    /// Get the clipped face's face.
    pub fn face(&self) -> Face {
        self.face
    }
}

impl Deref for ClippedFace {
    type Target = Face;

    fn deref(&self) -> &Self::Target {
        &self.face
    }
}

type NodePortals = SmallVec<[PortalRef; 4]>;

/// Declares portals which are surfaces connecting two partitioning planes,
/// [crate::BSPNode].
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct Portals {
    inner: SecondaryMap<NodeIndex, NodePortals>,
    faces: Vec<Face>,
}

impl Portals {
    pub fn new() -> Self {
        Self {
            inner: SecondaryMap::new(),
            faces: Vec::new(),
        }
    }

    pub fn generate(&mut self, tree: &BSPTree) {
        self.extend(tree.generate_portals())
    }

    /// Adds a new portal for both src and dst
    pub fn push(&mut self, portal: ClippedFace) {
        let face = self.faces.len();
        self.faces.push(portal.face);

        assert_ne!(portal.src, portal.dst);

        self.inner
            .entry(portal.src)
            .expect("Node was removed")
            .or_default()
            .push(PortalRef {
                dst: portal.dst,
                src: portal.src,
                normal: -portal.normal(),
                face,
            });
        self.inner
            .entry(portal.dst)
            .expect("Node was removed")
            .or_default()
            .push(PortalRef {
                dst: portal.src,
                src: portal.dst,
                normal: portal.normal(),
                face,
            });
    }

    pub fn get(&self, index: NodeIndex) -> PortalIter {
        PortalIter {
            faces: &self.faces,
            iter: self
                .inner
                .get(index)
                .map(|val| val.as_ref())
                .unwrap_or_default()
                .iter(),
        }
    }

    pub fn iter(&self) -> PortalsIter {
        PortalsIter {
            faces: &self.faces,
            inner: self.inner.iter(),
        }
    }

    pub fn from_ref(&self, portal: PortalRef) -> Portal {
        Portal {
            face: &self.faces[portal.face],
            portal_ref: portal,
        }
    }
}

#[doc(hidden)]
pub struct PortalIter<'a> {
    faces: &'a [Face],
    iter: slice::Iter<'a, PortalRef>,
}

impl<'a> Iterator for PortalIter<'a> {
    type Item = Portal<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let portal = self.iter.next()?;

        Some(Portal {
            face: &self.faces[portal.face],
            portal_ref: *portal,
        })
    }
}

impl<'a> IntoIterator for &'a Portals {
    type Item = PortalIter<'a>;

    type IntoIter = PortalsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[doc(hidden)]
pub struct PortalsIter<'a> {
    faces: &'a [Face],
    inner: Iter<'a, NodeIndex, NodePortals>,
}

impl<'a> Iterator for PortalsIter<'a> {
    type Item = PortalIter<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let (_, portals) = self.inner.next()?;
        Some(PortalIter {
            faces: self.faces,
            iter: portals.iter(),
        })
    }
}

impl Default for Portals {
    fn default() -> Self {
        Self::new()
    }
}

impl Extend<ClippedFace> for Portals {
    fn extend<T: IntoIterator<Item = ClippedFace>>(&mut self, iter: T) {
        let iter = iter.into_iter();
        let cap = self.inner.len() + iter.size_hint().0;

        self.inner.set_capacity(cap);
        iter.for_each(|val| self.push(val))
    }
}