Initial project import
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-06-05 21:44:45 -04:00
commit f29712d158
259 files changed
+52069

No files matched your search

@@ -0,0 +1,379 @@
//! Thumbnail cache for asset browser grid cells.
use std::collections::{HashMap, HashSet};
use bevy::prelude::*;
use bevy_egui::{egui, EguiPrimaryContextPass, EguiTextureHandle, EguiUserTextures};
use egui_phosphor_icons::icons;
use super::sources::gltf::gltf_base_color_texture_path;
use super::studio::{model_file_exists, ThumbnailStudio};
use crate::assets::{
asset_cache_key, asset_server_path, EditorAsset, EditorAssetKind, EditorAssets,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ThumbnailState {
Pending,
Ready,
Failed { reason: String, retryable: bool },
}
#[derive(Debug, Clone)]
struct ThumbnailFailure {
reason: String,
retryable: bool,
}
#[derive(Resource, Default)]
pub struct AssetThumbnailCache {
pub texture_ids: HashMap<String, egui::TextureId>,
pending: HashMap<String, Handle<Image>>,
pub(crate) studio_pending: HashSet<String>,
failed: HashMap<String, ThumbnailFailure>,
prefetched_folder: Option<String>,
}
pub struct AssetThumbnailsPlugin;
impl Plugin for AssetThumbnailsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<AssetThumbnailCache>()
.add_systems(EguiPrimaryContextPass, register_loaded_thumbnails);
}
}
impl AssetThumbnailCache {
pub fn state(&self, key: &str) -> Option<ThumbnailState> {
if self.texture_ids.contains_key(key) {
return Some(ThumbnailState::Ready);
}
if self.failed.contains_key(key) {
let failure = self.failed.get(key)?;
return Some(ThumbnailState::Failed {
reason: failure.reason.clone(),
retryable: failure.retryable,
});
}
if self.pending.contains_key(key) || self.studio_pending.contains(key) {
return Some(ThumbnailState::Pending);
}
None
}
pub fn retry(&mut self, key: &str) {
self.failed.remove(key);
self.pending.remove(key);
self.studio_pending.remove(key);
self.texture_ids.remove(key);
}
pub fn request_texture(&mut self, key: String, path: String, asset_server: &AssetServer) {
if matches!(
self.state(&key),
Some(ThumbnailState::Ready | ThumbnailState::Pending)
) {
return;
}
if self.failed.contains_key(&key) {
return;
}
let handle: Handle<Image> = asset_server.load(asset_server_path(&path));
self.pending.insert(key, handle);
}
pub fn request_model(
&mut self,
key: String,
model_path: String,
asset_server: &AssetServer,
studio: &mut ThumbnailStudio,
) {
if matches!(
self.state(&key),
Some(ThumbnailState::Ready | ThumbnailState::Pending)
) {
return;
}
if self.failed.contains_key(&key) {
return;
}
if let Some(texture_path) = gltf_base_color_texture_path(&model_path) {
self.request_texture(key, texture_path, asset_server);
return;
}
if !model_file_exists(&model_path) {
self.mark_studio_failed(&key, "file not found", false);
return;
}
if studio.enqueue(key.clone(), model_path) {
self.studio_pending.insert(key);
}
}
pub(crate) fn complete_studio_thumbnail(
&mut self,
key: &str,
image: Handle<Image>,
textures: &mut EguiUserTextures,
) {
self.studio_pending.remove(key);
self.failed.remove(key);
let texture_id = textures
.image_id(&image)
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(image)));
self.texture_ids.insert(key.to_string(), texture_id);
}
pub(crate) fn mark_studio_failed(&mut self, key: &str, reason: &str, retryable: bool) {
self.studio_pending.remove(key);
self.pending.remove(key);
self.failed.insert(
key.to_string(),
ThumbnailFailure {
reason: reason.to_string(),
retryable,
},
);
}
pub fn invalidate_all(&mut self) {
self.texture_ids.clear();
self.pending.clear();
self.studio_pending.clear();
self.failed.clear();
self.prefetched_folder = None;
}
pub fn snapshot(&self) -> ThumbnailCacheSnapshot {
ThumbnailCacheSnapshot {
texture_ids: self.texture_ids.clone(),
pending_keys: self
.pending
.keys()
.chain(self.studio_pending.iter())
.cloned()
.collect(),
failed_keys: self.failed.keys().cloned().collect(),
}
}
}
fn register_loaded_thumbnails(
asset_server: Res<AssetServer>,
mut cache: ResMut<AssetThumbnailCache>,
mut textures: ResMut<EguiUserTextures>,
) {
let ready: Vec<(String, Handle<Image>)> = cache
.pending
.iter()
.filter(|(_, handle)| asset_server.is_loaded_with_dependencies(*handle))
.map(|(key, handle)| (key.clone(), handle.clone()))
.collect();
for (key, handle) in ready {
cache.pending.remove(&key);
cache.failed.remove(&key);
let texture_id = textures
.image_id(&handle)
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(handle)));
cache.texture_ids.insert(key, texture_id);
}
}
pub fn kind_icon(kind: &EditorAssetKind) -> egui_phosphor_icons::Icon {
match kind {
EditorAssetKind::Primitive(_) => icons::CUBE,
EditorAssetKind::Light(_) => icons::LIGHTBULB,
EditorAssetKind::Model => icons::CUBE_TRANSPARENT,
EditorAssetKind::Texture => icons::IMAGE,
EditorAssetKind::Material => icons::PAINT_BRUSH,
EditorAssetKind::Level => icons::MAP_TRIFOLD,
EditorAssetKind::Prefab => icons::PACKAGE,
EditorAssetKind::PostProcessVolume => icons::CAMERA,
EditorAssetKind::PostProcessEffect => icons::SPARKLE,
EditorAssetKind::RenderingProfile => icons::SLIDERS,
EditorAssetKind::ShaderSchema => icons::CODE,
}
}
pub fn draw_asset_cell_with(
ui: &mut egui::Ui,
asset: &EditorAsset,
texture_id: Option<egui::TextureId>,
pending: bool,
failed: Option<&str>,
selected: bool,
thumbnail_size: f32,
) -> egui::Response {
let thumb_size = thumbnail_size.clamp(48.0, 112.0);
let cell_size = egui::vec2(thumb_size + 20.0, thumb_size + 30.0);
let (rect, response) = ui.allocate_exact_size(cell_size, egui::Sense::click_and_drag());
let fill = if selected {
crate::ui::theme::SELECTION_BG_MUTED
} else if response.hovered() {
crate::ui::theme::ELEVATED_BG
} else {
crate::ui::theme::WIDGET_BG
};
ui.painter().rect(
rect,
4.0,
fill,
egui::Stroke::new(
1.0,
if selected {
crate::ui::theme::ACCENT_HOVER
} else {
crate::ui::theme::BORDER
},
),
egui::StrokeKind::Inside,
);
let thumb_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(10.0, 8.0),
egui::vec2(thumb_size, thumb_size),
);
if let Some(texture_id) = texture_id {
ui.painter().image(
texture_id,
thumb_rect,
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
} else if pending {
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icons::CIRCLE_NOTCH.as_str(),
egui::FontId::new(24.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT_DIM,
);
} else if failed.is_some() {
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icons::WARNING_CIRCLE.as_str(),
egui::FontId::new(24.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT_DIM,
);
} else {
let icon = kind_icon(&asset.kind);
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(28.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT,
);
}
ui.painter().text(
egui::pos2(rect.center().x, rect.max.y - 6.0),
egui::Align2::CENTER_BOTTOM,
asset.label.as_str(),
egui::FontId::new(11.0, egui::FontFamily::Proportional),
if selected {
crate::ui::theme::TEXT_SELECTED
} else {
crate::ui::theme::TEXT
},
);
response
}
#[derive(Clone)]
pub struct ThumbnailCacheSnapshot {
pub texture_ids: HashMap<String, egui::TextureId>,
pub pending_keys: Vec<String>,
pub failed_keys: Vec<String>,
}
impl ThumbnailCacheSnapshot {
pub fn texture_for(&self, asset: &EditorAsset) -> Option<egui::TextureId> {
self.texture_ids.get(&asset_cache_key(asset)).copied()
}
pub fn is_pending(&self, asset: &EditorAsset) -> bool {
self.pending_keys
.iter()
.any(|key| key == &asset_cache_key(asset))
}
pub fn is_failed(&self, asset: &EditorAsset) -> bool {
self.failed_keys
.iter()
.any(|key| key == &asset_cache_key(asset))
}
}
pub fn prefetch_folder_thumbnails(world: &mut World, folder: &str) {
{
let cache = world.resource::<AssetThumbnailCache>();
if cache.prefetched_folder.as_deref() == Some(folder) {
return;
}
}
let requests: Vec<(String, String, EditorAssetKind)> = {
let assets = world.resource::<EditorAssets>();
assets
.assets
.iter()
.filter(|asset| asset.folder_path == folder)
.filter(|asset| {
matches!(
asset.kind,
EditorAssetKind::Texture | EditorAssetKind::Model
)
})
.filter_map(|asset| {
Some((
asset_cache_key(asset),
asset.path.clone()?,
asset.kind.clone(),
))
})
.collect()
};
let asset_server = world.resource::<AssetServer>().clone();
world.resource_scope(|world, mut cache: Mut<AssetThumbnailCache>| {
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
for (key, path, kind) in requests {
match kind {
EditorAssetKind::Texture => cache.request_texture(key, path, &asset_server),
EditorAssetKind::Model => {
cache.request_model(key, path, &asset_server, &mut studio)
}
_ => {}
}
}
});
});
world
.resource_mut::<AssetThumbnailCache>()
.prefetched_folder = Some(folder.to_string());
}
pub fn invalidate_on_catalog_refresh(world: &mut World) {
world.resource_mut::<AssetThumbnailCache>().invalidate_all();
if !world.contains_resource::<ThumbnailStudio>() {
return;
}
let cleanup = {
let mut studio = world.resource_mut::<ThumbnailStudio>();
studio.clear_queue();
studio.clear_jobs()
};
if let Some(root) = cleanup.active_root {
world.commands().entity(root).despawn_children();
world.commands().entity(root).despawn();
}
}
@@ -0,0 +1,7 @@
//! Thumbnail generation job descriptor.
#[derive(Debug, Clone)]
pub struct ThumbnailJob {
pub cache_key: String,
pub model_path: String,
}
@@ -0,0 +1,26 @@
//! Unified asset thumbnail pipeline (texture fast-path + model studio).
use bevy::prelude::*;
mod cache;
mod job;
mod sources;
mod studio;
pub use cache::{
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_folder_thumbnails,
AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot, ThumbnailState,
};
pub use job::ThumbnailJob;
pub use sources::{FbxThumbnailSource, GltfThumbnailSource, ThumbnailModelSource};
pub use studio::{
model_file_exists, model_scene_asset_path, ThumbnailStudio, ThumbnailStudioPlugin,
};
pub struct ThumbnailsPlugin;
impl Plugin for ThumbnailsPlugin {
fn build(&self, app: &mut App) {
app.add_plugins((AssetThumbnailsPlugin, ThumbnailStudioPlugin));
}
}
@@ -0,0 +1,123 @@
//! Direct FBX mesh extraction for thumbnail studio (no texture deps).
use bevy::asset::RenderAssetUsages;
use bevy::camera::visibility::RenderLayers;
use bevy::mesh::{Indices, PrimitiveTopology};
use bevy::prelude::*;
use bevy_ufbx::mesh::group_faces_by_material;
use bevy_ufbx::utils::convert_matrix;
use super::ThumbnailModelSource;
use crate::assets::thumbnails::studio::THUMBNAIL_LAYER;
pub struct FbxThumbnailSource;
impl ThumbnailModelSource for FbxThumbnailSource {
fn spawn_preview(
&self,
commands: &mut Commands,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
root: Entity,
catalog_path: &str,
) -> bool {
let Ok(bytes) = std::fs::read(catalog_path) else {
warn!("FBX thumbnail: could not read {catalog_path}");
return false;
};
let scene = match ufbx::load_memory(
&bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
..Default::default()
},
) {
Ok(scene) => scene,
Err(err) => {
warn!("FBX thumbnail: failed to parse {catalog_path}: {err:?}");
return false;
}
};
let material = materials.add(StandardMaterial {
base_color: Color::srgb(0.72, 0.72, 0.75),
..default()
});
let mut spawned = false;
for node in scene.nodes.as_ref().iter() {
let Some(mesh_ref) = node.mesh.as_ref() else {
continue;
};
let ufbx_mesh = mesh_ref.as_ref();
if ufbx_mesh.num_vertices == 0 || ufbx_mesh.faces.as_ref().is_empty() {
continue;
}
for (_material_idx, indices) in group_faces_by_material(ufbx_mesh) {
if indices.is_empty() {
continue;
}
let mesh_handle = meshes.add(build_mesh(ufbx_mesh, &indices));
let transform = Transform::from_matrix(convert_matrix(&node.geometry_to_world));
commands.entity(root).with_children(|parent| {
parent.spawn((
RenderLayers::layer(THUMBNAIL_LAYER),
Mesh3d(mesh_handle),
MeshMaterial3d(material.clone()),
transform,
));
});
spawned = true;
}
}
if !spawned {
warn!("FBX thumbnail: no renderable meshes in {catalog_path}");
}
spawned
}
}
fn build_mesh(ufbx_mesh: &ufbx::Mesh, indices: &[u32]) -> Mesh {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
let positions: Vec<[f32; 3]> = ufbx_mesh
.vertex_position
.values
.as_ref()
.iter()
.map(|v| [v.x as f32, v.y as f32, v.z as f32])
.collect();
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
if ufbx_mesh.vertex_normal.exists {
let normals: Vec<[f32; 3]> = (0..ufbx_mesh.num_vertices)
.map(|i| {
let n = ufbx_mesh.vertex_normal[i];
[n.x as f32, n.y as f32, n.z as f32]
})
.collect();
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
}
if ufbx_mesh.vertex_uv.exists {
let uvs: Vec<[f32; 2]> = (0..ufbx_mesh.num_vertices)
.map(|i| {
let uv = ufbx_mesh.vertex_uv[i];
[uv.x as f32, uv.y as f32]
})
.collect();
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
}
mesh.insert_indices(Indices::U32(indices.to_vec()));
mesh
}
@@ -0,0 +1,82 @@
//! glTF/GLB fast-path texture extraction for asset browser thumbnails.
use std::path::Path;
/// Returns an asset-server path for the first base-color texture referenced by a glTF/GLB file.
///
/// Embedded GLB buffers are skipped so callers can fall back to the render studio.
pub fn gltf_base_color_texture_path(model_asset_path: &str) -> Option<String> {
let model_path = Path::new(model_asset_path);
if !is_gltf_path(model_path) {
return None;
}
let (document, ..) = gltf::import(model_path).ok()?;
for material in document.materials() {
let Some(tex_info) = material.pbr_metallic_roughness().base_color_texture() else {
continue;
};
let texture = document.textures().nth(tex_info.texture().index())?;
let image = document.images().nth(texture.source().index())?;
let uri = match image.source() {
gltf::image::Source::Uri { uri, .. } => uri,
gltf::image::Source::View { .. } => continue,
};
if let Some(path) = resolve_texture_uri(model_path, uri) {
return Some(path);
}
}
None
}
pub struct GltfThumbnailSource;
fn is_gltf_path(path: &Path) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| matches!(ext.to_ascii_lowercase().as_str(), "gltf" | "glb"))
}
fn resolve_texture_uri(model_path: &Path, uri: &str) -> Option<String> {
if uri.starts_with("data:") {
return None;
}
let model_dir = model_path.parent()?;
let texture_path = model_dir.join(uri);
normalize_asset_path(&texture_path)
}
fn normalize_asset_path(path: &Path) -> Option<String> {
let raw = path.to_string_lossy().replace('\\', "/");
if raw.starts_with("assets/") {
return Some(raw);
}
let file_name = path.file_name()?.to_str()?;
if file_name.is_empty() {
return None;
}
Some(format!("assets/{file_name}"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn normalize_asset_path_keeps_assets_prefix() {
assert_eq!(
normalize_asset_path(Path::new("assets/textures/albedo.png")),
Some("assets/textures/albedo.png".into())
);
}
#[test]
fn resolve_texture_uri_relative_to_model() {
let model = PathBuf::from("assets/models/chair.gltf");
assert_eq!(
resolve_texture_uri(&model, "textures/chair_albedo.png"),
Some("assets/models/textures/chair_albedo.png".into())
);
}
}
@@ -0,0 +1,33 @@
//! Model file sources for the thumbnail render studio.
mod fbx;
pub(crate) mod gltf;
pub use fbx::FbxThumbnailSource;
pub use gltf::GltfThumbnailSource;
use bevy::prelude::*;
/// Spawns untextured or scene-root preview content under `root` for the thumbnail studio.
pub trait ThumbnailModelSource: Send + Sync {
fn spawn_preview(
&self,
commands: &mut Commands,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
root: Entity,
catalog_path: &str,
) -> bool;
}
pub fn source_for_extension(path: &str) -> Option<&'static dyn ThumbnailModelSource> {
if path.ends_with(".fbx") {
Some(&FbxThumbnailSource)
} else {
None
}
}
pub fn uses_scene_root(path: &str) -> bool {
!path.ends_with(".fbx")
}
@@ -0,0 +1,544 @@
//! Offscreen model thumbnail studio for FBX and untextured glTF assets.
use std::collections::VecDeque;
use std::path::Path;
use bevy::camera::visibility::RenderLayers;
use bevy::camera::RenderTarget;
use bevy::gltf::GltfAssetLabel;
use bevy::math::bounding::Aabb3d;
use bevy::mesh::VertexAttributeValues;
use bevy::prelude::*;
use bevy::render::render_resource::TextureFormat;
use bevy::scene::SceneRoot;
use bevy_egui::EguiUserTextures;
use shared::ModelRef;
use super::cache::AssetThumbnailCache;
use super::job::ThumbnailJob;
use super::sources::{source_for_extension, uses_scene_root};
use crate::assets::asset_server_path;
use crate::infra::EditorOnly;
pub(crate) const THUMB_SIZE: u32 = 128;
pub(crate) const THUMBNAIL_LAYER: usize = 31;
const MESH_WARMUP_FRAMES: u8 = 12;
const POST_ATTACH_FRAMES: u8 = 8;
const RENDER_FRAMES: u8 = 3;
const COOLDOWN_FRAMES: u8 = 2;
const LOAD_TIMEOUT_FRAMES: u32 = 240;
#[derive(Component)]
struct ThumbnailStudioCamera;
#[derive(Component)]
struct ThumbnailStudioLight;
#[derive(Component)]
struct ThumbnailStudioLayer;
#[derive(Component)]
struct ThumbnailSceneRoot;
#[derive(Resource)]
pub struct ThumbnailStudio {
camera: Entity,
render_image: Handle<Image>,
_lights: Vec<Entity>,
queue: VecDeque<ThumbnailJob>,
active: Option<ActiveModelThumbnail>,
cooldown_frames: u8,
}
struct ActiveModelThumbnail {
cache_key: String,
model_path: String,
root: Entity,
meshes_ready: bool,
mesh_warmup_frames: u8,
camera_active: bool,
post_attach_frames: u8,
framed: bool,
frames_remaining: u8,
wait_frames: u32,
}
pub struct ThumbnailStudioPlugin;
impl Plugin for ThumbnailStudioPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup_thumbnail_studio)
.add_systems(PostUpdate, apply_thumbnail_studio_layers)
.add_systems(Last, process_thumbnail_studio);
}
}
impl ThumbnailStudio {
pub fn enqueue(&mut self, cache_key: String, model_path: String) -> bool {
if self
.active
.as_ref()
.is_some_and(|active| active.cache_key == cache_key)
{
return false;
}
if self.queue.iter().any(|job| job.cache_key == cache_key) {
return false;
}
self.queue.push_back(ThumbnailJob {
cache_key,
model_path,
});
true
}
pub fn clear_queue(&mut self) {
self.queue.clear();
self.cooldown_frames = 0;
}
pub fn clear_jobs(&mut self) -> StudioCleanup {
StudioCleanup {
camera: self.camera,
active_root: self.active.take().map(|active| active.root),
}
}
}
pub struct StudioCleanup {
pub camera: Entity,
pub active_root: Option<Entity>,
}
pub fn model_scene_asset_path(path: &str, scene_index: usize) -> String {
let path = asset_server_path(path);
if path.ends_with(".fbx") {
ModelRef::fbx_scene_asset_path(&path, scene_index)
} else {
GltfAssetLabel::Scene(scene_index)
.from_asset(path)
.to_string()
}
}
fn setup_thumbnail_studio(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
let render_image = images.add(Image::new_target_texture(
THUMB_SIZE,
THUMB_SIZE,
TextureFormat::Rgba8UnormSrgb,
None,
));
let camera = commands
.spawn((
Name::new("Thumbnail Studio Camera"),
EditorOnly,
ThumbnailStudioCamera,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
Camera3d::default(),
Camera {
is_active: false,
order: -50,
clear_color: ClearColorConfig::Custom(Color::srgb(0.12, 0.12, 0.14)),
..default()
},
RenderTarget::Image(render_image.clone().into()),
Transform::from_xyz(2.0, 1.4, 2.0).looking_at(Vec3::new(0.0, 0.5, 0.0), Vec3::Y),
Projection::Perspective(PerspectiveProjection {
fov: 40.0_f32.to_radians(),
..default()
}),
))
.id();
let key_light = commands
.spawn((
EditorOnly,
ThumbnailStudioLight,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
DirectionalLight {
illuminance: 12_000.0,
shadows_enabled: false,
..default()
},
Transform::from_rotation(Quat::from_euler(EulerRot::XYZ, -0.8, 0.9, 0.0)),
))
.id();
let fill_light = commands
.spawn((
EditorOnly,
ThumbnailStudioLight,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
DirectionalLight {
illuminance: 3_500.0,
shadows_enabled: false,
..default()
},
Transform::from_rotation(Quat::from_euler(EulerRot::XYZ, -0.4, -2.2, 0.0)),
))
.id();
commands.insert_resource(ThumbnailStudio {
camera,
render_image,
_lights: vec![key_light, fill_light],
queue: VecDeque::new(),
active: None,
cooldown_frames: 0,
});
}
#[allow(clippy::too_many_arguments)]
fn process_thumbnail_studio(
mut commands: Commands,
mut studio: ResMut<ThumbnailStudio>,
mut cache: ResMut<AssetThumbnailCache>,
mut textures: ResMut<EguiUserTextures>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut mesh_storage: ResMut<Assets<Mesh>>,
asset_server: Res<AssetServer>,
mut cameras: Query<&mut Camera, With<ThumbnailStudioCamera>>,
mut camera_transforms: Query<&mut Transform, With<ThumbnailStudioCamera>>,
children: Query<&Children>,
transforms: Query<&GlobalTransform>,
mesh3d: Query<&Mesh3d>,
) {
if studio.cooldown_frames > 0 {
studio.cooldown_frames -= 1;
return;
}
if let Some(mut active) = studio.active.take() {
if !active.framed {
active.wait_frames += 1;
if !active.meshes_ready {
if thumbnail_meshes_present(active.root, &children, &mesh3d, &mesh_storage) {
active.meshes_ready = true;
active.mesh_warmup_frames = 0;
}
} else if active.mesh_warmup_frames < MESH_WARMUP_FRAMES {
active.mesh_warmup_frames += 1;
} else if frame_thumbnail_scene(
active.root,
&children,
&transforms,
&mesh3d,
&mesh_storage,
&mut camera_transforms,
) {
active.framed = true;
active.post_attach_frames = 0;
studio.active = Some(active);
return;
}
if active.wait_frames >= LOAD_TIMEOUT_FRAMES {
warn!(
"Model thumbnail timed out framing {} (meshes may still be loading)",
active.model_path
);
fail_active_thumbnail(
&mut commands,
&mut studio,
&mut cache,
&mut cameras,
active,
"load timeout",
true,
);
} else {
studio.active = Some(active);
}
return;
}
if !active.camera_active {
active.post_attach_frames += 1;
if active.post_attach_frames >= POST_ATTACH_FRAMES {
if let Ok(mut camera) = cameras.get_mut(studio.camera) {
camera.is_active = true;
}
active.camera_active = true;
active.frames_remaining = RENDER_FRAMES;
}
studio.active = Some(active);
return;
}
if active.camera_active {
if active.frames_remaining > 0 {
active.frames_remaining -= 1;
studio.active = Some(active);
} else {
cache.complete_studio_thumbnail(
&active.cache_key,
studio.render_image.clone(),
&mut textures,
);
finish_active_thumbnail(&mut commands, &mut studio, &mut cameras, active);
}
return;
}
studio.active = Some(active);
return;
}
let Some(job) = studio.queue.pop_front() else {
deactivate_studio_camera(&mut cameras, studio.camera);
return;
};
let mut root_entity = commands.spawn((
EditorOnly,
ThumbnailSceneRoot,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
Transform::default(),
));
if uses_scene_root(&job.model_path) {
root_entity.insert(SceneRoot(
asset_server.load(model_scene_asset_path(&job.model_path, 0)),
));
}
let root = root_entity.id();
let content_spawned = if let Some(source) = source_for_extension(&job.model_path) {
source.spawn_preview(
&mut commands,
&mut mesh_storage,
&mut materials,
root,
&job.model_path,
)
} else {
uses_scene_root(&job.model_path)
};
if source_for_extension(&job.model_path).is_some() && !content_spawned {
fail_active_thumbnail(
&mut commands,
&mut studio,
&mut cache,
&mut cameras,
ActiveModelThumbnail {
cache_key: job.cache_key,
model_path: job.model_path,
root,
meshes_ready: false,
mesh_warmup_frames: 0,
camera_active: false,
post_attach_frames: 0,
framed: false,
frames_remaining: 0,
wait_frames: 0,
},
"no renderable meshes",
true,
);
return;
}
studio.active = Some(ActiveModelThumbnail {
cache_key: job.cache_key,
model_path: job.model_path,
root,
meshes_ready: false,
mesh_warmup_frames: 0,
camera_active: false,
post_attach_frames: 0,
framed: false,
frames_remaining: 0,
wait_frames: 0,
});
}
fn finish_active_thumbnail(
commands: &mut Commands,
studio: &mut ThumbnailStudio,
cameras: &mut Query<&mut Camera, With<ThumbnailStudioCamera>>,
active: ActiveModelThumbnail,
) {
despawn_thumbnail_root(commands, active.root);
deactivate_studio_camera(cameras, studio.camera);
studio.cooldown_frames = COOLDOWN_FRAMES;
}
fn fail_active_thumbnail(
commands: &mut Commands,
studio: &mut ThumbnailStudio,
cache: &mut AssetThumbnailCache,
cameras: &mut Query<&mut Camera, With<ThumbnailStudioCamera>>,
active: ActiveModelThumbnail,
reason: &str,
retryable: bool,
) {
cache.mark_studio_failed(&active.cache_key, reason, retryable);
finish_active_thumbnail(commands, studio, cameras, active);
}
fn apply_thumbnail_studio_layers(
mut commands: Commands,
roots: Query<Entity, With<ThumbnailSceneRoot>>,
children: Query<&Children>,
tagged: Query<(), With<ThumbnailStudioLayer>>,
) {
for root in &roots {
let mut stack = vec![root];
while let Some(entity) = stack.pop() {
if tagged.get(entity).is_err() {
commands
.entity(entity)
.insert((ThumbnailStudioLayer, RenderLayers::layer(THUMBNAIL_LAYER)));
}
if let Ok(kids) = children.get(entity) {
stack.extend(kids.iter());
}
}
}
}
fn deactivate_studio_camera(
cameras: &mut Query<&mut Camera, With<ThumbnailStudioCamera>>,
camera: Entity,
) {
if let Ok(mut camera) = cameras.get_mut(camera) {
camera.is_active = false;
}
}
fn despawn_thumbnail_root(commands: &mut Commands, root: Entity) {
commands.entity(root).despawn_children();
commands.entity(root).despawn();
}
fn thumbnail_meshes_present(
root: Entity,
children: &Query<&Children>,
meshes: &Query<&Mesh3d>,
mesh_assets: &Assets<Mesh>,
) -> bool {
let mut entities = Vec::new();
collect_descendants(root, children, &mut entities);
entities.iter().any(|&entity| {
let Ok(mesh3d) = meshes.get(entity) else {
return false;
};
mesh_assets
.get(&mesh3d.0)
.is_some_and(|mesh| mesh_positions(mesh).next().is_some())
})
}
fn mesh_positions(mesh: &Mesh) -> impl Iterator<Item = [f32; 3]> + '_ {
let positions = mesh
.attribute(Mesh::ATTRIBUTE_POSITION)
.and_then(|values| match values {
VertexAttributeValues::Float32x3(positions) => Some(positions.as_slice()),
_ => None,
});
positions
.into_iter()
.flat_map(|slice| slice.iter().copied())
}
fn frame_thumbnail_scene(
root: Entity,
children: &Query<&Children>,
transforms: &Query<&GlobalTransform>,
meshes: &Query<&Mesh3d>,
mesh_assets: &Assets<Mesh>,
camera_transforms: &mut Query<&mut Transform, With<ThumbnailStudioCamera>>,
) -> bool {
let mut entities = Vec::new();
collect_descendants(root, children, &mut entities);
let mut min = Vec3::splat(f32::INFINITY);
let mut max = Vec3::splat(f32::NEG_INFINITY);
let mut found_mesh = false;
for entity in entities {
let Ok(mesh3d) = meshes.get(entity) else {
continue;
};
let Ok(global) = transforms.get(entity) else {
continue;
};
if let Some(mesh) = mesh_assets.get(&mesh3d.0) {
let mut local_min = Vec3::splat(f32::INFINITY);
let mut local_max = Vec3::splat(f32::NEG_INFINITY);
let mut has_positions = false;
for position in mesh_positions(mesh) {
let p = Vec3::from_array(position);
local_min = local_min.min(p);
local_max = local_max.max(p);
has_positions = true;
}
if has_positions {
found_mesh = true;
for corner in aabb_corners(&Aabb3d::from_min_max(
Vec3A::from(local_min),
Vec3A::from(local_max),
)) {
let world = global.transform_point(corner);
min = min.min(world);
max = max.max(world);
}
}
}
}
if !found_mesh {
return false;
}
let center = (min + max) * 0.5;
let radius = (max - min).length().max(0.25) * 0.5;
let distance = radius / (20.0_f32.to_radians()).tan() * 1.35;
let eye = center + Vec3::new(1.0, 0.75, 1.0).normalize() * distance;
if let Ok(mut transform) = camera_transforms.single_mut() {
*transform = Transform::from_translation(eye).looking_at(center, Vec3::Y);
}
true
}
fn collect_descendants(entity: Entity, children: &Query<&Children>, out: &mut Vec<Entity>) {
out.push(entity);
let Ok(child_list) = children.get(entity) else {
return;
};
for child in child_list.iter() {
collect_descendants(child, children, out);
}
}
fn aabb_corners(aabb: &Aabb3d) -> [Vec3; 8] {
let min = Vec3::from(aabb.min);
let max = Vec3::from(aabb.max);
[
Vec3::new(min.x, min.y, min.z),
Vec3::new(max.x, min.y, min.z),
Vec3::new(min.x, max.y, min.z),
Vec3::new(max.x, max.y, min.z),
Vec3::new(min.x, min.y, max.z),
Vec3::new(max.x, min.y, max.z),
Vec3::new(min.x, max.y, max.z),
Vec3::new(max.x, max.y, max.z),
]
}
/// Skip studio jobs when the source file is missing on disk.
pub fn model_file_exists(catalog_path: &str) -> bool {
Path::new(catalog_path).is_file()
}