aboutsummaryrefslogtreecommitdiff
path: root/src/geometry/wquadtree.rs
blob: 4e3bf5469de2bc5a4348d9851d0338e19e1ddd41 (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
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
use crate::geometry::{ColliderHandle, ColliderSet, Ray, AABB};
use crate::geometry::{WRay, WAABB};
use crate::math::{Point, Vector};
use crate::simd::{SimdFloat, SIMD_WIDTH};
use ncollide::bounding_volume::BoundingVolume;
use simba::simd::{SimdBool, SimdValue};

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct NodeIndex {
    index: u32, // Index of the addressed node in the `nodes` array.
    lane: u8,   // SIMD lane of the addressed node.
}

impl NodeIndex {
    fn new(index: u32, lane: u8) -> Self {
        Self { index, lane }
    }

    fn invalid() -> Self {
        Self {
            index: u32::MAX,
            lane: 0,
        }
    }
}

#[derive(Copy, Clone, Debug)]
struct WQuadtreeNodeChildren {
    waabb: WAABB,
    // Index of the nodes of the 4 nodes represented by self.
    // If this is a leaf, it contains the proxy ids instead.
    children: [u32; 4],
    parent: NodeIndex,
    leaf: bool, // TODO: pack this with the NodexIndex.lane?
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct ColliderNodeIndex {
    node: NodeIndex,
    handle: ColliderHandle, // The collider handle. TODO: only set the collider generation here?
}

impl ColliderNodeIndex {
    fn invalid() -> Self {
        Self {
            node: NodeIndex::invalid(),
            handle: ColliderSet::invalid_handle(),
        }
    }
}

pub struct WQuadtree {
    nodes: Vec<WQuadtreeNodeChildren>,
    dirty: Vec<bool>, // TODO: use a bitvec/Vob and check it does not break cross-platform determinism.
    proxies: Vec<ColliderNodeIndex>,
}

impl WQuadtree {
    pub fn new() -> Self {
        WQuadtree {
            nodes: Vec::new(),
            dirty: Vec::new(),
            proxies: Vec::new(),
        }
    }

    pub fn clear_and_rebuild(&mut self, colliders: &ColliderSet) {
        self.nodes.clear();
        self.dirty.clear();
        self.proxies.clear();

        // Create proxies.
        let mut indices = Vec::with_capacity(colliders.len());
        self.proxies = vec![ColliderNodeIndex::invalid(); colliders.len()];

        for (handle, collider) in colliders.iter() {
            let index = handle.into_raw_parts().0;
            if self.proxies.len() < index {
                self.proxies.resize(index + 1, ColliderNodeIndex::invalid());
            }

            self.proxies[index].handle = handle;
            indices.push(index);
        }

        // Compute AABBs.
        let mut aabbs = vec![AABB::new_invalid(); self.proxies.len()];
        for (handle, collider) in colliders.iter() {
            let index = handle.into_raw_parts().0;
            let aabb = collider.compute_aabb();
            aabbs[index] = aabb;
        }

        // Build the tree recursively.
        let root_node = WQuadtreeNodeChildren {
            waabb: WAABB::new_invalid(),
            children: [1, u32::MAX, u32::MAX, u32::MAX],
            parent: NodeIndex::invalid(),
            leaf: false,
        };

        self.nodes.push(root_node);
        let root_id = NodeIndex::new(0, 0);
        let (_, aabb) = self.do_recurse_build(&mut indices, &aabbs, root_id);
        self.nodes[0].waabb = WAABB::from([
            aabb,
            AABB::new_invalid(),
            AABB::new_invalid(),
            AABB::new_invalid(),
        ]);
    }

    fn do_recurse_build(
        &mut self,
        indices: &mut [usize],
        aabbs: &[AABB],
        parent: NodeIndex,
    ) -> (u32, AABB) {
        // Leaf case.
        if indices.len() <= 4 {
            let my_id = self.nodes.len();
            let mut my_aabb = AABB::new_invalid();
            let mut leaf_aabbs = [AABB::new_invalid(); 4];
            let mut proxy_ids = [u32::MAX; 4];

            for (k, id) in indices.iter().enumerate() {
                my_aabb.merge(&aabbs[*id]);
                leaf_aabbs[k] = aabbs[*id];
                proxy_ids[k] = *id as u32;
            }

            let node = WQuadtreeNodeChildren {
                waabb: WAABB::from(leaf_aabbs),
                children: proxy_ids,
                parent,
                leaf: true,
            };

            self.nodes.push(node);
            return (my_id as u32, my_aabb);
        }

        // Compute the center and variance along each dimension.
        // In 3D we compute the variance to not-subdivide the dimension with lowest variance.
        // Therefore variance computation is not needed in 2D because we only have 2 dimension
        // to split in the first place.
        let mut center = Point::origin();
        #[cfg(feature = "dim3")]
        let mut variance = Vector::zeros();

        let denom = 1.0 / (indices.len() as f32);

        for i in &*indices {
            let coords = aabbs[*i].center().coords;
            center += coords * denom;
            #[cfg(feature = "dim3")]
            {
                variance += coords.component_mul(&coords) * denom;
            }
        }

        #[cfg(feature = "dim3")]
        {
            variance = variance - center.coords.component_mul(&center.coords);
        }

        // Find the axis with minimum variance. This is the axis along
        // which we are **not** subdividing our set.
        let mut subdiv_dims = [0, 1];
        #[cfg(feature = "dim3")]
        {
            let min = variance.imin();
            subdiv_dims[0] = (min + 1) % 3;
            subdiv_dims[1] = (min + 2) % 3;
        }

        // Split the set along the two subdiv_dims dimensions.
        // TODO: should we split wrt. the median instead of the average?
        // TODO: we should ensure each subslice contains at least 4 elements each (or less if
        // indices has less than 16 elements in the first place.
        let (left, right) = split_indices_wrt_dim(indices, &aabbs, &center, subdiv_dims[0]);

        let (left_bottom, left_top) = split_indices_wrt_dim(left, &aabbs, &center, subdiv_dims[1]);
        let (right_bottom, right_top) =
            split_indices_wrt_dim(right, &aabbs, &center, subdiv_dims[1]);

        // println!(
        //     "Recursing on children: {}, {}, {}, {}",
        //     left_bottom.len(),
        //     left_top.len(),
        //     right_bottom.len(),
        //     right_top.len()
        // );

        let node = WQuadtreeNodeChildren {
            waabb: WAABB::new_invalid(),
            children: [0; 4], // Will be set after the recursive call
            parent,
            leaf: false,
        };

        let id = self.nodes.len() as u32;
        self.nodes.push(node);

        // Recurse!
        let a = self.do_recurse_build(left_bottom, aabbs, NodeIndex::new(id, 0));
        let b = self.do_recurse_build(left_top, aabbs, NodeIndex::new(id, 1));
        let c = self.do_recurse_build(right_bottom, aabbs, NodeIndex::new(id, 2));
        let d = self.do_recurse_build(right_top, aabbs, NodeIndex::new(id, 3));

        // Now we know the indices of the grand-nodes.
        self.nodes[id as usize].children = [a.0, b.0, c.0, d.0];
        self.nodes[id as usize].waabb = WAABB::from([a.1, b.1, c.1, d.1]);

        // TODO: will this chain of .merged be properly optimized?
        let my_aabb = a.1.merged(&b.1).merged(&c.1).merged(&d.1);
        (id, my_aabb)
    }

    pub fn cast_ray(&self, ray: &Ray, max_toi: f32) -> Vec<ColliderHandle> {
        let mut res = Vec::new();

        if self.nodes.is_empty() {
            return res;
        }

        // Special case for the root.
        let mut stack = vec!<