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
use bevy::{
prelude::*,
render::{mesh::VertexAttributeValues, pipeline::PrimitiveTopology},
};
use core::panic;
use crate::PluginState;
#[derive(Debug, Clone, Default)]
pub struct BoundVol {
pub sphere: Option<BoundingSphere>,
}
#[derive(Debug, Clone)]
pub struct BoundingSphere {
origin: Vec3,
radius: f32,
scaled_radius: Option<f32>,
}
impl BoundingSphere {
pub fn origin(&self) -> Vec3 {
self.origin
}
pub fn radius(&self) -> f32 {
self.radius
}
}
#[allow(clippy::type_complexity)]
pub fn update_bound_sphere<T: 'static + Send + Sync>(
state: Res<PluginState<T>>,
meshes: Res<Assets<Mesh>>,
mut new_bound_vol_query: Query<
(&mut BoundVol, &Handle<Mesh>),
Or<(Added<BoundVol>, Changed<Handle<Mesh>>)>,
>,
) {
if !state.enabled {
return;
}
for (mut bound_vol, mesh_handle) in &mut new_bound_vol_query.iter_mut() {
if let Some(mesh) = meshes.get(mesh_handle) {
bound_vol.sphere = Some(BoundingSphere::from(mesh));
} else {
continue;
}
}
}
impl From<&Mesh> for BoundingSphere {
fn from(mesh: &Mesh) -> Self {
if mesh.primitive_topology() != PrimitiveTopology::TriangleList {
panic!("Non-TriangleList mesh supplied for bounding sphere generation")
}
let vertices: Vec<Vec3> = match mesh.attribute(Mesh::ATTRIBUTE_POSITION) {
None => panic!("Mesh does not contain vertex positions"),
Some(vertex_values) => match &vertex_values {
VertexAttributeValues::Float3(positions) => positions
.iter()
.map(|coordinates| Vec3::from(*coordinates))
.collect(),
_ => panic!("Unexpected vertex types in ATTRIBUTE_POSITION"),
},
};
let point_x = vertices[0];
let point_y = vertices.iter().fold(point_x, |acc, x| {
if x.distance(point_x) >= acc.distance(point_x) {
*x
} else {
acc
}
});
let point_z = vertices.iter().fold(point_y, |acc, x| {
if x.distance(point_y) >= acc.distance(point_y) {
*x
} else {
acc
}
});
let mut sphere = BoundingSphere {
origin: point_y.lerp(point_z, 0.5),
radius: point_y.distance(point_z) / 2.0,
scaled_radius: None,
};
loop {
let point_n = vertices.iter().fold(point_x, |acc, x| {
if x.distance(sphere.origin) >= acc.distance(sphere.origin) {
*x
} else {
acc
}
});
let point_dist = point_n.distance(sphere.origin);
if point_dist > sphere.radius {
let radius_new = (sphere.radius + point_dist) / 2.0;
let lerp_ratio = (point_dist - radius_new) / point_dist;
sphere = BoundingSphere {
origin: sphere.origin.lerp(point_n, lerp_ratio),
radius: radius_new,
scaled_radius: None,
};
} else {
return sphere;
}
}
}
}