wde_renderer/assets/
mesh_lod.rs1use meshopt::{SimplifyOptions, VertexDataAdapter};
2use serde::{Deserialize, Serialize};
3use wde_wgpu::utils::Vertex;
4
5use super::Mesh;
6
7pub const MAX_MESH_LODS: usize = 4;
9
10#[derive(Clone, Debug)]
12pub struct MeshLod {
13 pub indices: Vec<u32>,
14 pub error: f32
16}
17
18#[derive(Clone, Debug, Serialize, Deserialize)]
20#[serde(default)]
21pub struct MeshLodSettings {
22 pub levels: usize,
24 pub ratio: f32,
26 pub min_triangles: usize,
28 pub max_error: f32,
30 pub min_reduction: f32
33}
34impl Default for MeshLodSettings {
35 fn default() -> Self {
36 Self {
37 levels: MAX_MESH_LODS - 1,
38 ratio: 0.5,
39 min_triangles: 64,
40 max_error: 0.1,
41 min_reduction: 0.2
42 }
43 }
44}
45
46impl Mesh {
47 pub fn generate_lods(&mut self, settings: &MeshLodSettings) {
49 self.lods.clear();
50 if self.indices.len() / 3 < settings.min_triangles {
51 return;
52 }
53 let Ok(adapter) = VertexDataAdapter::new(
54 bytemuck::cast_slice(&self.vertices),
55 std::mem::size_of::<Vertex>(),
56 std::mem::offset_of!(Vertex, position)
57 ) else {
58 return;
59 };
60 let scale = meshopt::simplify_scale(&adapter);
61
62 let mut previous_count = self.indices.len();
63 let mut previous_error = 0.0f32;
64 for _ in 0..settings.levels.min(MAX_MESH_LODS - 1) {
65 let target = (previous_count as f32 * settings.ratio) as usize / 3 * 3;
66 let mut error = 0.0;
67 let indices = meshopt::simplify(
68 &self.indices,
69 &adapter,
70 target,
71 settings.max_error,
72 SimplifyOptions::Prune,
73 Some(&mut error)
74 );
75 if indices.is_empty()
76 || indices.len() as f32 > previous_count as f32 * (1.0 - settings.min_reduction)
77 {
78 break;
79 }
80 previous_count = indices.len();
81 previous_error = previous_error.max(error * scale);
83 self.lods.push(MeshLod {
84 indices: meshopt::optimize_vertex_cache(&indices, self.vertices.len()),
85 error: previous_error
86 });
87 }
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use bevy::math::Vec3;
94
95 use super::*;
96 use crate::assets::MeshBbox;
97
98 fn grid(n: u32) -> Mesh {
100 let mut vertices = Vec::new();
101 for y in 0..=n {
102 for x in 0..=n {
103 let (u, v) = (x as f32 / n as f32, y as f32 / n as f32);
104 vertices.push(Vertex {
105 position: [u, (u * 6.0).sin() * (v * 6.0).cos() * 0.1, v],
106 normal: [0.0, 1.0, 0.0],
107 uv: [u, v],
108 ..Default::default()
109 });
110 }
111 }
112 let mut indices = Vec::new();
113 for y in 0..n {
114 for x in 0..n {
115 let i = y * (n + 1) + x;
116 indices.extend([i, i + n + 1, i + 1, i + 1, i + n + 1, i + n + 2]);
117 }
118 }
119 Mesh {
120 label: "grid".to_string(),
121 vertices,
122 indices,
123 lods: Vec::new(),
124 bbox: MeshBbox {
125 min: Vec3::ZERO,
126 max: Vec3::ONE
127 },
128 use_ssbo: true
129 }
130 }
131
132 #[test]
133 fn levels_get_coarser() {
134 let mut mesh = grid(32);
135 mesh.generate_lods(&MeshLodSettings::default());
136 assert_eq!(mesh.lods.len(), MAX_MESH_LODS - 1);
137
138 let mut previous = (mesh.indices.len(), 0.0);
139 for lod in &mesh.lods {
140 assert!(lod.indices.len() < previous.0);
141 assert!(lod.error >= previous.1);
142 assert!(
143 lod.indices
144 .iter()
145 .all(|&i| (i as usize) < mesh.vertices.len())
146 );
147 previous = (lod.indices.len(), lod.error);
148 }
149 }
150
151 #[test]
152 fn small_meshes_are_kept() {
153 let mut mesh = grid(2);
154 mesh.generate_lods(&MeshLodSettings::default());
155 assert!(mesh.lods.is_empty());
156 }
157}