1use std::{collections::HashMap, sync::Arc};
14
15use serde::{Deserialize, Serialize};
16use wde_logger::prelude::*;
17
18use bevy::{
19 asset::{AssetLoader, LoadContext, io::Reader},
20 prelude::*
21};
22use wde_animation::prelude::*;
23use wde_pbr::prelude::*;
24use wde_renderer::prelude::*;
25
26#[doc(hidden)]
27pub mod prelude {
28 pub use crate::GltfAsset;
29 pub use crate::GltfError;
30 pub use crate::GltfLight;
31 pub use crate::GltfLightKind;
32 pub use crate::GltfLoader;
33 pub use crate::GltfLoaderSettings;
34 pub use crate::GltfSpawnQueue;
35 pub use crate::MeshGeometry;
36 pub use crate::ModelCondition;
37}
38
39mod accessor;
40mod error;
41mod loader;
42mod material;
43mod model;
44mod parser;
45
46pub use error::GltfError;
47pub use model::{GltfBone, GltfLight, GltfLightKind, ModelCondition};
48
49pub struct GltfPlugin;
50impl Plugin for GltfPlugin {
51 fn build(&self, app: &mut App) {
52 app.init_asset::<GltfAsset>()
53 .init_asset_loader::<GltfAssetLoader>()
54 .init_resource::<GltfSpawnQueue>()
55 .add_systems(Update, process_gltf_spawn_queue);
56 }
57}
58
59#[derive(Resource, Default)]
61pub struct GltfSpawnQueue {
62 pending: Vec<(Entity, Handle<GltfAsset>)>
63}
64
65#[derive(Asset, TypePath, Clone)]
69pub struct GltfAsset {
70 path: String,
71
72 pub models: Vec<(Handle<Mesh>, Handle<PbrMaterial>)>,
75 pub conditions: Vec<Option<ModelCondition>>,
77 pub geometry: Vec<Arc<MeshGeometry>>,
80 pub bbox: MeshBbox,
82 pub properties: HashMap<String, (Vec3, Vec3)>,
85 pub bones: Vec<GltfBone>,
87 pub model_bones: Vec<Option<usize>>,
89 pub animations: HashMap<String, Handle<AnimationClip>>,
91 pub lights: Vec<GltfLight>
93}
94
95impl GltfAsset {
96 pub fn animation(&self, name: &str) -> Option<&Handle<AnimationClip>> {
97 self.animations.get(name)
98 }
99
100 pub fn spawn_lights(&self, commands: &mut Commands, parent: Entity) {
102 for light in &self.lights {
103 let color = wde_renderer::prelude::WdeColor::LinearRgba(
104 light.color.x,
105 light.color.y,
106 light.color.z,
107 1.0
108 );
109 let mut entity = commands.spawn((
110 Name::new(format!("Light {}", light.name)),
111 light.transform,
112 ChildOf(parent)
113 ));
114 match light.kind {
115 GltfLightKind::Point => entity.insert(PointLight {
116 position: Vec3::ZERO,
117 color,
118 intensity: light.intensity,
119 range: light.range
120 }),
121 GltfLightKind::Spot {
122 inner_cone,
123 outer_cone
124 } => entity.insert(SpotLight {
125 position: Vec3::ZERO,
126 direction: Vec3::NEG_Z,
127 color,
128 intensity: light.intensity,
129 range: light.range,
130 inner_cone,
131 outer_cone
132 })
133 };
134 }
135 }
136
137 pub fn models_where(
139 &self,
140 connected: impl Fn(&str) -> bool
141 ) -> impl Iterator<Item = &(Handle<Mesh>, Handle<PbrMaterial>)> {
142 self.models
143 .iter()
144 .zip(self.conditions.iter())
145 .filter(move |(_, condition): &(_, &Option<ModelCondition>)| {
146 condition
147 .as_ref()
148 .is_none_or(|c| connected(&c.anchor) == c.connected)
149 })
150 .map(|(model, _)| model)
151 }
152}
153
154#[derive(Debug, Default)]
156pub struct MeshGeometry {
157 pub positions: Vec<Vec3>,
158 pub indices: Vec<u32>
159}
160
161#[derive(Serialize, Deserialize)]
163#[serde(default)]
164pub struct GltfLoaderSettings {
165 pub stencil_value: Option<u32>,
167 pub lods: Option<MeshLodSettings>
169}
170impl Default for GltfLoaderSettings {
171 fn default() -> Self {
172 Self {
173 stencil_value: None,
174 lods: Some(MeshLodSettings::default())
175 }
176 }
177}
178
179#[derive(Default, TypePath)]
180pub(crate) struct GltfAssetLoader;
181impl AssetLoader for GltfAssetLoader {
182 type Asset = GltfAsset;
183 type Settings = GltfLoaderSettings;
184 type Error = GltfError;
185
186 async fn load(
187 &self,
188 reader: &mut dyn Reader,
189 settings: &Self::Settings,
190 load_context: &mut LoadContext<'_>
191 ) -> Result<Self::Asset, Self::Error> {
192 let path = load_context.path().clone();
193 debug!("Loading glTF file {}.", &path);
194
195 let mut bytes = Vec::new();
197 reader.read_to_end(&mut bytes).await?;
198 let model = parser::parse_gltf(bytes, &path.to_string())?;
199
200 let (raw_materials, raw_meshes, bounding_boxes) = loader::form_models(&model)?;
202
203 let materials_handles: Vec<Handle<PbrMaterial>> = raw_materials
205 .iter()
206 .map(|material| material.to_pbr(load_context))
207 .collect();
208
209 let mut bone_matrices: Vec<Mat4> = Vec::with_capacity(model.bones.len());
211 for bone in &model.bones {
212 let local = Mat4::from_scale_rotation_translation(
213 bone.rest.scale,
214 bone.rest.rotation,
215 bone.rest.translation
216 );
217 bone_matrices.push(match bone.parent {
218 Some(parent) => bone_matrices[parent] * local,
219 None => local
220 });
221 }
222
223 let mut models = Vec::new();
225 let mut conditions = Vec::new();
226 let mut geometry = Vec::new();
227 let mut model_bones = Vec::new();
228 let mut bbox_min = Vec3::splat(f32::INFINITY);
229 let mut bbox_max = Vec3::splat(f32::NEG_INFINITY);
230 for (i, (indices_data, vertices, material_id, condition, bone)) in
231 raw_meshes.iter().enumerate()
232 {
233 let label = format!("gltf_mesh_{}", i);
234 let (bb_min, bb_max) = bounding_boxes[i];
235 let mut mesh_asset = Mesh {
236 label: label.clone(),
237 vertices: vertices.clone(),
238 indices: indices_data.clone(),
239 lods: Vec::new(),
240 bbox: MeshBbox {
241 min: bb_min,
242 max: bb_max
243 },
244 use_ssbo: true
245 };
246 if let Some(lods) = &settings.lods {
247 mesh_asset.generate_lods(lods);
248 }
249
250 models.push((
251 load_context.add_labeled_asset(label.clone(), mesh_asset),
252 materials_handles[*material_id].clone()
253 ));
254 conditions.push(condition.clone());
255 geometry.push(Arc::new(MeshGeometry {
256 positions: vertices.iter().map(|v| Vec3::from(v.position)).collect(),
257 indices: match indices_data.is_empty() {
258 true => (0..vertices.len() as u32).collect(),
259 false => indices_data.clone()
260 }
261 }));
262 model_bones.push(*bone);
263
264 let corners = match bone {
266 Some(bone) => (0..8)
267 .map(|c| {
268 let corner = Vec3::select(
269 bevy::math::BVec3::new(c & 1 != 0, c & 2 != 0, c & 4 != 0),
270 bb_max,
271 bb_min
272 );
273 bone_matrices[*bone].transform_point3(corner)
274 })
275 .collect(),
276 None => vec![bb_min, bb_max]
277 };
278 for corner in corners {
279 bbox_min = bbox_min.min(corner);
280 bbox_max = bbox_max.max(corner);
281 }
282 }
283
284 let animations = model
285 .animations
286 .into_iter()
287 .map(|clip| {
288 let name = clip.name.clone();
289 let handle = load_context.add_labeled_asset(format!("animation_{name}"), clip);
290 (name, handle)
291 })
292 .collect();
293
294 Ok(GltfAsset {
295 path: path.to_string(),
296 models,
297 conditions,
298 geometry,
299 bbox: MeshBbox {
300 min: bbox_min,
301 max: bbox_max
302 },
303 properties: model.properties,
304 bones: model.bones,
305 model_bones,
306 animations,
307 lights: model.lights
308 })
309 }
310
311 fn extensions(&self) -> &[&str] {
312 &["gltf", "glb"]
313 }
314}
315
316pub struct GltfLoader;
319impl GltfLoader {
320 pub fn spawn(queue: &mut GltfSpawnQueue, gltf_asset: Handle<GltfAsset>, parent: Entity) {
322 queue.pending.push((parent, gltf_asset));
323 }
324
325 pub fn try_spawn(
328 commands: &mut Commands,
329 gltf_asset: &Handle<GltfAsset>,
330 gltf_assets: &Assets<GltfAsset>,
331 parent: Entity
332 ) -> Option<()> {
333 let gltf_asset = gltf_assets.get(gltf_asset)?;
334
335 let mut bones: Vec<Entity> = Vec::with_capacity(gltf_asset.bones.len());
337 for bone in &gltf_asset.bones {
338 let bone_entity = commands
339 .spawn((
340 Name::new(format!("Bone {}", bone.name)),
341 bone.rest,
342 AnimationBone {
343 name: bone.name.clone(),
344 rest: bone.rest
345 },
346 ChildOf(bone.parent.map_or(parent, |p| bones[p]))
347 ))
348 .id();
349 bones.push(bone_entity);
350 }
351
352 for (i, (mesh_handle, material_handle)) in gltf_asset.models.iter().enumerate() {
353 let mesh_parent = gltf_asset.model_bones[i].map_or(parent, |bone| bones[bone]);
354 commands.spawn((
355 Name::new(format!(
356 "Mesh Entity {} for GLTF Model {}",
357 i, gltf_asset.path
358 )),
359 Transform::default(),
360 Mesh3d(mesh_handle.clone()),
361 PbrMaterial3d(material_handle.clone()),
362 ChildOf(mesh_parent)
363 ));
364 }
365 gltf_asset.spawn_lights(commands, parent);
366 Some(())
367 }
368}
369
370fn process_gltf_spawn_queue(
371 mut commands: Commands,
372 mut queue: ResMut<GltfSpawnQueue>,
373 gltf_assets: Res<Assets<GltfAsset>>
374) {
375 let mut i = 0;
376 while i < queue.pending.len() {
377 let (parent, gltf_asset) = &queue.pending[i];
378 if GltfLoader::try_spawn(&mut commands, gltf_asset, &gltf_assets, *parent).is_some() {
379 queue.pending.swap_remove(i);
380 } else {
381 i += 1;
382 }
383 }
384}