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
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::marker::PhantomData;
use cgmath::prelude::*;
use collision::dbvt::{DynamicBoundingVolumeTree, TreeValue};
use collision::prelude::*;
use specs::{Component, Entities, Entity, FetchMut, Join, ReadStorage, System, WriteStorage};
use {NextFrame, Real};
use collide::{CollisionShape, Primitive};
#[derive(Debug)]
pub struct SpatialSortingSystem<P, T, D> {
entities: HashMap<Entity, usize>,
marker: PhantomData<(P, T, D)>,
}
impl<P, T, D> SpatialSortingSystem<P, T, D> {
pub fn new() -> Self {
Self {
entities: HashMap::default(),
marker: PhantomData,
}
}
}
impl<'a, P, T, D> System<'a> for SpatialSortingSystem<P, T, D>
where
P: Primitive + Send + Sync + 'static,
P::Aabb: Clone
+ Debug
+ Send
+ Sync
+ Aabb<Scalar = Real>
+ Contains<P::Aabb>
+ SurfaceArea<Scalar = Real>,
P::Point: Debug,
<P::Point as EuclideanSpace>::Diff: Debug + Send + Sync,
T: Component + Clone + Debug + Transform<P::Point> + Send + Sync,
for<'b: 'a> &'b T::Storage: Join<Type = &'b T>,
D: Send + Sync + 'static + TreeValue<Bound = P::Aabb>,
for<'c: 'a> D: From<(Entity, &'c CollisionShape<P, T>)>,
{
type SystemData = (
Entities<'a>,
ReadStorage<'a, T>,
ReadStorage<'a, NextFrame<T>>,
WriteStorage<'a, CollisionShape<P, T>>,
FetchMut<'a, DynamicBoundingVolumeTree<D>>,
);
fn run(&mut self, (entities, poses, next_poses, mut shapes, mut tree): Self::SystemData) {
let mut keys = self.entities.keys().cloned().collect::<HashSet<Entity>>();
for (entity, pose, shape) in (&*entities, (&poses).open().1, &mut shapes).join() {
shape.update(&pose, None);
if let Some(node_index) = self.entities.get(&entity).cloned() {
tree.update_node(node_index, (entity, &*shape).into());
}
}
for (entity, pose, next_pose, shape) in
(&*entities, &poses, (&next_poses).open().1, &mut shapes).join()
{
shape.update(&pose, Some(&next_pose.value));
if let Some(node_index) = self.entities.get(&entity).cloned() {
tree.update_node(node_index, (entity, &*shape).into());
}
}
for (entity, _, shape) in (&*entities, &poses, &shapes).join() {
keys.remove(&entity);
if let None = self.entities.get(&entity) {
let node_index = tree.insert((entity, &*shape).into());
self.entities.insert(entity, node_index);
}
}
for entity in keys {
match self.entities.get(&entity).cloned() {
Some(node_index) => {
tree.remove(node_index);
self.entities.remove(&entity);
}
None => (),
}
}
tree.update();
tree.do_refit();
}
}