This commit is contained in:
commit
f29712d158
259 files changed
+52069
No files matched your search
@@ -0,0 +1,257 @@
|
||||
//! Project asset registry (stable IDs + import metadata). Phase 5 foundation.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Stable asset identity for dependency tracking and prefab references.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub struct AssetId(pub Uuid);
|
||||
|
||||
impl AssetId {
|
||||
pub fn new() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
|
||||
pub fn as_string(&self) -> String {
|
||||
self.0.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AssetId {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum ModelPlacementMode {
|
||||
StaticAsset,
|
||||
SceneInstance,
|
||||
}
|
||||
|
||||
impl Default for ModelPlacementMode {
|
||||
fn default() -> Self {
|
||||
Self::StaticAsset
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum ModelHierarchyMode {
|
||||
SingleActor,
|
||||
SourceHierarchy,
|
||||
}
|
||||
|
||||
impl Default for ModelHierarchyMode {
|
||||
fn default() -> Self {
|
||||
Self::SingleActor
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum MaterialImportPolicy {
|
||||
SourceMaterials,
|
||||
AuthoringOverride,
|
||||
}
|
||||
|
||||
impl Default for MaterialImportPolicy {
|
||||
fn default() -> Self {
|
||||
Self::SourceMaterials
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ImportSettings {
|
||||
pub scale: f32,
|
||||
pub generate_collider: bool,
|
||||
pub lod0_only: bool,
|
||||
#[serde(default)]
|
||||
pub placement_mode: ModelPlacementMode,
|
||||
#[serde(default)]
|
||||
pub hierarchy_mode: ModelHierarchyMode,
|
||||
#[serde(default)]
|
||||
pub material_policy: MaterialImportPolicy,
|
||||
#[serde(default)]
|
||||
pub static_mesh_manifest_path: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for ImportSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
scale: 1.0,
|
||||
generate_collider: true,
|
||||
lod0_only: true,
|
||||
placement_mode: ModelPlacementMode::default(),
|
||||
hierarchy_mode: ModelHierarchyMode::default(),
|
||||
material_policy: MaterialImportPolicy::default(),
|
||||
static_mesh_manifest_path: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct AssetRecord {
|
||||
pub id: AssetId,
|
||||
pub path: String,
|
||||
pub label: String,
|
||||
pub kind_tag: String,
|
||||
#[serde(default)]
|
||||
pub import_settings: ImportSettings,
|
||||
#[serde(default)]
|
||||
pub dependencies: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct AssetRegistry {
|
||||
pub records: Vec<AssetRecord>,
|
||||
pub index_dirty: bool,
|
||||
}
|
||||
|
||||
pub struct AssetDbPlugin;
|
||||
|
||||
impl Plugin for AssetDbPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_resource(load_registry())
|
||||
.add_systems(Update, sync_registry_from_browser);
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_registry_from_browser(
|
||||
assets: Res<crate::assets::EditorAssets>,
|
||||
mut registry: ResMut<AssetRegistry>,
|
||||
) {
|
||||
if !assets.is_changed() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut existing: HashMap<String, AssetRecord> = registry
|
||||
.records
|
||||
.drain(..)
|
||||
.map(|record| (record.path.clone(), record))
|
||||
.collect();
|
||||
|
||||
let mut next_records = Vec::new();
|
||||
let mut seen_paths = HashMap::new();
|
||||
|
||||
for asset in &assets.assets {
|
||||
let Some(path) = asset.path.clone() else {
|
||||
continue;
|
||||
};
|
||||
if path.is_empty() || seen_paths.contains_key(&path) {
|
||||
continue;
|
||||
}
|
||||
seen_paths.insert(path.clone(), ());
|
||||
|
||||
let kind_tag = format!("{:?}", asset.kind);
|
||||
let mut record = if let Some(mut prior) = existing.remove(&path) {
|
||||
prior.label = asset.label.clone();
|
||||
prior.kind_tag = kind_tag;
|
||||
prior
|
||||
} else {
|
||||
AssetRecord {
|
||||
id: AssetId::new(),
|
||||
path: path.clone(),
|
||||
label: asset.label.clone(),
|
||||
kind_tag,
|
||||
import_settings: ImportSettings::default(),
|
||||
dependencies: Vec::new(),
|
||||
}
|
||||
};
|
||||
if record.kind_tag == "Model" {
|
||||
if let Err(error) = super::static_mesh::refresh_static_mesh_artifact(&mut record) {
|
||||
warn!(
|
||||
"Static mesh processor failed for {} (asset id {}): {error}",
|
||||
record.path,
|
||||
record.id.as_string()
|
||||
);
|
||||
}
|
||||
}
|
||||
next_records.push(record);
|
||||
}
|
||||
|
||||
let changed = registry.records != next_records;
|
||||
registry.records = next_records;
|
||||
if changed {
|
||||
registry.index_dirty = true;
|
||||
}
|
||||
|
||||
if registry.index_dirty {
|
||||
if let Err(error) = save_registry(®istry) {
|
||||
warn!("Asset registry save failed: {error}");
|
||||
} else {
|
||||
registry.index_dirty = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_asset_by_path(registry: &AssetRegistry, path: &str) -> Option<AssetRecord> {
|
||||
registry
|
||||
.records
|
||||
.iter()
|
||||
.find(|record| record.path == path)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn find_asset_by_id(registry: &AssetRegistry, id: &str) -> Option<AssetRecord> {
|
||||
registry
|
||||
.records
|
||||
.iter()
|
||||
.find(|record| record.id.as_string() == id)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn find_asset_mut_by_path<'a>(
|
||||
registry: &'a mut AssetRegistry,
|
||||
path: &str,
|
||||
) -> Option<&'a mut AssetRecord> {
|
||||
registry
|
||||
.records
|
||||
.iter_mut()
|
||||
.find(|record| record.path == path)
|
||||
}
|
||||
|
||||
pub fn update_import_settings(
|
||||
registry: &mut AssetRegistry,
|
||||
path: &str,
|
||||
settings: ImportSettings,
|
||||
) -> bool {
|
||||
let Some(record) = registry
|
||||
.records
|
||||
.iter_mut()
|
||||
.find(|record| record.path == path)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
record.import_settings = settings;
|
||||
registry.index_dirty = true;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn registry_index_path() -> &'static str {
|
||||
"assets/.index/registry.ron"
|
||||
}
|
||||
|
||||
pub fn save_registry(registry: &AssetRegistry) -> Result<(), String> {
|
||||
let path = registry_index_path();
|
||||
if let Some(parent) = std::path::Path::new(path).parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let text = ron::ser::to_string_pretty(®istry.records, ron::ser::PrettyConfig::default())
|
||||
.map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, text).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn load_registry() -> AssetRegistry {
|
||||
let path = registry_index_path();
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => {
|
||||
let records: Vec<AssetRecord> = ron::from_str(&text).unwrap_or_default();
|
||||
AssetRegistry {
|
||||
records,
|
||||
index_dirty: false,
|
||||
}
|
||||
}
|
||||
Err(_) => AssetRegistry::default(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,711 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use settings::ProjectSettings;
|
||||
use shared::{
|
||||
ActorKind, AuthoringLightKind, ColliderDesc, ColorDesc, EditorVisibility, LightDesc,
|
||||
MaterialDesc, ModelRef, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
|
||||
PrimitiveShape, RigidBodyDesc,
|
||||
};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::asset_db::{
|
||||
find_asset_by_path, find_asset_mut_by_path, AssetRegistry, ModelPlacementMode,
|
||||
};
|
||||
use crate::assets::static_mesh::{
|
||||
load_static_mesh_manifest, refresh_static_mesh_artifact, renderer_from_manifest,
|
||||
};
|
||||
use crate::history::{spawn_with_history, EditorEntitySnapshot};
|
||||
|
||||
pub const BUILTINS_FOLDER: &str = "__builtins__";
|
||||
pub const ASSETS_ROOT: &str = "assets";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum AssetSelection {
|
||||
Builtin(String),
|
||||
File(String),
|
||||
}
|
||||
|
||||
impl AssetSelection {
|
||||
pub fn from_asset(asset: &EditorAsset) -> Self {
|
||||
match &asset.path {
|
||||
Some(path) => AssetSelection::File(path.clone()),
|
||||
None => AssetSelection::Builtin(asset.label.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum EditorAssetKind {
|
||||
Primitive(PrimitiveShape),
|
||||
Light(AuthoringLightKind),
|
||||
Model,
|
||||
Texture,
|
||||
Material,
|
||||
Level,
|
||||
Prefab,
|
||||
PostProcessVolume,
|
||||
PostProcessEffect,
|
||||
RenderingProfile,
|
||||
ShaderSchema,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EditorAsset {
|
||||
pub label: String,
|
||||
pub path: Option<String>,
|
||||
pub folder_path: String,
|
||||
pub kind: EditorAssetKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AssetFolder {
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
pub parent: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug)]
|
||||
pub struct EditorAssets {
|
||||
pub folders: Vec<AssetFolder>,
|
||||
pub assets: Vec<EditorAsset>,
|
||||
pub current_folder: String,
|
||||
pub selected: Option<AssetSelection>,
|
||||
pub dragging: Option<AssetSelection>,
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
impl Default for EditorAssets {
|
||||
fn default() -> Self {
|
||||
let mut assets = Self {
|
||||
folders: Vec::new(),
|
||||
assets: Vec::new(),
|
||||
current_folder: ASSETS_ROOT.to_string(),
|
||||
selected: None,
|
||||
dragging: None,
|
||||
status: "Assets not scanned yet".to_string(),
|
||||
};
|
||||
assets.refresh();
|
||||
assets
|
||||
}
|
||||
}
|
||||
|
||||
impl EditorAssets {
|
||||
pub fn refresh(&mut self) {
|
||||
self.folders.clear();
|
||||
self.assets.clear();
|
||||
|
||||
self.folders.push(AssetFolder {
|
||||
path: BUILTINS_FOLDER.to_string(),
|
||||
name: "Built-ins".to_string(),
|
||||
parent: None,
|
||||
});
|
||||
|
||||
register_folder_tree(&mut self.folders, ASSETS_ROOT);
|
||||
self.assets.extend(builtin_assets());
|
||||
scan_assets_directory(&mut self.assets);
|
||||
|
||||
if !self.folder_exists(&self.current_folder) {
|
||||
self.current_folder = ASSETS_ROOT.to_string();
|
||||
}
|
||||
|
||||
self.selected = self
|
||||
.selected
|
||||
.take()
|
||||
.filter(|selection| self.asset_for_selection(selection).is_some());
|
||||
|
||||
let folder_count = self.folders.len();
|
||||
self.status = format!(
|
||||
"Scanned {} assets in {} folders",
|
||||
self.assets.len(),
|
||||
folder_count
|
||||
);
|
||||
}
|
||||
|
||||
fn folder_exists(&self, path: &str) -> bool {
|
||||
self.folders.iter().any(|folder| folder.path == path)
|
||||
}
|
||||
|
||||
pub fn asset_for_selection(&self, selection: &AssetSelection) -> Option<&EditorAsset> {
|
||||
match selection {
|
||||
AssetSelection::Builtin(label) => self
|
||||
.assets
|
||||
.iter()
|
||||
.find(|asset| asset.path.is_none() && asset.label == *label),
|
||||
AssetSelection::File(path) => self
|
||||
.assets
|
||||
.iter()
|
||||
.find(|asset| asset.path.as_deref() == Some(path.as_str())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn selected_asset(&self) -> Option<&EditorAsset> {
|
||||
self.selected
|
||||
.as_ref()
|
||||
.and_then(|selection| self.asset_for_selection(selection))
|
||||
}
|
||||
|
||||
pub fn dragging_asset(&self) -> Option<&EditorAsset> {
|
||||
self.dragging
|
||||
.as_ref()
|
||||
.and_then(|selection| self.asset_for_selection(selection))
|
||||
}
|
||||
|
||||
pub fn select(&mut self, selection: AssetSelection) {
|
||||
if let Some(asset) = self.asset_for_selection(&selection).cloned() {
|
||||
self.selected = Some(selection);
|
||||
self.status = format!("Selected {}", asset.label);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_drag(&mut self, selection: AssetSelection) {
|
||||
if self.asset_for_selection(&selection).is_some() {
|
||||
self.dragging = Some(selection);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_drag(&mut self) {
|
||||
self.dragging = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EditorAssetsPlugin;
|
||||
|
||||
impl Plugin for EditorAssetsPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<EditorAssets>()
|
||||
.add_systems(Update, refresh_assets_on_settings_change);
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_assets_on_settings_change(
|
||||
settings: Res<settings::ProjectSettings>,
|
||||
mut assets: ResMut<EditorAssets>,
|
||||
) {
|
||||
if settings.is_changed() {
|
||||
assets.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
fn builtin_assets() -> Vec<EditorAsset> {
|
||||
vec![
|
||||
EditorAsset {
|
||||
label: "Cube".to_string(),
|
||||
path: None,
|
||||
folder_path: BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::Primitive(PrimitiveShape::Box),
|
||||
},
|
||||
EditorAsset {
|
||||
label: "Sphere".to_string(),
|
||||
path: None,
|
||||
folder_path: BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::Primitive(PrimitiveShape::Sphere),
|
||||
},
|
||||
EditorAsset {
|
||||
label: "Ramp".to_string(),
|
||||
path: None,
|
||||
folder_path: BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::Primitive(PrimitiveShape::Ramp),
|
||||
},
|
||||
EditorAsset {
|
||||
label: "Point Light".to_string(),
|
||||
path: None,
|
||||
folder_path: BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::Light(AuthoringLightKind::Point),
|
||||
},
|
||||
EditorAsset {
|
||||
label: "Spot Light".to_string(),
|
||||
path: None,
|
||||
folder_path: BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::Light(AuthoringLightKind::Spot),
|
||||
},
|
||||
EditorAsset {
|
||||
label: "Directional Light".to_string(),
|
||||
path: None,
|
||||
folder_path: BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::Light(AuthoringLightKind::Directional),
|
||||
},
|
||||
EditorAsset {
|
||||
label: "Post Process Volume".to_string(),
|
||||
path: None,
|
||||
folder_path: BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::PostProcessVolume,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn register_folder_tree(folders: &mut Vec<AssetFolder>, root: &str) {
|
||||
let normalized = normalize_path(root);
|
||||
if folders.iter().any(|folder| folder.path == normalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
let parent = parent_folder_path(&normalized);
|
||||
if let Some(ref parent_path) = parent {
|
||||
if !folders.iter().any(|folder| folder.path == *parent_path) {
|
||||
register_folder_tree(folders, parent_path);
|
||||
}
|
||||
}
|
||||
|
||||
folders.push(AssetFolder {
|
||||
name: folder_name(&normalized),
|
||||
path: normalized.clone(),
|
||||
parent,
|
||||
});
|
||||
|
||||
if Path::new(&normalized).is_dir() {
|
||||
let Ok(read_dir) = fs::read_dir(&normalized) else {
|
||||
return;
|
||||
};
|
||||
for entry in read_dir.flatten() {
|
||||
if entry.path().is_dir() {
|
||||
register_folder_tree(folders, &entry.path().to_string_lossy());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_assets_directory(assets: &mut Vec<EditorAsset>) {
|
||||
let root_path = Path::new(ASSETS_ROOT);
|
||||
if !root_path.exists() {
|
||||
return;
|
||||
}
|
||||
|
||||
for entry in WalkDir::new(root_path)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
if should_skip_asset_path(path) {
|
||||
continue;
|
||||
}
|
||||
if let Some(asset) = asset_from_file_path(path) {
|
||||
assets.push(asset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn should_skip_asset_path(path: &Path) -> bool {
|
||||
if path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.starts_with('.'))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
let normalized = normalize_asset_path(path);
|
||||
normalized == "assets/project.ron"
|
||||
|| normalized.starts_with("assets/.index/")
|
||||
|| normalized.starts_with(crate::assets::static_mesh::STATIC_MESH_ARTIFACT_DIR)
|
||||
}
|
||||
|
||||
fn asset_from_file_path(path: &Path) -> Option<EditorAsset> {
|
||||
let extension = path.extension()?.to_str()?.to_ascii_lowercase();
|
||||
let (kinds, extensions) = match extension.as_str() {
|
||||
"gltf" | "glb" | "fbx" => (vec![EditorAssetKind::Model], vec!["gltf", "glb", "fbx"]),
|
||||
"png" | "jpg" | "jpeg" | "webp" | "ktx2" => (
|
||||
vec![EditorAssetKind::Texture],
|
||||
vec!["png", "jpg", "jpeg", "webp", "ktx2"],
|
||||
),
|
||||
"ron" | "mat" | "material" => {
|
||||
if path.to_string_lossy().contains("/materials/") {
|
||||
(
|
||||
vec![EditorAssetKind::Material],
|
||||
vec!["ron", "mat", "material"],
|
||||
)
|
||||
} else if path.to_string_lossy().contains("/post_fx/") {
|
||||
(vec![EditorAssetKind::PostProcessEffect], vec!["ron"])
|
||||
} else if path.to_string_lossy().contains("/rendering_profiles/") {
|
||||
(vec![EditorAssetKind::RenderingProfile], vec!["ron"])
|
||||
} else if path.to_string_lossy().contains("/shaders/") {
|
||||
(vec![EditorAssetKind::ShaderSchema], vec!["ron"])
|
||||
} else {
|
||||
(
|
||||
vec![EditorAssetKind::Level, EditorAssetKind::Prefab],
|
||||
vec!["ron"],
|
||||
)
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
if !has_extension(path, &extensions) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let path_string = normalize_asset_path(path);
|
||||
let folder_path = parent_folder_path(&path_string).unwrap_or_else(|| ASSETS_ROOT.to_string());
|
||||
let label = path
|
||||
.file_stem()
|
||||
.and_then(|stem| stem.to_str())
|
||||
.unwrap_or(&path_string)
|
||||
.to_string();
|
||||
let kind = if kinds.len() == 2 && path_string.ends_with(".scn.ron") {
|
||||
kinds[1].clone()
|
||||
} else {
|
||||
kinds[0].clone()
|
||||
};
|
||||
|
||||
Some(EditorAsset {
|
||||
label,
|
||||
path: Some(path_string),
|
||||
folder_path,
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_path(path: &str) -> String {
|
||||
path.replace('\\', "/").trim_end_matches('/').to_string()
|
||||
}
|
||||
|
||||
fn normalize_asset_path(path: &Path) -> String {
|
||||
let raw = path.to_string_lossy().replace('\\', "/");
|
||||
raw.strip_prefix("assets/")
|
||||
.or_else(|| raw.strip_prefix("./assets/"))
|
||||
.map(|rest| format!("assets/{rest}"))
|
||||
.unwrap_or(raw)
|
||||
}
|
||||
|
||||
/// Path relative to Bevy's `assets/` folder for [`AssetServer::load`].
|
||||
pub fn asset_server_path(catalog_path: &str) -> String {
|
||||
shared::asset_server_path(catalog_path)
|
||||
}
|
||||
|
||||
fn parent_folder_path(path: &str) -> Option<String> {
|
||||
let normalized = normalize_path(path);
|
||||
normalized
|
||||
.rfind('/')
|
||||
.map(|index| normalized[..index].to_string())
|
||||
}
|
||||
|
||||
fn folder_name(path: &str) -> String {
|
||||
Path::new(path)
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or(path)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn has_extension(path: &Path, extensions: &[&str]) -> bool {
|
||||
path.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| {
|
||||
extensions
|
||||
.iter()
|
||||
.any(|candidate| ext.eq_ignore_ascii_case(candidate))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> Option<EditorEntitySnapshot> {
|
||||
let mut snapshot = EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: ActorKind::Empty,
|
||||
actor_name: None,
|
||||
name: Some(asset.label.clone()),
|
||||
transform: Transform::from_translation(translation),
|
||||
primitive: None,
|
||||
static_mesh_renderer: None,
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: None,
|
||||
collider: None,
|
||||
physics: None,
|
||||
light: None,
|
||||
player_spawn: false,
|
||||
model: None,
|
||||
prefab: None,
|
||||
prefab_instance: None,
|
||||
weapon_spawn: None,
|
||||
trigger_volume: None,
|
||||
post_process_volume: None,
|
||||
team_spawn: None,
|
||||
objective: None,
|
||||
hierarchy_sibling_index: 0,
|
||||
editor_visibility: EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
};
|
||||
|
||||
match &asset.kind {
|
||||
EditorAssetKind::Primitive(shape) => {
|
||||
snapshot.actor_kind = ActorKind::StaticMesh;
|
||||
let size = match shape {
|
||||
PrimitiveShape::Box => Vec3::ONE,
|
||||
PrimitiveShape::Sphere => Vec3::splat(1.5),
|
||||
PrimitiveShape::Ramp => Vec3::new(4.0, 0.4, 5.0),
|
||||
};
|
||||
snapshot.primitive = Some(match shape {
|
||||
PrimitiveShape::Box => Primitive::cuboid(size),
|
||||
PrimitiveShape::Sphere => Primitive::sphere(size.x * 0.5),
|
||||
PrimitiveShape::Ramp => Primitive::ramp(size),
|
||||
});
|
||||
snapshot.material = Some(default_material_for(shape));
|
||||
snapshot.rigid_body = Some(RigidBodyDesc::default());
|
||||
snapshot.collider = Some(match shape {
|
||||
PrimitiveShape::Sphere => ColliderDesc::static_sphere(size.x * 0.5),
|
||||
_ => ColliderDesc::static_cuboid(size),
|
||||
});
|
||||
if matches!(shape, PrimitiveShape::Ramp) {
|
||||
snapshot.transform.rotation = Quat::from_rotation_x(-std::f32::consts::PI / 9.0);
|
||||
snapshot.transform.translation.y += 1.0;
|
||||
} else {
|
||||
snapshot.transform.translation.y += size.y * 0.5;
|
||||
}
|
||||
}
|
||||
EditorAssetKind::Light(kind) => {
|
||||
snapshot.actor_kind = ActorKind::Light;
|
||||
snapshot.light = Some(LightDesc::for_kind(*kind));
|
||||
snapshot.transform.translation.y += 3.0;
|
||||
}
|
||||
EditorAssetKind::PostProcessVolume => {
|
||||
snapshot.actor_kind = ActorKind::PostProcessVolume;
|
||||
snapshot.post_process_volume = Some(PostProcessVolumeDesc {
|
||||
half_extents: Vec3::new(4.0, 2.0, 4.0),
|
||||
..Default::default()
|
||||
});
|
||||
snapshot.transform.translation.y += 2.0;
|
||||
}
|
||||
EditorAssetKind::Model => {
|
||||
snapshot.actor_kind = ActorKind::ImportedModel;
|
||||
let path = asset.path.as_ref()?;
|
||||
snapshot.model = Some(ModelRef::new(path.clone()));
|
||||
snapshot.transform.translation.y += 0.1;
|
||||
}
|
||||
EditorAssetKind::Prefab | EditorAssetKind::Level => {
|
||||
snapshot.actor_kind = ActorKind::PrefabAnchor;
|
||||
let path = asset.path.as_ref()?;
|
||||
snapshot.prefab = Some(PrefabRef::new(path.clone()));
|
||||
}
|
||||
EditorAssetKind::Texture
|
||||
| EditorAssetKind::Material
|
||||
| EditorAssetKind::PostProcessEffect
|
||||
| EditorAssetKind::RenderingProfile
|
||||
| EditorAssetKind::ShaderSchema => return None,
|
||||
}
|
||||
|
||||
Some(snapshot)
|
||||
}
|
||||
|
||||
pub fn spawn_asset_at(world: &mut World, asset: &EditorAsset, translation: Vec3) -> Option<Entity> {
|
||||
let mut snapshot = snapshot_for_asset(asset, translation)?;
|
||||
if let Some(light) = snapshot.light.as_mut() {
|
||||
if matches!(light.kind, AuthoringLightKind::Directional) {
|
||||
light.intensity = world
|
||||
.resource::<ProjectSettings>()
|
||||
.rendering
|
||||
.sun_illuminance;
|
||||
}
|
||||
}
|
||||
if let Some(path) = asset.path.as_ref() {
|
||||
let record = world
|
||||
.get_resource::<AssetRegistry>()
|
||||
.and_then(|registry| find_asset_by_path(registry, path));
|
||||
if let Some(record) = record {
|
||||
match asset.kind {
|
||||
EditorAssetKind::Model => {
|
||||
snapshot.transform.scale *= record.import_settings.scale;
|
||||
if matches!(
|
||||
record.import_settings.placement_mode,
|
||||
ModelPlacementMode::StaticAsset
|
||||
) {
|
||||
if let Some(renderer) = static_mesh_renderer_for_asset(world, path) {
|
||||
let collider = record
|
||||
.import_settings
|
||||
.generate_collider
|
||||
.then(|| static_mesh_collider_for_renderer(&renderer));
|
||||
apply_static_mesh_placement_mode(
|
||||
&mut snapshot,
|
||||
renderer,
|
||||
collider,
|
||||
record.import_settings.hierarchy_mode,
|
||||
);
|
||||
} else {
|
||||
warn!(
|
||||
"Static mesh placement fell back to SceneRoot for {} because no renderer manifest was available",
|
||||
path
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
EditorAssetKind::Prefab => {
|
||||
snapshot.prefab_instance =
|
||||
Some(PrefabInstance::new(record.id.as_string(), path.clone()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(spawn_with_history(world, snapshot))
|
||||
}
|
||||
|
||||
fn apply_static_mesh_placement_mode(
|
||||
snapshot: &mut EditorEntitySnapshot,
|
||||
renderer: shared::StaticMeshRenderer,
|
||||
collider: Option<ColliderDesc>,
|
||||
hierarchy_mode: crate::asset_db::ModelHierarchyMode,
|
||||
) {
|
||||
snapshot.model = None;
|
||||
match hierarchy_mode {
|
||||
crate::asset_db::ModelHierarchyMode::SingleActor => {
|
||||
snapshot.actor_kind = ActorKind::StaticMesh;
|
||||
snapshot.static_mesh_renderer = Some(renderer);
|
||||
if let Some(collider) = collider {
|
||||
snapshot.rigid_body = Some(RigidBodyDesc::default());
|
||||
snapshot.collider = Some(collider);
|
||||
}
|
||||
}
|
||||
crate::asset_db::ModelHierarchyMode::SourceHierarchy => {
|
||||
snapshot.actor_kind = ActorKind::Empty;
|
||||
snapshot.static_mesh_renderer = None;
|
||||
snapshot.children = renderer
|
||||
.slots
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, mut entry)| {
|
||||
let transform = entry.local_transform;
|
||||
let collider = collider
|
||||
.as_ref()
|
||||
.map(|_| ColliderDesc::static_mesh(vec![entry.mesh.clone()]));
|
||||
entry.local_transform = Transform::default();
|
||||
EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: ActorKind::StaticMesh,
|
||||
actor_name: None,
|
||||
name: Some(if entry.name.trim().is_empty() {
|
||||
format!("Mesh Part {index}")
|
||||
} else {
|
||||
entry.name.clone()
|
||||
}),
|
||||
transform,
|
||||
primitive: None,
|
||||
static_mesh_renderer: Some(shared::StaticMeshRenderer::single(entry)),
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: collider.as_ref().map(|_| RigidBodyDesc::default()),
|
||||
collider,
|
||||
physics: None,
|
||||
light: None,
|
||||
player_spawn: false,
|
||||
model: None,
|
||||
prefab: None,
|
||||
prefab_instance: None,
|
||||
weapon_spawn: None,
|
||||
trigger_volume: None,
|
||||
post_process_volume: None,
|
||||
team_spawn: None,
|
||||
objective: None,
|
||||
hierarchy_sibling_index: index as i32,
|
||||
editor_visibility: EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn static_mesh_collider_for_renderer(renderer: &shared::StaticMeshRenderer) -> ColliderDesc {
|
||||
ColliderDesc::static_mesh(
|
||||
renderer
|
||||
.slots
|
||||
.iter()
|
||||
.map(|slot| slot.mesh.clone())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn static_mesh_renderer_for_asset(
|
||||
world: &mut World,
|
||||
path: &str,
|
||||
) -> Option<shared::StaticMeshRenderer> {
|
||||
let mut manifest_path = None;
|
||||
if let Some(mut registry) = world.get_resource_mut::<AssetRegistry>() {
|
||||
let mut renderer = None;
|
||||
if let Some(record) = find_asset_mut_by_path(&mut registry, path) {
|
||||
match refresh_static_mesh_artifact(record) {
|
||||
Ok(manifest) => {
|
||||
renderer = Some(renderer_from_manifest(&manifest, &record.import_settings));
|
||||
registry.index_dirty = true;
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("Static mesh manifest refresh failed for {path}: {error}");
|
||||
manifest_path = record.import_settings.static_mesh_manifest_path.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
if renderer.is_some() {
|
||||
if let Err(error) = crate::asset_db::save_registry(®istry) {
|
||||
warn!("Asset registry save failed after static mesh refresh: {error}");
|
||||
} else {
|
||||
registry.index_dirty = false;
|
||||
}
|
||||
return renderer;
|
||||
}
|
||||
}
|
||||
|
||||
let manifest_path = manifest_path?;
|
||||
let registry = world.get_resource::<AssetRegistry>()?;
|
||||
let record = find_asset_by_path(registry, path)?;
|
||||
let manifest = load_static_mesh_manifest(&manifest_path).ok()?;
|
||||
Some(renderer_from_manifest(&manifest, &record.import_settings))
|
||||
}
|
||||
|
||||
pub fn import_external_assets(paths: &[PathBuf]) -> Result<usize, String> {
|
||||
let mut copied = 0;
|
||||
for source in paths {
|
||||
let Some(file_name) = source.file_name() else {
|
||||
continue;
|
||||
};
|
||||
let Some(extension) = source.extension().and_then(|ext| ext.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
let dest_dir = import_dir_for_extension(extension);
|
||||
if extension.eq_ignore_ascii_case("fbx") {
|
||||
super::import::copy_fbx_with_sidecar(source, Path::new(dest_dir))?;
|
||||
copied += 1;
|
||||
continue;
|
||||
}
|
||||
fs::create_dir_all(dest_dir)
|
||||
.map_err(|err| format!("could not create {dest_dir}: {err}"))?;
|
||||
let dest = Path::new(dest_dir).join(file_name);
|
||||
fs::copy(source, &dest).map_err(|err| {
|
||||
format!(
|
||||
"could not copy {} to {}: {err}",
|
||||
source.display(),
|
||||
dest.display()
|
||||
)
|
||||
})?;
|
||||
copied += 1;
|
||||
}
|
||||
Ok(copied)
|
||||
}
|
||||
|
||||
fn import_dir_for_extension(extension: &str) -> &'static str {
|
||||
match extension.to_ascii_lowercase().as_str() {
|
||||
"gltf" | "glb" | "fbx" => "assets/models",
|
||||
"png" | "jpg" | "jpeg" | "webp" | "ktx2" => "assets/textures",
|
||||
"ron" => "assets/levels",
|
||||
"mat" | "material" => "assets/materials",
|
||||
_ => "assets",
|
||||
}
|
||||
}
|
||||
|
||||
fn default_material_for(shape: &PrimitiveShape) -> MaterialDesc {
|
||||
match shape {
|
||||
PrimitiveShape::Box => MaterialDesc::default(),
|
||||
PrimitiveShape::Sphere => MaterialDesc::new(ColorDesc::srgb(0.9, 0.9, 0.92), 1.0, 0.25),
|
||||
PrimitiveShape::Ramp => MaterialDesc::new(ColorDesc::srgb(0.30, 0.45, 0.70), 0.05, 0.55),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn asset_cache_key(asset: &EditorAsset) -> String {
|
||||
match &asset.path {
|
||||
Some(path) => path.clone(),
|
||||
None => format!("builtin:{}", asset.label),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! External asset import helpers (FBX sidecar folders, etc.).
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Copies an FBX file and its sibling `.fbm` embedded-texture folder when present.
|
||||
pub fn copy_fbx_with_sidecar(source: &Path, dest_dir: &Path) -> Result<(), String> {
|
||||
let Some(file_name) = source.file_name() else {
|
||||
return Err("FBX import path has no file name".into());
|
||||
};
|
||||
fs::create_dir_all(dest_dir)
|
||||
.map_err(|err| format!("could not create {}: {err}", dest_dir.display()))?;
|
||||
let dest = dest_dir.join(file_name);
|
||||
fs::copy(source, &dest).map_err(|err| {
|
||||
format!(
|
||||
"could not copy {} to {}: {err}",
|
||||
source.display(),
|
||||
dest.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
if let Some(fbm_dir) = fbm_sidecar_dir(source) {
|
||||
if fbm_dir.is_dir() {
|
||||
let dest_fbm = dest_dir.join(fbm_dir.file_name().unwrap_or_default());
|
||||
copy_dir_recursive(&fbm_dir, &dest_fbm)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fbm_sidecar_dir(source: &Path) -> Option<PathBuf> {
|
||||
let stem = source.file_stem()?.to_str()?;
|
||||
let parent = source.parent()?;
|
||||
Some(parent.join(format!("{stem}.fbm")))
|
||||
}
|
||||
|
||||
fn copy_dir_recursive(source: &Path, dest: &Path) -> Result<(), String> {
|
||||
fs::create_dir_all(dest)
|
||||
.map_err(|err| format!("could not create {}: {err}", dest.display()))?;
|
||||
for entry in fs::read_dir(source).map_err(|err| err.to_string())? {
|
||||
let entry = entry.map_err(|err| err.to_string())?;
|
||||
let src_path = entry.path();
|
||||
let dest_path = dest.join(entry.file_name());
|
||||
if src_path.is_dir() {
|
||||
copy_dir_recursive(&src_path, &dest_path)?;
|
||||
} else {
|
||||
fs::copy(&src_path, &dest_path).map_err(|err| {
|
||||
format!(
|
||||
"could not copy {} to {}: {err}",
|
||||
src_path.display(),
|
||||
dest_path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::fbm_sidecar_dir;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn fbm_sidecar_path() {
|
||||
assert_eq!(
|
||||
fbm_sidecar_dir(Path::new("/tmp/Character.fbx")),
|
||||
Some(Path::new("/tmp/Character.fbm").to_path_buf())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Material asset loading and inspector/browser integration.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use shared::{LevelObject, MaterialAsset, MaterialDesc};
|
||||
|
||||
use crate::assets::{EditorAsset, EditorAssetKind, EditorAssets};
|
||||
use crate::history::set_material_with_history;
|
||||
use crate::ui::inspector::property_row;
|
||||
|
||||
pub fn load_material_asset(catalog_path: &str) -> Result<MaterialAsset, String> {
|
||||
MaterialAsset::load_from_path(catalog_path)
|
||||
}
|
||||
|
||||
pub fn material_desc_from_asset(catalog_path: &str) -> Result<MaterialDesc, String> {
|
||||
let asset = load_material_asset(catalog_path)?;
|
||||
let mut desc = asset.material;
|
||||
desc.material_asset_path = Some(catalog_path.to_string());
|
||||
Ok(desc)
|
||||
}
|
||||
|
||||
pub fn apply_material_asset_to_selection(
|
||||
world: &mut World,
|
||||
asset: &EditorAsset,
|
||||
selected: &bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities,
|
||||
) {
|
||||
let Some(path) = asset.path.clone() else {
|
||||
return;
|
||||
};
|
||||
let desc = match material_desc_from_asset(&path) {
|
||||
Ok(desc) => desc,
|
||||
Err(err) => {
|
||||
world.resource_mut::<crate::scene_io::SceneIo>().status = err;
|
||||
return;
|
||||
}
|
||||
};
|
||||
for entity in crate::ui::helpers::selected_level_entities(world, selected) {
|
||||
if world.get::<LevelObject>(entity).is_none() {
|
||||
continue;
|
||||
}
|
||||
if world.get::<MaterialDesc>(entity).is_none() {
|
||||
world.entity_mut(entity).insert(desc.clone());
|
||||
}
|
||||
set_material_with_history(world, entity, desc.clone());
|
||||
}
|
||||
world.resource_mut::<crate::scene_io::SceneIo>().status =
|
||||
format!("Applied material {}", asset.label);
|
||||
}
|
||||
|
||||
pub fn material_asset_picker_ui(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
_entity: Entity,
|
||||
material: &mut MaterialDesc,
|
||||
_original: &MaterialDesc,
|
||||
) -> bool {
|
||||
let assets: Vec<(String, String)> = world
|
||||
.resource::<EditorAssets>()
|
||||
.assets
|
||||
.iter()
|
||||
.filter(|a| matches!(a.kind, EditorAssetKind::Material))
|
||||
.filter_map(|a| Some((a.label.clone(), a.path.clone()?)))
|
||||
.collect();
|
||||
|
||||
let current = material.material_asset_path.clone().unwrap_or_default();
|
||||
let mut selected_label = assets
|
||||
.iter()
|
||||
.find(|(_, path)| path == ¤t)
|
||||
.map(|(label, _)| label.clone())
|
||||
.unwrap_or_else(|| "(none)".to_string());
|
||||
|
||||
let mut changed = false;
|
||||
property_row(ui, "Material asset", |ui| {
|
||||
egui::ComboBox::from_id_salt("material_asset_picker")
|
||||
.selected_text(&selected_label)
|
||||
.show_ui(ui, |ui| {
|
||||
if ui.selectable_label(current.is_empty(), "(none)").clicked() {
|
||||
material.material_asset_path = None;
|
||||
selected_label = "(none)".into();
|
||||
changed = true;
|
||||
}
|
||||
for (label, path) in &assets {
|
||||
if ui
|
||||
.selectable_label(&selected_label == label, label)
|
||||
.clicked()
|
||||
{
|
||||
if let Ok(desc) = material_desc_from_asset(path) {
|
||||
*material = desc;
|
||||
selected_label = label.clone();
|
||||
changed = true;
|
||||
} else {
|
||||
world.resource_mut::<crate::scene_io::SceneIo>().status =
|
||||
format!("Could not load material {path}");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
changed
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Asset catalog, database, thumbnails, materials, and prefab overrides.
|
||||
|
||||
pub mod asset_db;
|
||||
mod catalog;
|
||||
mod import;
|
||||
pub mod materials;
|
||||
pub mod prefab_overrides;
|
||||
pub mod static_mesh;
|
||||
pub mod thumbnails;
|
||||
|
||||
pub use catalog::*;
|
||||
pub use thumbnails::{
|
||||
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_folder_thumbnails,
|
||||
AssetThumbnailCache, ThumbnailCacheSnapshot, ThumbnailState, ThumbnailsPlugin,
|
||||
};
|
||||
@@ -0,0 +1,390 @@
|
||||
//! Prefab instance overrides — apply/revert per field group (v2).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
use scene::{migrate_scene_text, strip_schema_version, validate_level_text};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shared::{EditorVisibility, MaterialDesc, PrefabInstance};
|
||||
|
||||
use crate::history::{set_material_with_history, set_transform_with_history};
|
||||
use crate::ui::inspector::{
|
||||
apply_component_card_response, component_card, component_card_context, property_row,
|
||||
ComponentCardOptions,
|
||||
};
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct PrefabOverrideClipboard {
|
||||
pub property_path: String,
|
||||
pub value_ron: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PrefabOverrides {
|
||||
#[serde(default)]
|
||||
pub transform: Option<Transform>,
|
||||
#[serde(default)]
|
||||
pub material: Option<MaterialDesc>,
|
||||
#[serde(default)]
|
||||
pub child_visibility: HashMap<String, bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PrefabOverrideField {
|
||||
Transform,
|
||||
Material,
|
||||
ChildVisibility,
|
||||
}
|
||||
|
||||
pub fn read_overrides(instance: &PrefabInstance) -> PrefabOverrides {
|
||||
instance
|
||||
.overrides_ron
|
||||
.as_ref()
|
||||
.and_then(|ron| ron::from_str(ron).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn write_overrides(world: &mut World, entity: Entity, overrides: &PrefabOverrides) {
|
||||
let Some(mut instance) = world.get::<PrefabInstance>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
instance.overrides_ron = if overrides == &PrefabOverrides::default() {
|
||||
None
|
||||
} else {
|
||||
Some(ron::to_string(overrides).unwrap_or_default())
|
||||
};
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert(instance);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_override(overrides: &PrefabOverrides, field: PrefabOverrideField) -> bool {
|
||||
match field {
|
||||
PrefabOverrideField::Transform => overrides.transform.is_some(),
|
||||
PrefabOverrideField::Material => overrides.material.is_some(),
|
||||
PrefabOverrideField::ChildVisibility => !overrides.child_visibility.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capture_transform_override(world: &mut World, entity: Entity) {
|
||||
let Some(transform) = world.get::<Transform>(entity).copied() else {
|
||||
return;
|
||||
};
|
||||
let Some(instance) = world.get::<PrefabInstance>(entity) else {
|
||||
return;
|
||||
};
|
||||
let mut overrides = read_overrides(instance);
|
||||
overrides.transform = Some(transform);
|
||||
write_overrides(world, entity, &overrides);
|
||||
}
|
||||
|
||||
pub fn revert_transform_override(world: &mut World, entity: Entity) {
|
||||
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(old) = world.get::<Transform>(entity).copied() else {
|
||||
return;
|
||||
};
|
||||
let Some(source_transform) = prefab_root_transform(&instance.source_path) else {
|
||||
world.resource_mut::<crate::scene_io::SceneIo>().status =
|
||||
"Could not read prefab source for revert".into();
|
||||
return;
|
||||
};
|
||||
set_transform_with_history(world, entity, old, source_transform);
|
||||
let mut overrides = read_overrides(&instance);
|
||||
overrides.transform = None;
|
||||
write_overrides(world, entity, &overrides);
|
||||
}
|
||||
|
||||
pub fn apply_material_override(world: &mut World, entity: Entity) {
|
||||
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(material) = world.get::<MaterialDesc>(entity).cloned() else {
|
||||
world.resource_mut::<crate::scene_io::SceneIo>().status =
|
||||
"Prefab instance has no MaterialDesc to capture".into();
|
||||
return;
|
||||
};
|
||||
let mut overrides = read_overrides(&instance);
|
||||
overrides.material = Some(material);
|
||||
write_overrides(world, entity, &overrides);
|
||||
world.resource_mut::<crate::scene_io::SceneIo>().status = "Material override applied".into();
|
||||
}
|
||||
|
||||
pub fn revert_material_override(world: &mut World, entity: Entity) {
|
||||
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(source_material) = prefab_root_material(&instance.source_path) else {
|
||||
world.resource_mut::<crate::scene_io::SceneIo>().status =
|
||||
"Could not read prefab source material".into();
|
||||
return;
|
||||
};
|
||||
let old = world.get::<MaterialDesc>(entity).cloned();
|
||||
if old.is_some() {
|
||||
set_material_with_history(world, entity, source_material.clone());
|
||||
} else {
|
||||
world.entity_mut(entity).insert(source_material.clone());
|
||||
}
|
||||
let mut overrides = read_overrides(&instance);
|
||||
overrides.material = None;
|
||||
write_overrides(world, entity, &overrides);
|
||||
}
|
||||
|
||||
pub fn apply_child_visibility_override(world: &mut World, entity: Entity, child: Entity) {
|
||||
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(name) = world.get::<Name>(child).map(|n| n.to_string()) else {
|
||||
return;
|
||||
};
|
||||
let visible = world
|
||||
.get::<EditorVisibility>(child)
|
||||
.map(|v| v.visible)
|
||||
.unwrap_or(true);
|
||||
|
||||
let mut overrides = read_overrides(&instance);
|
||||
overrides.child_visibility.insert(name, visible);
|
||||
write_overrides(world, entity, &overrides);
|
||||
}
|
||||
|
||||
pub fn revert_child_visibility_overrides(world: &mut World, entity: Entity) {
|
||||
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
for child in prefab_instance_children(world, entity) {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(child) {
|
||||
entity_mut.remove::<EditorVisibility>();
|
||||
}
|
||||
}
|
||||
let mut overrides = read_overrides(&instance);
|
||||
overrides.child_visibility.clear();
|
||||
write_overrides(world, entity, &overrides);
|
||||
}
|
||||
|
||||
pub fn apply_stored_overrides(world: &mut World, entity: Entity) {
|
||||
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let overrides = read_overrides(&instance);
|
||||
|
||||
if let Some(transform) = overrides.transform {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert(transform);
|
||||
}
|
||||
}
|
||||
if let Some(material) = overrides.material {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert(material);
|
||||
}
|
||||
}
|
||||
for child in prefab_instance_children(world, entity) {
|
||||
let Some(name) = world.get::<Name>(child).map(|n| n.to_string()) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(&visible) = overrides.child_visibility.get(&name) {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(child) {
|
||||
entity_mut.insert(EditorVisibility { visible });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prefab_instance_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let overrides = read_overrides(&instance);
|
||||
|
||||
let card = component_card_context(
|
||||
world,
|
||||
entity,
|
||||
ComponentCardOptions::removable(
|
||||
shared::COMPONENT_PREFAB_INSTANCE,
|
||||
"Prefab Instance",
|
||||
icons::PACKAGE,
|
||||
),
|
||||
);
|
||||
let card_response = component_card(ui, &card, |ui| {
|
||||
property_row(ui, "Asset ID", |ui| {
|
||||
ui.add(egui::Label::new(instance.asset_id.as_str()).truncate());
|
||||
});
|
||||
property_row(ui, "Source", |ui| {
|
||||
ui.add(egui::Label::new(instance.source_path.as_str()).truncate());
|
||||
});
|
||||
|
||||
ui.collapsing("Transform override", |ui| {
|
||||
let active = has_override(&overrides, PrefabOverrideField::Transform);
|
||||
if active {
|
||||
ui.label(egui::RichText::new("Override active").weak());
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button("Apply").clicked() {
|
||||
capture_transform_override(world, entity);
|
||||
world.resource_mut::<crate::scene_io::SceneIo>().status =
|
||||
"Transform override saved".into();
|
||||
}
|
||||
if ui
|
||||
.add_enabled(active, egui::Button::new("Revert"))
|
||||
.clicked()
|
||||
{
|
||||
revert_transform_override(world, entity);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ui.collapsing("Material override", |ui| {
|
||||
let active = has_override(&overrides, PrefabOverrideField::Material);
|
||||
if active {
|
||||
ui.label(egui::RichText::new("Override active").weak());
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button("Apply").clicked() {
|
||||
apply_material_override(world, entity);
|
||||
}
|
||||
if ui
|
||||
.add_enabled(active, egui::Button::new("Revert"))
|
||||
.clicked()
|
||||
{
|
||||
revert_material_override(world, entity);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ui.collapsing("Child visibility overrides", |ui| {
|
||||
let active = has_override(&overrides, PrefabOverrideField::ChildVisibility);
|
||||
if active {
|
||||
ui.label(egui::RichText::new("Overrides stored by child name").weak());
|
||||
}
|
||||
for child in prefab_instance_children(world, entity) {
|
||||
let name = world
|
||||
.get::<Name>(child)
|
||||
.map(|n| n.to_string())
|
||||
.unwrap_or_else(|| format!("{child:?}"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.add(egui::Label::new(name).truncate());
|
||||
if ui.small_button("Apply").clicked() {
|
||||
apply_child_visibility_override(world, entity, child);
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui
|
||||
.add_enabled(active, egui::Button::new("Revert all"))
|
||||
.clicked()
|
||||
{
|
||||
revert_child_visibility_overrides(world, entity);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button("Unpack Instance").clicked() {
|
||||
crate::history::unpack_prefab_instance(world, entity);
|
||||
}
|
||||
});
|
||||
});
|
||||
apply_component_card_response(world, entity, card_response);
|
||||
}
|
||||
|
||||
fn prefab_instance_children(world: &World, root: Entity) -> Vec<Entity> {
|
||||
let mut children = Vec::new();
|
||||
let mut stack = Vec::new();
|
||||
if let Some(kids) = world.get::<Children>(root) {
|
||||
stack.extend(kids.iter());
|
||||
}
|
||||
while let Some(entity) = stack.pop() {
|
||||
children.push(entity);
|
||||
if let Some(kids) = world.get::<Children>(entity) {
|
||||
stack.extend(kids.iter());
|
||||
}
|
||||
}
|
||||
children
|
||||
}
|
||||
|
||||
fn prefab_root_transform(source_path: &str) -> Option<Transform> {
|
||||
parse_prefab_root_component::<Transform>(source_path, "Transform")
|
||||
}
|
||||
|
||||
fn prefab_root_material(source_path: &str) -> Option<MaterialDesc> {
|
||||
parse_prefab_root_component::<MaterialDesc>(source_path, "MaterialDesc")
|
||||
}
|
||||
|
||||
fn parse_prefab_root_component<T: serde::de::DeserializeOwned>(
|
||||
source_path: &str,
|
||||
type_name: &str,
|
||||
) -> Option<T> {
|
||||
let path = Path::new(source_path);
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
validate_level_text(&text).ok()?;
|
||||
let body = strip_schema_version(&migrate_scene_text(&text).ok()?).ok()?;
|
||||
let root_tuple = body.trim().trim_start_matches('(').trim_end_matches(')');
|
||||
for segment in split_top_level_fields(root_tuple) {
|
||||
let segment = segment.trim();
|
||||
if segment.starts_with("entities:") {
|
||||
let entities_body = segment.trim_start_matches("entities:").trim();
|
||||
return parse_first_entity_component(entities_body, type_name);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn split_top_level_fields(input: &str) -> Vec<String> {
|
||||
let mut fields = Vec::new();
|
||||
let mut depth: i32 = 0;
|
||||
let mut start = 0;
|
||||
for (index, ch) in input.char_indices() {
|
||||
match ch {
|
||||
'(' | '{' => depth += 1,
|
||||
')' | '}' => depth = depth.saturating_sub(1),
|
||||
',' if depth == 0 => {
|
||||
fields.push(input[start..index].to_string());
|
||||
start = index + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if start < input.len() {
|
||||
fields.push(input[start..].to_string());
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
fn parse_first_entity_component<T: serde::de::DeserializeOwned>(
|
||||
entities_body: &str,
|
||||
type_name: &str,
|
||||
) -> Option<T> {
|
||||
let trimmed = entities_body.trim();
|
||||
let inner = trimmed.strip_prefix('{')?.strip_suffix('}')?.trim();
|
||||
let first_entity = inner.split(',').next()?.trim();
|
||||
let components = first_entity
|
||||
.split(':')
|
||||
.nth(1)?
|
||||
.trim()
|
||||
.strip_prefix('(')?
|
||||
.strip_suffix(')')?;
|
||||
for component in split_top_level_fields(components) {
|
||||
if component.contains(type_name) {
|
||||
return ron::from_str::<T>(&format!("({component})")).ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn list_prefab_dependencies(path: &str) -> Vec<String> {
|
||||
vec![path.to_string()]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_overrides_roundtrip() {
|
||||
let instance = PrefabInstance::new("id", "assets/prefabs/test.scn.ron");
|
||||
assert_eq!(read_overrides(&instance), PrefabOverrides::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
//! Normalized static mesh artifacts generated from model source files.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use bevy::gltf::GltfAssetLabel;
|
||||
use bevy::prelude::*;
|
||||
use bevy_ufbx::label::FbxAssetLabel;
|
||||
use bevy_ufbx::mesh::group_faces_by_material;
|
||||
use bevy_ufbx::utils::convert_matrix;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::asset_db::{
|
||||
AssetRecord, ImportSettings, MaterialImportPolicy, ModelHierarchyMode, ModelPlacementMode,
|
||||
};
|
||||
use shared::{ComponentInstanceId, EditorAssetRef, StaticMeshRenderer, StaticMeshRendererEntry};
|
||||
|
||||
pub const STATIC_MESH_MANIFEST_SCHEMA: u32 = 1;
|
||||
pub const STATIC_MESH_ARTIFACT_DIR: &str = "assets/meshes/generated";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct StaticMeshManifest {
|
||||
pub schema_version: u32,
|
||||
pub asset_id: String,
|
||||
pub label: String,
|
||||
pub source: StaticMeshSource,
|
||||
pub import: StaticMeshImportSnapshot,
|
||||
pub metadata: StaticMeshMetadata,
|
||||
pub parts: Vec<StaticMeshPart>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct StaticMeshSource {
|
||||
pub path: String,
|
||||
pub format: String,
|
||||
pub fingerprint: StaticMeshSourceFingerprint,
|
||||
pub dependencies: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct StaticMeshSourceFingerprint {
|
||||
pub byte_len: u64,
|
||||
pub modified_unix_secs: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct StaticMeshImportSnapshot {
|
||||
pub scale: f32,
|
||||
pub generate_collider: bool,
|
||||
pub lod0_only: bool,
|
||||
pub placement_mode: ModelPlacementMode,
|
||||
pub hierarchy_mode: ModelHierarchyMode,
|
||||
pub material_policy: MaterialImportPolicy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct StaticMeshMetadata {
|
||||
pub mesh_count: usize,
|
||||
pub material_count: usize,
|
||||
pub node_count: usize,
|
||||
pub animation_count: usize,
|
||||
pub skin_count: usize,
|
||||
pub light_count: usize,
|
||||
pub camera_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct StaticMeshPart {
|
||||
#[serde(default)]
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub mesh_label: String,
|
||||
#[serde(default)]
|
||||
pub material_id: Option<String>,
|
||||
pub material_slot_name: String,
|
||||
pub material_label: Option<String>,
|
||||
pub local_transform: Transform,
|
||||
pub source_node: Option<String>,
|
||||
pub source_mesh: Option<String>,
|
||||
pub source_material: Option<String>,
|
||||
}
|
||||
|
||||
pub fn static_mesh_manifest_path(asset_id: &str) -> String {
|
||||
format!("{STATIC_MESH_ARTIFACT_DIR}/{asset_id}.static_mesh.ron")
|
||||
}
|
||||
|
||||
pub fn part_id_from_label(label: &str) -> String {
|
||||
format!("mesh:{}", stable_sub_asset_slug(label))
|
||||
}
|
||||
|
||||
pub fn material_id_from_label(label: &str) -> String {
|
||||
format!("material:{}", stable_sub_asset_slug(label))
|
||||
}
|
||||
|
||||
fn stable_sub_asset_slug(label: &str) -> String {
|
||||
let mut slug = String::new();
|
||||
for ch in label.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
slug.push(ch.to_ascii_lowercase());
|
||||
} else if !slug.ends_with('_') {
|
||||
slug.push('_');
|
||||
}
|
||||
}
|
||||
slug.trim_matches('_').to_string()
|
||||
}
|
||||
|
||||
pub fn refresh_static_mesh_artifact(
|
||||
record: &mut AssetRecord,
|
||||
) -> Result<StaticMeshManifest, String> {
|
||||
let mut manifest = build_static_mesh_manifest(record)?;
|
||||
let path = static_mesh_manifest_path(&record.id.as_string());
|
||||
record.import_settings.static_mesh_manifest_path = Some(path.clone());
|
||||
manifest.source.dependencies.sort();
|
||||
manifest.source.dependencies.dedup();
|
||||
record.dependencies = manifest.source.dependencies.clone();
|
||||
|
||||
let text = ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default())
|
||||
.map_err(|err| format!("could not serialize static mesh manifest: {err}"))?;
|
||||
if let Some(parent) = Path::new(&path).parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|err| format!("could not create {}: {err}", parent.display()))?;
|
||||
}
|
||||
let should_write = fs::read_to_string(&path).ok().as_deref() != Some(text.as_str());
|
||||
if should_write {
|
||||
fs::write(&path, text)
|
||||
.map_err(|err| format!("could not write static mesh manifest {path}: {err}"))?;
|
||||
info!(
|
||||
"Static mesh manifest refreshed: source={} artifact={} parts={}",
|
||||
record.path,
|
||||
path,
|
||||
manifest.parts.len()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
pub fn load_static_mesh_manifest(path: &str) -> Result<StaticMeshManifest, String> {
|
||||
let text = fs::read_to_string(path).map_err(|err| format!("could not read {path}: {err}"))?;
|
||||
ron::from_str(&text).map_err(|err| format!("could not parse {path}: {err}"))
|
||||
}
|
||||
|
||||
pub fn renderer_from_manifest(
|
||||
manifest: &StaticMeshManifest,
|
||||
settings: &ImportSettings,
|
||||
) -> StaticMeshRenderer {
|
||||
let use_source_materials = matches!(
|
||||
settings.material_policy,
|
||||
MaterialImportPolicy::SourceMaterials
|
||||
);
|
||||
|
||||
StaticMeshRenderer {
|
||||
slots: manifest
|
||||
.parts
|
||||
.iter()
|
||||
.map(|part| StaticMeshRendererEntry {
|
||||
id: ComponentInstanceId::new(part_effective_id(part)),
|
||||
name: part.name.clone(),
|
||||
mesh: EditorAssetRef::new(
|
||||
manifest.asset_id.clone(),
|
||||
part_effective_id(part),
|
||||
part.name.clone(),
|
||||
),
|
||||
material: use_source_materials
|
||||
.then(|| {
|
||||
part_effective_material_id(part).map(|id| {
|
||||
EditorAssetRef::new(
|
||||
manifest.asset_id.clone(),
|
||||
id,
|
||||
part.material_slot_name.clone(),
|
||||
)
|
||||
})
|
||||
})
|
||||
.flatten(),
|
||||
local_transform: part.local_transform,
|
||||
visible: true,
|
||||
cast_shadows: true,
|
||||
receive_shadows: true,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn part_effective_id(part: &StaticMeshPart) -> String {
|
||||
if part.id.trim().is_empty() {
|
||||
part_id_from_label(&part.mesh_label)
|
||||
} else {
|
||||
part.id.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn part_effective_material_id(part: &StaticMeshPart) -> Option<String> {
|
||||
part.material_id.clone().or_else(|| {
|
||||
part.material_label
|
||||
.as_ref()
|
||||
.map(|label| material_id_from_label(label))
|
||||
})
|
||||
}
|
||||
|
||||
fn build_static_mesh_manifest(record: &AssetRecord) -> Result<StaticMeshManifest, String> {
|
||||
let format = source_format(&record.path)?;
|
||||
let fingerprint = source_fingerprint(&record.path)?;
|
||||
let import = StaticMeshImportSnapshot {
|
||||
scale: record.import_settings.scale,
|
||||
generate_collider: record.import_settings.generate_collider,
|
||||
lod0_only: record.import_settings.lod0_only,
|
||||
placement_mode: record.import_settings.placement_mode.clone(),
|
||||
hierarchy_mode: record.import_settings.hierarchy_mode.clone(),
|
||||
material_policy: record.import_settings.material_policy.clone(),
|
||||
};
|
||||
|
||||
let mut manifest = match format.as_str() {
|
||||
"gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, import)?,
|
||||
"fbx" => build_fbx_manifest(record, format, fingerprint, import)?,
|
||||
_ => return Err(format!("unsupported static mesh source format `{format}`")),
|
||||
};
|
||||
|
||||
if manifest.parts.is_empty() {
|
||||
manifest
|
||||
.warnings
|
||||
.push("No renderable static mesh parts were found.".into());
|
||||
}
|
||||
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
fn build_gltf_manifest(
|
||||
record: &AssetRecord,
|
||||
format: String,
|
||||
fingerprint: StaticMeshSourceFingerprint,
|
||||
import: StaticMeshImportSnapshot,
|
||||
) -> Result<StaticMeshManifest, String> {
|
||||
let gltf = gltf::Gltf::open(&record.path)
|
||||
.map_err(|err| format!("could not parse glTF {}: {err}", record.path))?;
|
||||
let mut parts = Vec::new();
|
||||
let mut dependencies = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
for buffer in gltf.document.buffers() {
|
||||
if let gltf::buffer::Source::Uri(uri) = buffer.source() {
|
||||
dependencies.push(resolve_dependency(&record.path, uri));
|
||||
}
|
||||
}
|
||||
for image in gltf.document.images() {
|
||||
if let gltf::image::Source::Uri { uri, .. } = image.source() {
|
||||
dependencies.push(resolve_dependency(&record.path, uri));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(scene) = gltf
|
||||
.document
|
||||
.default_scene()
|
||||
.or_else(|| gltf.document.scenes().next())
|
||||
{
|
||||
for node in scene.nodes() {
|
||||
collect_gltf_node_parts(node, Mat4::IDENTITY, &mut parts);
|
||||
}
|
||||
} else {
|
||||
for mesh in gltf.document.meshes() {
|
||||
collect_gltf_mesh_parts(None, None, mesh, Mat4::IDENTITY, &mut parts);
|
||||
}
|
||||
}
|
||||
|
||||
if gltf.document.animations().count() > 0 {
|
||||
warnings.push(
|
||||
"Animations are recorded as metadata; use Scene Instance placement for playback."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
if gltf.document.skins().count() > 0 {
|
||||
warnings.push(
|
||||
"Skins are recorded as metadata; skinned playback stays on the Scene Instance path."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
parts.sort_by(|a, b| a.mesh_label.cmp(&b.mesh_label).then(a.name.cmp(&b.name)));
|
||||
|
||||
Ok(StaticMeshManifest {
|
||||
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
|
||||
asset_id: record.id.as_string(),
|
||||
label: record.label.clone(),
|
||||
source: StaticMeshSource {
|
||||
path: record.path.clone(),
|
||||
format,
|
||||
fingerprint,
|
||||
dependencies,
|
||||
},
|
||||
import,
|
||||
metadata: StaticMeshMetadata {
|
||||
mesh_count: gltf.document.meshes().count(),
|
||||
material_count: gltf.document.materials().count(),
|
||||
node_count: gltf.document.nodes().count(),
|
||||
animation_count: gltf.document.animations().count(),
|
||||
skin_count: gltf.document.skins().count(),
|
||||
light_count: 0,
|
||||
camera_count: gltf.document.cameras().count(),
|
||||
},
|
||||
parts,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_gltf_node_parts(
|
||||
node: gltf::Node<'_>,
|
||||
parent_transform: Mat4,
|
||||
parts: &mut Vec<StaticMeshPart>,
|
||||
) {
|
||||
let local = Mat4::from_cols_array_2d(&node.transform().matrix());
|
||||
let world_transform = parent_transform * local;
|
||||
if let Some(mesh) = node.mesh() {
|
||||
collect_gltf_mesh_parts(
|
||||
node.name().map(str::to_string),
|
||||
Some(node.index()),
|
||||
mesh,
|
||||
world_transform,
|
||||
parts,
|
||||
);
|
||||
}
|
||||
for child in node.children() {
|
||||
collect_gltf_node_parts(child, world_transform, parts);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_gltf_mesh_parts(
|
||||
node_name: Option<String>,
|
||||
node_index: Option<usize>,
|
||||
mesh: gltf::Mesh<'_>,
|
||||
transform: Mat4,
|
||||
parts: &mut Vec<StaticMeshPart>,
|
||||
) {
|
||||
let mesh_index = mesh.index();
|
||||
let mesh_name = mesh.name().map(str::to_string);
|
||||
for primitive in mesh.primitives() {
|
||||
let primitive_index = primitive.index();
|
||||
let mesh_label = GltfAssetLabel::Primitive {
|
||||
mesh: mesh_index,
|
||||
primitive: primitive_index,
|
||||
}
|
||||
.to_string();
|
||||
let material = primitive.material();
|
||||
let material_label = material
|
||||
.index()
|
||||
.map(|index| {
|
||||
GltfAssetLabel::Material {
|
||||
index,
|
||||
is_scale_inverted: false,
|
||||
}
|
||||
.to_string()
|
||||
})
|
||||
.or_else(|| Some(GltfAssetLabel::DefaultMaterial.to_string()));
|
||||
let material_name = material
|
||||
.name()
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| "Default Material".into());
|
||||
let name = node_name
|
||||
.clone()
|
||||
.or_else(|| mesh_name.clone())
|
||||
.unwrap_or_else(|| format!("Mesh {mesh_index}"));
|
||||
let source_node = node_index.map(|index| format!("Node{index}"));
|
||||
parts.push(StaticMeshPart {
|
||||
id: part_id_from_label(&mesh_label),
|
||||
name: format!("{name} / Primitive {primitive_index}"),
|
||||
material_id: material_label
|
||||
.as_ref()
|
||||
.map(|label| material_id_from_label(label)),
|
||||
mesh_label,
|
||||
material_slot_name: material_name.clone(),
|
||||
material_label,
|
||||
local_transform: Transform::from_matrix(transform),
|
||||
source_node,
|
||||
source_mesh: Some(format!("Mesh{mesh_index}")),
|
||||
source_material: Some(material_name),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn build_fbx_manifest(
|
||||
record: &AssetRecord,
|
||||
format: String,
|
||||
fingerprint: StaticMeshSourceFingerprint,
|
||||
import: StaticMeshImportSnapshot,
|
||||
) -> Result<StaticMeshManifest, String> {
|
||||
let bytes =
|
||||
fs::read(&record.path).map_err(|err| format!("could not read {}: {err}", record.path))?;
|
||||
let scene = ufbx::load_memory(
|
||||
&bytes,
|
||||
ufbx::LoadOpts {
|
||||
target_unit_meters: 1.0,
|
||||
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.map_err(|err| format!("could not parse FBX {}: {err:?}", record.path))?;
|
||||
|
||||
let mut parts = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
for (node_index, node) in scene.nodes.as_ref().iter().enumerate() {
|
||||
let Some(mesh_ref) = node.mesh.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let mesh = mesh_ref.as_ref();
|
||||
if mesh.num_vertices == 0 || mesh.faces.as_ref().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut groups: Vec<(usize, Vec<u32>)> =
|
||||
group_faces_by_material(mesh).into_iter().collect();
|
||||
groups.sort_by_key(|(material_index, _)| *material_index);
|
||||
for (material_index, indices) in groups {
|
||||
if indices.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let material = mesh.materials.get(material_index).map(|mat| mat.as_ref());
|
||||
let material_label = material
|
||||
.and_then(|mat| fbx_material_label(&scene, mat.element.element_id))
|
||||
.or_else(|| Some(FbxAssetLabel::DefaultMaterial.to_string()));
|
||||
let material_name = material
|
||||
.map(|mat| mat.element.name.to_string())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Default Material".into());
|
||||
let node_name = if node.element.name.is_empty() {
|
||||
format!("Node {node_index}")
|
||||
} else {
|
||||
node.element.name.to_string()
|
||||
};
|
||||
let mesh_label = FbxAssetLabel::Mesh(node_index * 1000 + material_index).to_string();
|
||||
parts.push(StaticMeshPart {
|
||||
id: part_id_from_label(&mesh_label),
|
||||
name: format!("{node_name} / Material {material_index}"),
|
||||
material_id: material_label
|
||||
.as_ref()
|
||||
.map(|label| material_id_from_label(label)),
|
||||
mesh_label,
|
||||
material_slot_name: material_name.clone(),
|
||||
material_label,
|
||||
local_transform: Transform::from_matrix(convert_matrix(&node.geometry_to_world)),
|
||||
source_node: Some(format!("Node{node_index}")),
|
||||
source_mesh: Some(format!("Mesh{node_index}")),
|
||||
source_material: Some(material_name),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if !scene.anim_stacks.as_ref().is_empty() {
|
||||
warnings.push(
|
||||
"Animations are recorded as metadata; use Scene Instance placement for playback."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
if !scene.skin_deformers.as_ref().is_empty() {
|
||||
warnings.push(
|
||||
"Skins are recorded as metadata; skinned playback stays on the Scene Instance path."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
parts.sort_by(|a, b| a.mesh_label.cmp(&b.mesh_label).then(a.name.cmp(&b.name)));
|
||||
|
||||
Ok(StaticMeshManifest {
|
||||
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
|
||||
asset_id: record.id.as_string(),
|
||||
label: record.label.clone(),
|
||||
source: StaticMeshSource {
|
||||
path: record.path.clone(),
|
||||
format,
|
||||
fingerprint,
|
||||
dependencies: fbx_dependencies(&record.path),
|
||||
},
|
||||
import,
|
||||
metadata: StaticMeshMetadata {
|
||||
mesh_count: scene.meshes.as_ref().len(),
|
||||
material_count: scene.materials.as_ref().len(),
|
||||
node_count: scene.nodes.as_ref().len(),
|
||||
animation_count: scene.anim_stacks.as_ref().len(),
|
||||
skin_count: scene.skin_deformers.as_ref().len(),
|
||||
light_count: scene.lights.as_ref().len(),
|
||||
camera_count: scene.cameras.as_ref().len(),
|
||||
},
|
||||
parts,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
fn fbx_material_label(scene: &ufbx::Scene, element_id: u32) -> Option<String> {
|
||||
if element_id == 0 {
|
||||
return None;
|
||||
}
|
||||
scene
|
||||
.materials
|
||||
.as_ref()
|
||||
.iter()
|
||||
.position(|material| material.element.element_id == element_id)
|
||||
.map(|index| FbxAssetLabel::Material(index).to_string())
|
||||
}
|
||||
|
||||
fn fbx_dependencies(source_path: &str) -> Vec<String> {
|
||||
let path = Path::new(source_path);
|
||||
let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(parent) = path.parent() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let sidecar = parent.join(format!("{stem}.fbm"));
|
||||
if !sidecar.is_dir() {
|
||||
return Vec::new();
|
||||
}
|
||||
walkdir::WalkDir::new(sidecar)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| entry.file_type().is_file())
|
||||
.map(|entry| entry.path().to_string_lossy().replace('\\', "/"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn source_format(path: &str) -> Result<String, String> {
|
||||
Path::new(path)
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.map(|ext| ext.to_ascii_lowercase())
|
||||
.ok_or_else(|| format!("asset path `{path}` has no extension"))
|
||||
}
|
||||
|
||||
fn source_fingerprint(path: &str) -> Result<StaticMeshSourceFingerprint, String> {
|
||||
let metadata = fs::metadata(path).map_err(|err| format!("could not stat {path}: {err}"))?;
|
||||
let modified_unix_secs = metadata
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|duration| duration.as_secs())
|
||||
.unwrap_or_default();
|
||||
Ok(StaticMeshSourceFingerprint {
|
||||
byte_len: metadata.len(),
|
||||
modified_unix_secs,
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_dependency(source_path: &str, uri: &str) -> String {
|
||||
if uri.starts_with("data:") || uri.contains("://") {
|
||||
return uri.to_string();
|
||||
}
|
||||
Path::new(source_path)
|
||||
.parent()
|
||||
.unwrap_or_else(|| Path::new(""))
|
||||
.join(uri)
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_manifest() -> StaticMeshManifest {
|
||||
StaticMeshManifest {
|
||||
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
|
||||
asset_id: "asset-1".into(),
|
||||
label: "Crate".into(),
|
||||
source: StaticMeshSource {
|
||||
path: "assets/models/crate.glb".into(),
|
||||
format: "glb".into(),
|
||||
fingerprint: StaticMeshSourceFingerprint {
|
||||
byte_len: 42,
|
||||
modified_unix_secs: 10,
|
||||
},
|
||||
dependencies: Vec::new(),
|
||||
},
|
||||
import: StaticMeshImportSnapshot {
|
||||
scale: 1.0,
|
||||
generate_collider: true,
|
||||
lod0_only: true,
|
||||
placement_mode: ModelPlacementMode::StaticAsset,
|
||||
hierarchy_mode: ModelHierarchyMode::SingleActor,
|
||||
material_policy: MaterialImportPolicy::SourceMaterials,
|
||||
},
|
||||
metadata: StaticMeshMetadata {
|
||||
mesh_count: 1,
|
||||
material_count: 1,
|
||||
node_count: 1,
|
||||
animation_count: 0,
|
||||
skin_count: 0,
|
||||
light_count: 0,
|
||||
camera_count: 0,
|
||||
},
|
||||
parts: vec![StaticMeshPart {
|
||||
id: "mesh:mesh0_primitive0".into(),
|
||||
name: "Crate / Primitive 0".into(),
|
||||
mesh_label: "Mesh0/Primitive0".into(),
|
||||
material_id: Some("material:material0".into()),
|
||||
material_slot_name: "Wood".into(),
|
||||
material_label: Some("Material0".into()),
|
||||
local_transform: Transform::from_xyz(1.0, 2.0, 3.0),
|
||||
source_node: Some("Node0".into()),
|
||||
source_mesh: Some("Mesh0".into()),
|
||||
source_material: Some("Wood".into()),
|
||||
}],
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_mesh_manifest_path_uses_asset_id() {
|
||||
assert_eq!(
|
||||
static_mesh_manifest_path("abc"),
|
||||
"assets/meshes/generated/abc.static_mesh.ron"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renderer_from_manifest_preserves_labels_and_collider_policy() {
|
||||
let manifest = test_manifest();
|
||||
let settings = ImportSettings {
|
||||
generate_collider: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let renderer = renderer_from_manifest(&manifest, &settings);
|
||||
|
||||
assert_eq!(renderer.slots.len(), 1);
|
||||
let entry = &renderer.slots[0];
|
||||
assert_eq!(entry.mesh.asset_id, manifest.asset_id);
|
||||
assert_eq!(entry.mesh.sub_asset_id, "mesh:mesh0_primitive0");
|
||||
assert_eq!(
|
||||
entry
|
||||
.material
|
||||
.as_ref()
|
||||
.map(|material| material.sub_asset_id.as_str()),
|
||||
Some("material:material0")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renderer_from_manifest_can_ignore_source_materials() {
|
||||
let manifest = test_manifest();
|
||||
let settings = ImportSettings {
|
||||
material_policy: MaterialImportPolicy::AuthoringOverride,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let renderer = renderer_from_manifest(&manifest, &settings);
|
||||
|
||||
assert!(renderer.slots[0].material.is_none());
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! In-process editor binary entry point.
|
||||
|
||||
fn main() {
|
||||
if std::env::var_os("WGPU_VALIDATION").is_none() {
|
||||
// SAFETY: called before any threads or GPU init.
|
||||
unsafe { std::env::set_var("WGPU_VALIDATION", "0") };
|
||||
}
|
||||
|
||||
let mut app = bevy::prelude::App::new();
|
||||
editor::configure_editor_app(&mut app);
|
||||
editor::register_game_editor_plugins(&mut app);
|
||||
app.run();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use bevy::prelude::*;
|
||||
use bevy::remote::{http::RemoteHttpPlugin, RemotePlugin};
|
||||
|
||||
/// Bevy Remote Protocol support for future external editor, automation, and AI
|
||||
/// tooling. This is editor-only so the shipped game does not expose a port.
|
||||
pub struct BrpPlugin;
|
||||
|
||||
impl Plugin for BrpPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_plugins(RemotePlugin::default())
|
||||
.add_plugins(RemoteHttpPlugin::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Deferred editor command execution (palette, BRP bridge).
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct PendingEditorCommands {
|
||||
pub queue: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn queue_editor_command(world: &mut World, name: String) {
|
||||
world
|
||||
.resource_mut::<PendingEditorCommands>()
|
||||
.queue
|
||||
.push(name);
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! Editor extensibility: command registry, inspector sections, and extension hooks.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::{egui, EguiContexts, EguiPrimaryContextPass};
|
||||
|
||||
use crate::history::group_selection_with_history;
|
||||
use crate::state::{EditorMode, PlayPossession};
|
||||
use crate::ui::helpers::{
|
||||
reset_scene_lighting_to_project_defaults, toggle_play_mode, toggle_play_paused,
|
||||
};
|
||||
use crate::ui::selection_ops::focus_editor_camera_on_selection;
|
||||
use crate::ui::theme::{apply_editor_theme, PANEL_BG, TEXT, TEXT_DIM};
|
||||
use crate::ui::UiState;
|
||||
|
||||
/// Named editor command invokable from the palette and BRP.
|
||||
pub trait EditorCommand: Send + Sync {
|
||||
fn name(&self) -> &str;
|
||||
fn execute(&self, world: &mut World);
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct EditorCommandRegistry {
|
||||
commands: Vec<Box<dyn EditorCommand>>,
|
||||
}
|
||||
|
||||
impl EditorCommandRegistry {
|
||||
pub fn register(&mut self, command: Box<dyn EditorCommand>) {
|
||||
self.commands.push(command);
|
||||
}
|
||||
|
||||
pub fn names(&self) -> Vec<String> {
|
||||
self.commands
|
||||
.iter()
|
||||
.map(|cmd| cmd.name().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn run(&self, world: &mut World, name: &str) -> bool {
|
||||
if let Some(command) = self.commands.iter().find(|cmd| cmd.name() == name) {
|
||||
command.execute(world);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom inspector body for level objects (game crates register via [`register_actor_inspector_section`]).
|
||||
pub trait ActorInspectorSection: Send + Sync {
|
||||
fn id(&self) -> &str;
|
||||
fn title(&self) -> &str;
|
||||
fn order(&self) -> i32;
|
||||
fn applies_to(&self, world: &World, entity: Entity) -> bool;
|
||||
fn ui(&self, world: &mut World, ui: &mut egui::Ui, entity: Entity);
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct ActorInspectorSectionRegistry {
|
||||
sections: Vec<Box<dyn ActorInspectorSection>>,
|
||||
}
|
||||
|
||||
impl ActorInspectorSectionRegistry {
|
||||
pub fn register(&mut self, section: Box<dyn ActorInspectorSection>) {
|
||||
self.sections.push(section);
|
||||
}
|
||||
|
||||
pub fn sections_for(&self, world: &World, entity: Entity) -> Vec<&dyn ActorInspectorSection> {
|
||||
let mut matched: Vec<_> = self
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|section| section.applies_to(world, entity))
|
||||
.map(|section| section.as_ref())
|
||||
.collect();
|
||||
matched.sort_by_key(|section| section.order());
|
||||
matched
|
||||
}
|
||||
|
||||
pub fn draw_sections(&self, world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let mut matched: Vec<_> = self
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|section| section.applies_to(world, entity))
|
||||
.collect();
|
||||
matched.sort_by_key(|section| section.order());
|
||||
for section in matched {
|
||||
section.ui(world, ui, entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_actor_inspector_section(app: &mut App, section: Box<dyn ActorInspectorSection>) {
|
||||
if !app
|
||||
.world()
|
||||
.contains_resource::<ActorInspectorSectionRegistry>()
|
||||
{
|
||||
app.init_resource::<ActorInspectorSectionRegistry>();
|
||||
}
|
||||
app.world_mut()
|
||||
.resource_mut::<ActorInspectorSectionRegistry>()
|
||||
.register(section);
|
||||
}
|
||||
|
||||
/// Optional extension point for registering editor panels and menu hooks.
|
||||
pub trait EditorExtension: Send + Sync {
|
||||
fn name(&self) -> &str;
|
||||
fn register(&self, _app: &mut App) {}
|
||||
}
|
||||
|
||||
/// Formal editor plugin surface for game-specific panels (H5).
|
||||
pub trait EditorPlugin: Send + Sync {
|
||||
fn name(&self) -> &str;
|
||||
fn register(&self, app: &mut App);
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct EditorExtensions {
|
||||
pub extensions: Vec<Box<dyn EditorExtension>>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct RegisteredEditorPlugins {
|
||||
pub plugins: Vec<Box<dyn EditorPlugin>>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct CommandPalette {
|
||||
pub open: bool,
|
||||
pub filter: String,
|
||||
pub pending_run: Option<String>,
|
||||
}
|
||||
|
||||
pub struct ExtensibilityPlugin;
|
||||
|
||||
impl Plugin for ExtensibilityPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<EditorCommandRegistry>()
|
||||
.init_resource::<ActorInspectorSectionRegistry>()
|
||||
.init_resource::<EditorExtensions>()
|
||||
.init_resource::<RegisteredEditorPlugins>()
|
||||
.init_resource::<CommandPalette>()
|
||||
.init_resource::<crate::command_queue::PendingEditorCommands>()
|
||||
.add_systems(Startup, register_builtin_commands)
|
||||
.add_systems(Update, run_palette_commands)
|
||||
.add_systems(EguiPrimaryContextPass, command_palette_ui);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_editor_plugin(app: &mut App, plugin: Box<dyn EditorPlugin>) {
|
||||
plugin.register(app);
|
||||
app.world_mut()
|
||||
.resource_mut::<RegisteredEditorPlugins>()
|
||||
.plugins
|
||||
.push(plugin);
|
||||
}
|
||||
|
||||
fn register_builtin_commands(mut registry: ResMut<EditorCommandRegistry>) {
|
||||
registry.register(Box::new(TogglePlayCommand));
|
||||
registry.register(Box::new(TogglePlayPausedCommand));
|
||||
registry.register(Box::new(TogglePossessionCommand));
|
||||
registry.register(Box::new(ResetLightingCommand));
|
||||
registry.register(Box::new(GroupSelectionCommand));
|
||||
registry.register(Box::new(FocusSelectionCommand));
|
||||
registry.register(Box::new(CreatePostProcessVolumeCommand));
|
||||
registry.register(Box::new(FocusActiveVolumesCommand));
|
||||
registry.register(Box::new(SelectVolumesAtCameraCommand));
|
||||
}
|
||||
|
||||
fn run_palette_commands(world: &mut World) {
|
||||
let pending = world.resource_mut::<CommandPalette>().pending_run.take();
|
||||
if let Some(name) = pending {
|
||||
dispatch_editor_command(world, &name);
|
||||
}
|
||||
let names = std::mem::take(
|
||||
&mut world
|
||||
.resource_mut::<crate::command_queue::PendingEditorCommands>()
|
||||
.queue,
|
||||
);
|
||||
for name in names {
|
||||
dispatch_editor_command(world, &name);
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_editor_command(world: &mut World, name: &str) {
|
||||
let ran = world
|
||||
.resource_scope(|world, registry: Mut<EditorCommandRegistry>| registry.run(world, name));
|
||||
if !ran {
|
||||
warn!("unknown editor command: {name}");
|
||||
}
|
||||
}
|
||||
|
||||
struct TogglePlayCommand;
|
||||
|
||||
impl EditorCommand for TogglePlayCommand {
|
||||
fn name(&self) -> &str {
|
||||
"play.toggle"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
toggle_play_mode(world);
|
||||
}
|
||||
}
|
||||
|
||||
struct TogglePlayPausedCommand;
|
||||
|
||||
impl EditorCommand for TogglePlayPausedCommand {
|
||||
fn name(&self) -> &str {
|
||||
"play.toggle_pause"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
toggle_play_paused(world);
|
||||
}
|
||||
}
|
||||
|
||||
struct TogglePossessionCommand;
|
||||
|
||||
impl EditorCommand for TogglePossessionCommand {
|
||||
fn name(&self) -> &str {
|
||||
"play.toggle_possession"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
if *world.resource::<State<EditorMode>>().get() != EditorMode::Playing {
|
||||
return;
|
||||
}
|
||||
let next = match *world.resource::<PlayPossession>() {
|
||||
PlayPossession::Possessed => PlayPossession::Ejected,
|
||||
PlayPossession::Ejected => PlayPossession::Possessed,
|
||||
};
|
||||
*world.resource_mut::<PlayPossession>() = next;
|
||||
}
|
||||
}
|
||||
|
||||
struct ResetLightingCommand;
|
||||
|
||||
impl EditorCommand for ResetLightingCommand {
|
||||
fn name(&self) -> &str {
|
||||
"scene.reset_lighting"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
reset_scene_lighting_to_project_defaults(world);
|
||||
}
|
||||
}
|
||||
|
||||
struct GroupSelectionCommand;
|
||||
|
||||
impl EditorCommand for GroupSelectionCommand {
|
||||
fn name(&self) -> &str {
|
||||
"selection.group"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
let selected: Vec<Entity> = world
|
||||
.resource::<UiState>()
|
||||
.selected_entities
|
||||
.iter()
|
||||
.collect();
|
||||
group_selection_with_history(world, &selected);
|
||||
}
|
||||
}
|
||||
|
||||
struct FocusSelectionCommand;
|
||||
|
||||
impl EditorCommand for FocusSelectionCommand {
|
||||
fn name(&self) -> &str {
|
||||
"selection.focus"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
focus_editor_camera_on_selection(world);
|
||||
}
|
||||
}
|
||||
|
||||
struct CreatePostProcessVolumeCommand;
|
||||
|
||||
impl EditorCommand for CreatePostProcessVolumeCommand {
|
||||
fn name(&self) -> &str {
|
||||
"rendering.create_volume"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
crate::rendering_diagnostics::spawn_post_process_volume_at_camera(world);
|
||||
}
|
||||
}
|
||||
|
||||
struct FocusActiveVolumesCommand;
|
||||
|
||||
impl EditorCommand for FocusActiveVolumesCommand {
|
||||
fn name(&self) -> &str {
|
||||
"rendering.focus_active_volumes"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
crate::rendering_diagnostics::select_volumes_at_camera(world);
|
||||
focus_editor_camera_on_selection(world);
|
||||
}
|
||||
}
|
||||
|
||||
struct SelectVolumesAtCameraCommand;
|
||||
|
||||
impl EditorCommand for SelectVolumesAtCameraCommand {
|
||||
fn name(&self) -> &str {
|
||||
"rendering.select_volumes_at_camera"
|
||||
}
|
||||
|
||||
fn execute(&self, world: &mut World) {
|
||||
crate::rendering_diagnostics::select_volumes_at_camera(world);
|
||||
}
|
||||
}
|
||||
|
||||
fn command_palette_ui(
|
||||
mut contexts: EguiContexts,
|
||||
mut palette: ResMut<CommandPalette>,
|
||||
registry: Res<EditorCommandRegistry>,
|
||||
) -> Result {
|
||||
let Ok(ctx) = contexts.ctx_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
apply_editor_theme(ctx);
|
||||
|
||||
if ctx.input(|input| input.modifiers.command && input.key_pressed(egui::Key::P)) {
|
||||
palette.open = true;
|
||||
}
|
||||
|
||||
if !palette.open {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut open = palette.open;
|
||||
egui::Window::new("Command Palette")
|
||||
.open(&mut open)
|
||||
.default_width(400.0)
|
||||
.frame(egui::Frame::window(&ctx.style()).fill(PANEL_BG))
|
||||
.show(ctx, |ui| {
|
||||
ui.label(
|
||||
egui::RichText::new("Ctrl+P — filter and run commands")
|
||||
.color(TEXT_DIM)
|
||||
.small(),
|
||||
);
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut palette.filter)
|
||||
.hint_text("Type to filter...")
|
||||
.desired_width(f32::INFINITY),
|
||||
);
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical()
|
||||
.max_height(280.0)
|
||||
.show(ui, |ui| {
|
||||
for name in registry.names() {
|
||||
if !palette.filter.is_empty()
|
||||
&& !name.to_lowercase().contains(&palette.filter.to_lowercase())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let response =
|
||||
ui.selectable_label(false, egui::RichText::new(&name).color(TEXT));
|
||||
if response.clicked() {
|
||||
palette.pending_run = Some(name);
|
||||
palette.open = false;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
palette.open = open;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Game-specific [`ActorInspectorSection`] implementations (ADR 0007 dogfood).
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use shared::{LevelObject, WeaponSpawn};
|
||||
|
||||
use super::extensibility::{register_actor_inspector_section, ActorInspectorSection};
|
||||
|
||||
/// Registers inspector sections declared in [`game::editor_ext::actor_inspector_section_ids`].
|
||||
pub fn register_game_inspector_sections(app: &mut App) {
|
||||
for id in game::editor_ext::actor_inspector_section_ids() {
|
||||
match *id {
|
||||
"game.fps_weapon_stats" => {
|
||||
register_actor_inspector_section(app, Box::new(FpsWeaponStatsSection));
|
||||
}
|
||||
other => {
|
||||
warn!("unknown game actor inspector section id: {other}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FpsWeaponStatsSection;
|
||||
|
||||
impl ActorInspectorSection for FpsWeaponStatsSection {
|
||||
fn id(&self) -> &str {
|
||||
"game.fps_weapon_stats"
|
||||
}
|
||||
|
||||
fn title(&self) -> &str {
|
||||
"Weapon Stats (Demo)"
|
||||
}
|
||||
|
||||
fn order(&self) -> i32 {
|
||||
200
|
||||
}
|
||||
|
||||
fn applies_to(&self, world: &World, entity: Entity) -> bool {
|
||||
world
|
||||
.get_entity(entity)
|
||||
.is_ok_and(|e| e.contains::<LevelObject>() && e.contains::<WeaponSpawn>())
|
||||
}
|
||||
|
||||
fn ui(&self, _world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
ui.collapsing(self.title(), |ui| {
|
||||
ui.label(format!("Entity {entity:?}"));
|
||||
ui.small("Registered from `game::editor_ext` — extend with gameplay fields.");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Renders game-registered editor panel state (ADR 0007 dogfood UI).
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::{egui, EguiContexts, EguiPrimaryContextPass};
|
||||
|
||||
use game::editor_ext::FpsDemoPanelState;
|
||||
|
||||
pub struct GameEditorPanelsPlugin;
|
||||
|
||||
impl Plugin for GameEditorPanelsPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(EguiPrimaryContextPass, fps_demo_panel_ui);
|
||||
}
|
||||
}
|
||||
|
||||
fn fps_demo_panel_ui(mut contexts: EguiContexts, mut panel: ResMut<FpsDemoPanelState>) -> Result {
|
||||
let Ok(ctx) = contexts.ctx_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if panel.headline.is_empty() {
|
||||
panel.headline = "FPS Foundation Demo".into();
|
||||
}
|
||||
|
||||
if ctx.input(|input| {
|
||||
input.modifiers.command && input.key_pressed(egui::Key::G) && input.modifiers.shift
|
||||
}) {
|
||||
panel.open = !panel.open;
|
||||
}
|
||||
|
||||
if !panel.open {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut open = panel.open;
|
||||
egui::Window::new("FPS Demo (Game EditorPlugin)")
|
||||
.open(&mut open)
|
||||
.default_width(280.0)
|
||||
.show(ctx, |ui| {
|
||||
ui.label("Registered from `game::editor_ext` via ADR 0007.");
|
||||
ui.small("Toggle: Ctrl+Shift+G");
|
||||
ui.separator();
|
||||
ui.heading(&panel.headline);
|
||||
ui.label("Game crate owns panel state; editor renders the dock window.");
|
||||
});
|
||||
panel.open = open;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Dev-only hot reload polling and status for the `game_hot` dylib.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{mpsc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use game::{hot_reload_subscribe, on_hot_reload};
|
||||
use hot_lib_reloader::LibReloadObserver;
|
||||
use notify::Event;
|
||||
|
||||
/// Status label shown in the bottom status bar.
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct HotReloadState {
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
impl Default for HotReloadState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
label: "Hot reload: idle".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HotReloadPlugin;
|
||||
|
||||
impl Plugin for HotReloadPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<HotReloadState>()
|
||||
.add_systems(Startup, spawn_dylib_watcher)
|
||||
.add_systems(Last, poll_lib_reload)
|
||||
.add_systems(Last, manual_hot_reload);
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_dylib_watcher(mut commands: Commands) {
|
||||
let Some(path) = game_hot_dylib_path() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let watch_path = path.clone();
|
||||
std::thread::spawn(move || {
|
||||
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
|
||||
let tx = tx.clone();
|
||||
let mut watcher = RecommendedWatcher::new(
|
||||
move |result: notify::Result<Event>| {
|
||||
if let Ok(event) = result {
|
||||
if matches!(event.kind, EventKind::Modify(_) | EventKind::Create(_)) {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
}
|
||||
},
|
||||
notify::Config::default(),
|
||||
)
|
||||
.expect("hot reload watcher");
|
||||
|
||||
if let Some(parent) = watch_path.parent() {
|
||||
let _ = watcher.watch(parent, RecursiveMode::NonRecursive);
|
||||
}
|
||||
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(3600));
|
||||
}
|
||||
});
|
||||
|
||||
commands.insert_resource(DylibWatchReceiver(Mutex::new(rx)));
|
||||
info!("Watching for game_hot dylib changes at {}", path.display());
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct DylibWatchReceiver(Mutex<mpsc::Receiver<()>>);
|
||||
|
||||
fn poll_lib_reload(world: &mut World, mut observer: Local<Option<LibReloadObserver>>) {
|
||||
if observer.is_none() {
|
||||
*observer = Some(hot_reload_subscribe());
|
||||
}
|
||||
|
||||
let mut building = false;
|
||||
if let Some(watch) = world.get_resource::<DylibWatchReceiver>() {
|
||||
if let Ok(rx) = watch.0.lock() {
|
||||
while rx.try_recv().is_ok() {
|
||||
building = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if building {
|
||||
world.resource_mut::<HotReloadState>().label = "Hot reload: building…".into();
|
||||
}
|
||||
|
||||
let Some(obs) = observer.as_ref() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if obs.wait_for_reload_timeout(Duration::ZERO) {
|
||||
on_hot_reload(world);
|
||||
world.resource_mut::<HotReloadState>().label = "Hot reload: reloaded".into();
|
||||
info!("game_hot dylib reloaded");
|
||||
}
|
||||
}
|
||||
|
||||
fn manual_hot_reload(world: &mut World) {
|
||||
let ctrl = world
|
||||
.resource::<ButtonInput<KeyCode>>()
|
||||
.pressed(KeyCode::ControlLeft)
|
||||
|| world
|
||||
.resource::<ButtonInput<KeyCode>>()
|
||||
.pressed(KeyCode::ControlRight);
|
||||
let shift = world
|
||||
.resource::<ButtonInput<KeyCode>>()
|
||||
.pressed(KeyCode::ShiftLeft)
|
||||
|| world
|
||||
.resource::<ButtonInput<KeyCode>>()
|
||||
.pressed(KeyCode::ShiftRight);
|
||||
let reload = world
|
||||
.resource::<ButtonInput<KeyCode>>()
|
||||
.just_pressed(KeyCode::KeyR);
|
||||
|
||||
if ctrl && shift && reload {
|
||||
on_hot_reload(world);
|
||||
world.resource_mut::<HotReloadState>().label = "Hot reload: manual refresh".into();
|
||||
info!("Manual hot reload refresh (Ctrl+Shift+R)");
|
||||
}
|
||||
}
|
||||
|
||||
fn game_hot_dylib_path() -> Option<PathBuf> {
|
||||
let target = std::env::var("CARGO_TARGET_DIR").map_or_else(
|
||||
|_| PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../../target")),
|
||||
PathBuf::from,
|
||||
);
|
||||
let profile = if cfg!(debug_assertions) {
|
||||
"debug"
|
||||
} else {
|
||||
"release"
|
||||
};
|
||||
Some(target.join(profile).join(game_hot_lib_name()))
|
||||
}
|
||||
|
||||
fn game_hot_lib_name() -> &'static str {
|
||||
if cfg!(target_os = "macos") {
|
||||
"libgame_hot.dylib"
|
||||
} else if cfg!(target_os = "windows") {
|
||||
"game_hot.dll"
|
||||
} else {
|
||||
"libgame_hot.so"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Editor extensibility, BRP, command queue, and optional hot reload.
|
||||
|
||||
pub mod brp;
|
||||
pub mod command_queue;
|
||||
pub mod extensibility;
|
||||
pub mod game_inspector;
|
||||
pub mod game_panels;
|
||||
#[cfg(feature = "hot-reload")]
|
||||
pub mod hot_reload;
|
||||
@@ -0,0 +1,151 @@
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
ActorId, ActorKind, ActorName, ColliderDesc, EditorVisibility, InspectorOrder, LightDesc,
|
||||
MaterialDesc, MaterialOverride, ModelRef, ObjectiveMarker, PhysicsBody, PostProcessVolumeDesc,
|
||||
PrefabInstance, PrefabRef, Primitive, RigidBodyDesc, StaticMeshRenderer, TeamSpawn,
|
||||
TriggerVolume, WeaponSpawn,
|
||||
};
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EditorEntitySnapshot {
|
||||
pub actor_id: Option<ActorId>,
|
||||
pub actor_kind: ActorKind,
|
||||
pub actor_name: Option<ActorName>,
|
||||
pub name: Option<String>,
|
||||
pub transform: Transform,
|
||||
pub primitive: Option<Primitive>,
|
||||
pub static_mesh_renderer: Option<StaticMeshRenderer>,
|
||||
pub material: Option<MaterialDesc>,
|
||||
pub material_override: Option<MaterialOverride>,
|
||||
pub rigid_body: Option<RigidBodyDesc>,
|
||||
pub collider: Option<ColliderDesc>,
|
||||
pub physics: Option<PhysicsBody>,
|
||||
pub light: Option<LightDesc>,
|
||||
pub player_spawn: bool,
|
||||
pub model: Option<ModelRef>,
|
||||
pub prefab: Option<PrefabRef>,
|
||||
pub prefab_instance: Option<PrefabInstance>,
|
||||
pub weapon_spawn: Option<WeaponSpawn>,
|
||||
pub trigger_volume: Option<TriggerVolume>,
|
||||
pub post_process_volume: Option<PostProcessVolumeDesc>,
|
||||
pub team_spawn: Option<TeamSpawn>,
|
||||
pub objective: Option<ObjectiveMarker>,
|
||||
pub hierarchy_sibling_index: i32,
|
||||
pub editor_visibility: EditorVisibility,
|
||||
pub children: Vec<EditorEntitySnapshot>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SiblingChange {
|
||||
pub entity: Entity,
|
||||
pub old_parent: Option<Entity>,
|
||||
pub new_parent: Option<Entity>,
|
||||
pub old_index: i32,
|
||||
pub new_index: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum EditorCommand {
|
||||
Spawn {
|
||||
snapshot: EditorEntitySnapshot,
|
||||
entity: Option<Entity>,
|
||||
},
|
||||
Despawn {
|
||||
snapshot: EditorEntitySnapshot,
|
||||
entity: Option<Entity>,
|
||||
},
|
||||
Duplicate {
|
||||
snapshots: Vec<EditorEntitySnapshot>,
|
||||
entities: Vec<Entity>,
|
||||
},
|
||||
Rename {
|
||||
entity: Entity,
|
||||
old: String,
|
||||
new: String,
|
||||
},
|
||||
SetTransform {
|
||||
entity: Entity,
|
||||
old: Transform,
|
||||
new: Transform,
|
||||
},
|
||||
SetMaterial {
|
||||
entity: Entity,
|
||||
old: Option<MaterialDesc>,
|
||||
new: MaterialDesc,
|
||||
},
|
||||
SetMaterialOverride {
|
||||
entity: Entity,
|
||||
old: Option<MaterialOverride>,
|
||||
new: MaterialOverride,
|
||||
},
|
||||
SetLight {
|
||||
entity: Entity,
|
||||
old: Option<LightDesc>,
|
||||
new: LightDesc,
|
||||
},
|
||||
SetPhysics {
|
||||
entity: Entity,
|
||||
old: Option<PhysicsBody>,
|
||||
new: PhysicsBody,
|
||||
},
|
||||
SetRigidBody {
|
||||
entity: Entity,
|
||||
old: Option<RigidBodyDesc>,
|
||||
new: RigidBodyDesc,
|
||||
},
|
||||
SetCollider {
|
||||
entity: Entity,
|
||||
old: Option<ColliderDesc>,
|
||||
new: ColliderDesc,
|
||||
},
|
||||
SetPrimitive {
|
||||
entity: Entity,
|
||||
old: Option<Primitive>,
|
||||
new: Primitive,
|
||||
},
|
||||
SetStaticMeshRenderer {
|
||||
entity: Entity,
|
||||
old: Option<StaticMeshRenderer>,
|
||||
new: StaticMeshRenderer,
|
||||
},
|
||||
SetPostProcessVolume {
|
||||
entity: Entity,
|
||||
old: Option<PostProcessVolumeDesc>,
|
||||
new: PostProcessVolumeDesc,
|
||||
},
|
||||
SetTransformGroup {
|
||||
entities: Vec<Entity>,
|
||||
olds: Vec<Transform>,
|
||||
news: Vec<Transform>,
|
||||
},
|
||||
Reparent {
|
||||
entity: Entity,
|
||||
old_parent: Option<Entity>,
|
||||
new_parent: Option<Entity>,
|
||||
},
|
||||
SetActorKind {
|
||||
entity: Entity,
|
||||
old: ActorKind,
|
||||
new: ActorKind,
|
||||
},
|
||||
ReorderSibling {
|
||||
changes: Vec<SiblingChange>,
|
||||
},
|
||||
SetEditorVisibility {
|
||||
entity: Entity,
|
||||
old: EditorVisibility,
|
||||
new: EditorVisibility,
|
||||
},
|
||||
SetInspectorOrder {
|
||||
entity: Entity,
|
||||
old: Option<InspectorOrder>,
|
||||
new: InspectorOrder,
|
||||
},
|
||||
AddComponent {
|
||||
entity: Entity,
|
||||
snapshot: EditorEntitySnapshot,
|
||||
},
|
||||
RemoveComponent {
|
||||
entity: Entity,
|
||||
snapshot: EditorEntitySnapshot,
|
||||
},
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
use bevy::picking::Pickable;
|
||||
use bevy::prelude::*;
|
||||
|
||||
/// Marker for editor/runtime helper entities that are never authored content.
|
||||
#[derive(Component, Reflect, Default, Debug, Clone, Copy)]
|
||||
#[reflect(Component, Default, Debug)]
|
||||
pub struct EditorOnly;
|
||||
|
||||
pub struct EditorInfraPlugin;
|
||||
|
||||
impl Plugin for EditorInfraPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.register_type::<EditorOnly>()
|
||||
.add_systems(Update, make_editor_only_non_pickable);
|
||||
}
|
||||
}
|
||||
|
||||
fn make_editor_only_non_pickable(
|
||||
mut commands: Commands,
|
||||
editor_only: Query<Entity, Added<EditorOnly>>,
|
||||
) {
|
||||
for entity in &editor_only {
|
||||
commands.entity(entity).insert(Pickable::IGNORE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! In-process level editor library for the Bevy FPS foundation.
|
||||
#![allow(clippy::type_complexity)]
|
||||
|
||||
pub mod assets;
|
||||
pub mod ext;
|
||||
pub mod history;
|
||||
pub mod infra;
|
||||
pub mod play;
|
||||
pub mod project;
|
||||
pub mod render_target;
|
||||
pub mod scene;
|
||||
pub mod ui;
|
||||
pub mod viewport;
|
||||
|
||||
// Flat re-exports preserve legacy `crate::module` paths.
|
||||
pub use assets::asset_db;
|
||||
pub use ext::brp;
|
||||
pub use ext::command_queue;
|
||||
pub use ext::extensibility;
|
||||
#[cfg(feature = "hot-reload")]
|
||||
pub use ext::hot_reload;
|
||||
pub use play::net_editor;
|
||||
pub use play::state;
|
||||
pub use project::project_io;
|
||||
pub use project::settings_ui;
|
||||
pub use project::workspace;
|
||||
pub use scene::scene_io;
|
||||
pub use scene::scene_schema;
|
||||
pub use scene::scene_view;
|
||||
pub use viewport::actor_icons;
|
||||
pub use viewport::camera;
|
||||
pub use viewport::gizmos;
|
||||
pub use viewport::render_view;
|
||||
pub use viewport::rendering_diagnostics;
|
||||
pub use viewport::selection;
|
||||
pub use viewport::selection_outline;
|
||||
pub use viewport::visualizers;
|
||||
|
||||
use bevy::app::PluginGroupBuilder;
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::EguiPlugin;
|
||||
use game::{
|
||||
launch, GameInputEnabled, GameInputFocused, GamePlugin, GameRenderBootstrap, SimEnabled,
|
||||
};
|
||||
use transform_gizmo_bevy::prelude::TransformGizmoPlugin;
|
||||
|
||||
use actor_icons::ActorIconsPlugin;
|
||||
use asset_db::AssetDbPlugin;
|
||||
use camera::EditorCameraPlugin;
|
||||
use extensibility::ExtensibilityPlugin;
|
||||
use gizmos::EditorGizmoPlugin;
|
||||
use history::EditorHistoryPlugin;
|
||||
use infra::EditorInfraPlugin;
|
||||
use play::PlaySessionPlugin;
|
||||
use project_io::ProjectIoPlugin;
|
||||
use render_view::RenderViewPlugin;
|
||||
use scene_io::SceneIoPlugin;
|
||||
use scene_view::SceneViewPlugin;
|
||||
use selection::EditorSelectionPlugin;
|
||||
use selection_outline::SelectionOutlinePlugin;
|
||||
use settings_ui::SettingsUiPlugin;
|
||||
use state::EditorStatePlugin;
|
||||
use ui::EditorUiPlugin;
|
||||
use viewport::ViewportPlugin;
|
||||
use visualizers::EditorVisualizersPlugin;
|
||||
|
||||
/// Ordered editor plugin bundle. Registration order is part of the startup contract
|
||||
/// (see `docs/editor/architecture.md` and ADR 0008).
|
||||
pub struct EditorPluginGroup;
|
||||
|
||||
impl PluginGroup for EditorPluginGroup {
|
||||
fn build(self) -> PluginGroupBuilder {
|
||||
let group = PluginGroupBuilder::start::<Self>()
|
||||
.add(EditorInfraPlugin)
|
||||
.add(ProjectIoPlugin)
|
||||
.add(workspace::WorkspacePlugin)
|
||||
.add(scene_schema::SceneSchemaPlugin)
|
||||
.add(net_editor::NetEditorPlugin)
|
||||
.add(AssetDbPlugin)
|
||||
.add(ExtensibilityPlugin)
|
||||
.add(SettingsUiPlugin)
|
||||
.add(assets::EditorAssetsPlugin)
|
||||
.add(assets::ThumbnailsPlugin)
|
||||
.add(EditorStatePlugin)
|
||||
.add(RenderViewPlugin)
|
||||
.add(SceneViewPlugin)
|
||||
.add(PlaySessionPlugin)
|
||||
.add(ViewportPlugin)
|
||||
.add(EditorCameraPlugin)
|
||||
.add(ActorIconsPlugin)
|
||||
.add(EditorSelectionPlugin)
|
||||
.add(SelectionOutlinePlugin)
|
||||
.add(EditorGizmoPlugin)
|
||||
.add(EditorVisualizersPlugin)
|
||||
.add(EditorHistoryPlugin)
|
||||
.add(SceneIoPlugin)
|
||||
.add(EditorUiPlugin)
|
||||
.add(brp::BrpPlugin);
|
||||
#[cfg(feature = "hot-reload")]
|
||||
let group = group.add(hot_reload::HotReloadPlugin);
|
||||
group
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared Bevy app wiring for the in-process editor (game sim + egui shell).
|
||||
pub fn configure_editor_app(app: &mut App) {
|
||||
app.add_plugins(launch::default_plugins("Bevy FPS Editor"))
|
||||
.insert_resource(GameInputEnabled(false))
|
||||
.insert_resource(GameInputFocused(false))
|
||||
.insert_resource(SimEnabled(false))
|
||||
.insert_resource(GameRenderBootstrap {
|
||||
defer_player_camera_fx: true,
|
||||
})
|
||||
.add_plugins(GamePlugin)
|
||||
.add_plugins(MeshPickingPlugin)
|
||||
.add_plugins(TransformGizmoPlugin)
|
||||
.add_plugins(EguiPlugin::default())
|
||||
.add_plugins(EditorPluginGroup);
|
||||
}
|
||||
|
||||
/// Register game-provided editor panel hooks (ADR 0007 dogfood).
|
||||
pub fn register_game_editor_plugins(app: &mut App) {
|
||||
for setup in game::editor_ext::editor_panel_setups() {
|
||||
extensibility::register_editor_plugin(app, Box::new(GamePanelAdapter(*setup)));
|
||||
}
|
||||
ext::game_inspector::register_game_inspector_sections(app);
|
||||
}
|
||||
|
||||
struct GamePanelAdapter(game::editor_ext::EditorPanelSetup);
|
||||
|
||||
impl extensibility::EditorPlugin for GamePanelAdapter {
|
||||
fn name(&self) -> &str {
|
||||
"game.fps_demo_panel"
|
||||
}
|
||||
|
||||
fn register(&self, app: &mut App) {
|
||||
(self.0)(app);
|
||||
app.add_plugins(ext::game_panels::GameEditorPanelsPlugin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//! Play-in-editor session, editor mode state, and net editor profiles.
|
||||
|
||||
pub mod net_editor;
|
||||
mod session;
|
||||
pub mod state;
|
||||
|
||||
pub use session::*;
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Multiplayer / determinism editor tooling (H4).
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum NetPlayProfile {
|
||||
#[default]
|
||||
LocalPie,
|
||||
ListenServer,
|
||||
ConnectToServer,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct NetEditorState {
|
||||
pub profile: NetPlayProfile,
|
||||
pub server_address: String,
|
||||
pub show_determinism_hud: bool,
|
||||
pub last_state_hash: u64,
|
||||
pub replay_tick: u64,
|
||||
}
|
||||
|
||||
impl Default for NetEditorState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
profile: NetPlayProfile::LocalPie,
|
||||
server_address: "127.0.0.1:7777".into(),
|
||||
show_determinism_hud: true,
|
||||
last_state_hash: 0,
|
||||
replay_tick: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NetEditorPlugin;
|
||||
|
||||
impl Plugin for NetEditorPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<NetEditorState>()
|
||||
.add_systems(Update, update_determinism_hud);
|
||||
}
|
||||
}
|
||||
|
||||
fn update_determinism_hud(
|
||||
mut state: ResMut<NetEditorState>,
|
||||
players: Query<(&Transform, &sim::PlayerVelocity), With<sim::Player>>,
|
||||
) {
|
||||
if !state.show_determinism_hud {
|
||||
return;
|
||||
}
|
||||
let Some((transform, velocity)) = players.iter().next() else {
|
||||
return;
|
||||
};
|
||||
state.replay_tick = state.replay_tick.wrapping_add(1);
|
||||
let bits = transform.translation.to_array().map(f32::to_bits);
|
||||
let vel = velocity.0.to_array().map(f32::to_bits);
|
||||
state.last_state_hash = bits[0] as u64 ^ (bits[1] as u64) << 16 ^ vel[0] as u64;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Play-in-editor session: player bootstrap and viewport camera binding.
|
||||
|
||||
use bevy::camera::RenderTarget;
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::WindowRef;
|
||||
use game::player::PlayerCamera;
|
||||
use protocol::PlayerInputIntent;
|
||||
use settings::SimTuning;
|
||||
use shared::{inspector_component_active, InspectorOrder, PlayerSpawn, COMPONENT_PLAYER_SPAWN};
|
||||
use sim::{Crouching, Grounded, JumpState, Player, PlayerVelocity};
|
||||
|
||||
use crate::render_target::ViewportRenderTarget;
|
||||
use crate::state::{EditorMode, PlayPossession};
|
||||
|
||||
pub struct PlaySessionPlugin;
|
||||
|
||||
impl Plugin for PlaySessionPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(OnEnter(EditorMode::Playing), bootstrap_player_on_play)
|
||||
.add_systems(
|
||||
PostUpdate,
|
||||
sync_play_camera_target.after(crate::scene_view::ensure_viewport_render_target),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Default player spawn used when no [`PlayerSpawn`] marker exists in the scene.
|
||||
pub fn default_player_spawn() -> Transform {
|
||||
Transform::from_xyz(0.0, 1.5, 10.0)
|
||||
}
|
||||
|
||||
pub(crate) fn sync_play_camera_target(
|
||||
mode: Res<State<EditorMode>>,
|
||||
possession: Res<PlayPossession>,
|
||||
target: Res<ViewportRenderTarget>,
|
||||
mut player_cameras: Query<(Entity, &mut Camera), With<PlayerCamera>>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
let possessed = *mode.get() == EditorMode::Playing && *possession == PlayPossession::Possessed;
|
||||
|
||||
for (entity, mut camera) in &mut player_cameras {
|
||||
camera.viewport = None;
|
||||
|
||||
if possessed {
|
||||
let Some(viewport_target) = target.0.as_ref() else {
|
||||
camera.is_active = false;
|
||||
continue;
|
||||
};
|
||||
camera.is_active = true;
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(RenderTarget::Image(viewport_target.image.clone().into()));
|
||||
} else {
|
||||
camera.is_active = false;
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(RenderTarget::Window(WindowRef::Primary));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bootstrap_player_on_play(world: &mut World) {
|
||||
let tuning = world
|
||||
.get_resource::<SimTuning>()
|
||||
.copied()
|
||||
.unwrap_or_else(|| SimTuning::from_physics(&settings::PhysicsSettings::default()));
|
||||
|
||||
let spawn = world
|
||||
.query_filtered::<(&Transform, Option<&InspectorOrder>), With<PlayerSpawn>>()
|
||||
.iter(world)
|
||||
.filter(|(_, order)| inspector_component_active(*order, COMPONENT_PLAYER_SPAWN))
|
||||
.map(|(transform, _)| transform)
|
||||
.next()
|
||||
.copied()
|
||||
.unwrap_or_else(default_player_spawn);
|
||||
|
||||
let mut player_query = world.query_filtered::<(
|
||||
Entity,
|
||||
&mut Transform,
|
||||
&mut PlayerVelocity,
|
||||
&mut PlayerInputIntent,
|
||||
&mut JumpState,
|
||||
&mut Grounded,
|
||||
&mut Crouching,
|
||||
), With<Player>>();
|
||||
let Some((
|
||||
player_entity,
|
||||
mut transform,
|
||||
mut velocity,
|
||||
mut intent,
|
||||
mut jump,
|
||||
mut grounded,
|
||||
mut crouching,
|
||||
)) = player_query.iter_mut(world).next()
|
||||
else {
|
||||
warn!("Play mode entered but no Player entity exists");
|
||||
return;
|
||||
};
|
||||
|
||||
*transform = spawn;
|
||||
velocity.0 = Vec3::ZERO;
|
||||
*intent = PlayerInputIntent::default();
|
||||
*jump = JumpState::default();
|
||||
grounded.0 = false;
|
||||
crouching.0 = false;
|
||||
let position = transform.translation;
|
||||
|
||||
{
|
||||
let mut camera_query = world.query_filtered::<&mut Transform, With<PlayerCamera>>();
|
||||
for mut camera_transform in camera_query.iter_mut(world) {
|
||||
camera_transform.translation = Vec3::new(0.0, tuning.eye_offset_stand, 0.0);
|
||||
camera_transform.rotation = Quat::IDENTITY;
|
||||
}
|
||||
}
|
||||
|
||||
info!("Play session started: player {player_entity:?} at {position:?}");
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
|
||||
use bevy_egui::PrimaryEguiContext;
|
||||
use game::player::PlayerCamera;
|
||||
use game::{GameInputEnabled, GameInputFocused, SimEnabled};
|
||||
use protocol::PlayerInputIntent;
|
||||
use sim::{Crouching, Grounded, JumpState, Player, PlayerVelocity};
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::scene_io::SceneIo;
|
||||
|
||||
/// Editor/game mode. `Playing` runs the real game sim; use [`PlayPossession`] for camera control.
|
||||
#[derive(States, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum EditorMode {
|
||||
#[default]
|
||||
Editing,
|
||||
Playing,
|
||||
}
|
||||
|
||||
/// FPS vs editor fly camera while sim runs in Play mode.
|
||||
#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum PlayPossession {
|
||||
#[default]
|
||||
Possessed,
|
||||
Ejected,
|
||||
}
|
||||
|
||||
/// Player/sim state captured on play enter, restored on play stop.
|
||||
#[derive(Resource, Default, Clone)]
|
||||
pub struct PlayModeSnapshot {
|
||||
pub player: Option<PlayerSimSnapshot>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PlayerSimSnapshot {
|
||||
pub transform: Transform,
|
||||
pub velocity: Vec3,
|
||||
pub intent: PlayerInputIntent,
|
||||
pub jump_coyote: f32,
|
||||
pub jump_buffer: f32,
|
||||
pub grounded: bool,
|
||||
pub crouching: bool,
|
||||
pub camera_local: Transform,
|
||||
}
|
||||
|
||||
/// When true, Play mode is active but the fixed-step sim is frozen.
|
||||
#[derive(Resource, Debug, Clone, Copy, Default)]
|
||||
pub struct PlayPaused(pub bool);
|
||||
|
||||
/// Request one fixed-step sim tick while paused in Play mode (H3).
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct PlayStepOnce(pub bool);
|
||||
|
||||
pub struct EditorStatePlugin;
|
||||
|
||||
impl Plugin for EditorStatePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_state::<EditorMode>()
|
||||
.init_resource::<PlayPossession>()
|
||||
.init_resource::<PlayPaused>()
|
||||
.init_resource::<PlayStepOnce>()
|
||||
.init_resource::<PlayModeSnapshot>()
|
||||
.add_systems(PostStartup, init_player_camera_for_editor)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
toggle_editor_mode,
|
||||
toggle_play_pause,
|
||||
toggle_play_step,
|
||||
toggle_play_possession,
|
||||
sync_mode_resources_and_cameras,
|
||||
sync_play_input_focus,
|
||||
)
|
||||
.chain(),
|
||||
)
|
||||
.add_systems(
|
||||
OnEnter(EditorMode::Playing),
|
||||
(
|
||||
enter_play_mode,
|
||||
reset_possession,
|
||||
reset_play_paused,
|
||||
grab_play_cursor,
|
||||
),
|
||||
)
|
||||
.add_systems(
|
||||
OnEnter(EditorMode::Editing),
|
||||
(exit_play_mode, reset_play_paused, release_play_cursor),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Scene tools (selection, gizmos, undo, fly cam) are active in Edit mode or ejected PIE.
|
||||
pub fn scene_tools_active(mode: Res<State<EditorMode>>, possession: Res<PlayPossession>) -> bool {
|
||||
match mode.get() {
|
||||
EditorMode::Editing => true,
|
||||
EditorMode::Playing => *possession == PlayPossession::Ejected,
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_editor_mode(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
state: Res<State<EditorMode>>,
|
||||
mut next: ResMut<NextState<EditorMode>>,
|
||||
) {
|
||||
if keys.just_pressed(KeyCode::F5) {
|
||||
next.set(match state.get() {
|
||||
EditorMode::Editing => EditorMode::Playing,
|
||||
EditorMode::Playing => EditorMode::Editing,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_play_possession(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
mode: Res<State<EditorMode>>,
|
||||
mut possession: ResMut<PlayPossession>,
|
||||
mut cursor: Single<&mut CursorOptions, With<PrimaryWindow>>,
|
||||
mut editor_cameras: Query<&mut Transform, With<EditorCamera>>,
|
||||
player: Query<&GlobalTransform, With<Player>>,
|
||||
player_cameras: Query<&GlobalTransform, With<PlayerCamera>>,
|
||||
) {
|
||||
if *mode.get() != EditorMode::Playing || !keys.just_pressed(KeyCode::F8) {
|
||||
return;
|
||||
}
|
||||
|
||||
match *possession {
|
||||
PlayPossession::Possessed => {
|
||||
*possession = PlayPossession::Ejected;
|
||||
if let Ok(camera_gt) = player_cameras.single() {
|
||||
for mut editor_transform in &mut editor_cameras {
|
||||
*editor_transform = Transform {
|
||||
translation: camera_gt.translation(),
|
||||
rotation: camera_gt.rotation(),
|
||||
..default()
|
||||
};
|
||||
}
|
||||
} else if let Ok(player_gt) = player.single() {
|
||||
for mut editor_transform in &mut editor_cameras {
|
||||
editor_transform.translation = player_gt.translation();
|
||||
}
|
||||
}
|
||||
release_play_cursor_internal(&mut cursor);
|
||||
}
|
||||
PlayPossession::Ejected => {
|
||||
*possession = PlayPossession::Possessed;
|
||||
grab_play_cursor_internal(&mut cursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_play_pause(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
mode: Res<State<EditorMode>>,
|
||||
mut paused: ResMut<PlayPaused>,
|
||||
) {
|
||||
if *mode.get() != EditorMode::Playing || !keys.just_pressed(KeyCode::F6) {
|
||||
return;
|
||||
}
|
||||
paused.0 = !paused.0;
|
||||
}
|
||||
|
||||
fn toggle_play_step(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
mode: Res<State<EditorMode>>,
|
||||
paused: Res<PlayPaused>,
|
||||
mut step: ResMut<PlayStepOnce>,
|
||||
) {
|
||||
if *mode.get() != EditorMode::Playing || !paused.0 || !keys.just_pressed(KeyCode::F7) {
|
||||
return;
|
||||
}
|
||||
step.0 = true;
|
||||
}
|
||||
|
||||
fn reset_play_paused(mut paused: ResMut<PlayPaused>) {
|
||||
paused.0 = false;
|
||||
}
|
||||
|
||||
fn reset_possession(mut possession: ResMut<PlayPossession>) {
|
||||
*possession = PlayPossession::Possessed;
|
||||
}
|
||||
|
||||
pub(crate) fn init_player_camera_for_editor(
|
||||
mut player_cameras: Query<&mut Camera, (With<PlayerCamera>, Without<EditorCamera>)>,
|
||||
) {
|
||||
for mut camera in &mut player_cameras {
|
||||
camera.order = 1;
|
||||
camera.is_active = false;
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn sync_mode_resources_and_cameras(
|
||||
state: Res<State<EditorMode>>,
|
||||
possession: Res<PlayPossession>,
|
||||
paused: Res<PlayPaused>,
|
||||
mut step: ResMut<PlayStepOnce>,
|
||||
mut input_enabled: ResMut<GameInputEnabled>,
|
||||
mut sim_enabled: ResMut<SimEnabled>,
|
||||
mut editor_cameras: Query<&mut Camera, With<EditorCamera>>,
|
||||
mut player_cameras: Query<&mut Camera, (With<PlayerCamera>, Without<EditorCamera>)>,
|
||||
mut egui_cameras: Query<
|
||||
&mut Camera,
|
||||
(
|
||||
With<PrimaryEguiContext>,
|
||||
Without<EditorCamera>,
|
||||
Without<PlayerCamera>,
|
||||
),
|
||||
>,
|
||||
mut last_mode: Local<Option<(EditorMode, PlayPossession)>>,
|
||||
) {
|
||||
let mode = *state.get();
|
||||
let playing = mode == EditorMode::Playing;
|
||||
let ejected = playing && *possession == PlayPossession::Ejected;
|
||||
let possessed = playing && *possession == PlayPossession::Possessed;
|
||||
|
||||
sim_enabled.0 = playing && (!paused.0 || step.0);
|
||||
input_enabled.0 = possessed && !paused.0;
|
||||
if step.0 {
|
||||
step.0 = false;
|
||||
}
|
||||
|
||||
for mut camera in &mut editor_cameras {
|
||||
camera.is_active = !playing || ejected;
|
||||
}
|
||||
for mut camera in &mut player_cameras {
|
||||
camera.is_active = possessed;
|
||||
}
|
||||
|
||||
for mut camera in &mut egui_cameras {
|
||||
camera.clear_color = if !playing || ejected {
|
||||
ClearColorConfig::None
|
||||
} else {
|
||||
ClearColorConfig::Custom(Color::BLACK)
|
||||
};
|
||||
}
|
||||
|
||||
let key = (mode, *possession);
|
||||
if *last_mode != Some(key) {
|
||||
*last_mode = Some(key);
|
||||
info!("EditorMode -> {mode:?}, possession -> {possession:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_play_input_focus(
|
||||
mode: Res<State<EditorMode>>,
|
||||
possession: Res<PlayPossession>,
|
||||
paused: Res<PlayPaused>,
|
||||
mut focused: ResMut<GameInputFocused>,
|
||||
) {
|
||||
focused.0 =
|
||||
*mode.get() == EditorMode::Playing && *possession == PlayPossession::Possessed && !paused.0;
|
||||
}
|
||||
|
||||
fn enter_play_mode(world: &mut World) {
|
||||
let snapshot = snapshot_player_sim(world);
|
||||
world.resource_mut::<PlayModeSnapshot>().player = Some(snapshot);
|
||||
}
|
||||
|
||||
fn exit_play_mode(world: &mut World) {
|
||||
if let Some(snapshot) = world.resource_mut::<PlayModeSnapshot>().player.take() {
|
||||
restore_player_sim(world, &snapshot);
|
||||
}
|
||||
if let Some(mut scene_io) = world.get_resource_mut::<SceneIo>() {
|
||||
scene_io.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot_player_sim(world: &mut World) -> PlayerSimSnapshot {
|
||||
let player_data = {
|
||||
let mut player_query = world.query_filtered::<(
|
||||
&Transform,
|
||||
&PlayerVelocity,
|
||||
&PlayerInputIntent,
|
||||
&JumpState,
|
||||
&Grounded,
|
||||
&Crouching,
|
||||
), With<Player>>();
|
||||
|
||||
player_query.iter(world).next().map(
|
||||
|(transform, velocity, intent, jump, grounded, crouching)| {
|
||||
(
|
||||
*transform,
|
||||
velocity.0,
|
||||
*intent,
|
||||
jump.coyote,
|
||||
jump.buffer,
|
||||
grounded.0,
|
||||
crouching.0,
|
||||
)
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let Some((transform, velocity, intent, jump_coyote, jump_buffer, grounded, crouching)) =
|
||||
player_data
|
||||
else {
|
||||
return PlayerSimSnapshot {
|
||||
transform: Transform::default(),
|
||||
velocity: Vec3::ZERO,
|
||||
intent: PlayerInputIntent::default(),
|
||||
jump_coyote: 0.0,
|
||||
jump_buffer: 0.0,
|
||||
grounded: false,
|
||||
crouching: false,
|
||||
camera_local: Transform::IDENTITY,
|
||||
};
|
||||
};
|
||||
|
||||
let camera_local = {
|
||||
let mut camera_query = world.query_filtered::<&Transform, With<PlayerCamera>>();
|
||||
camera_query
|
||||
.iter(world)
|
||||
.next()
|
||||
.copied()
|
||||
.unwrap_or(Transform::IDENTITY)
|
||||
};
|
||||
|
||||
PlayerSimSnapshot {
|
||||
transform,
|
||||
velocity,
|
||||
intent,
|
||||
jump_coyote,
|
||||
jump_buffer,
|
||||
grounded,
|
||||
crouching,
|
||||
camera_local,
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_player_sim(world: &mut World, snapshot: &PlayerSimSnapshot) {
|
||||
let mut player_query = world.query_filtered::<(
|
||||
&mut Transform,
|
||||
&mut PlayerVelocity,
|
||||
&mut PlayerInputIntent,
|
||||
&mut JumpState,
|
||||
&mut Grounded,
|
||||
&mut Crouching,
|
||||
), With<Player>>();
|
||||
|
||||
if let Some((mut transform, mut velocity, mut intent, mut jump, mut grounded, mut crouching)) =
|
||||
player_query.iter_mut(world).next()
|
||||
{
|
||||
*transform = snapshot.transform;
|
||||
velocity.0 = snapshot.velocity;
|
||||
*intent = snapshot.intent;
|
||||
*jump = JumpState {
|
||||
coyote: snapshot.jump_coyote,
|
||||
buffer: snapshot.jump_buffer,
|
||||
};
|
||||
grounded.0 = snapshot.grounded;
|
||||
crouching.0 = snapshot.crouching;
|
||||
}
|
||||
|
||||
let mut camera_query = world.query_filtered::<&mut Transform, With<PlayerCamera>>();
|
||||
for mut camera in camera_query.iter_mut(world) {
|
||||
*camera = snapshot.camera_local;
|
||||
}
|
||||
}
|
||||
|
||||
fn grab_play_cursor(mut cursor: Single<&mut CursorOptions, With<PrimaryWindow>>) {
|
||||
grab_play_cursor_internal(&mut cursor);
|
||||
}
|
||||
|
||||
fn release_play_cursor(mut cursor: Single<&mut CursorOptions, With<PrimaryWindow>>) {
|
||||
release_play_cursor_internal(&mut cursor);
|
||||
}
|
||||
|
||||
fn grab_play_cursor_internal(cursor: &mut CursorOptions) {
|
||||
cursor.grab_mode = CursorGrabMode::Locked;
|
||||
cursor.visible = false;
|
||||
}
|
||||
|
||||
fn release_play_cursor_internal(cursor: &mut CursorOptions) {
|
||||
cursor.grab_mode = CursorGrabMode::None;
|
||||
cursor.visible = true;
|
||||
}
|
||||
|
||||
/// Toggles possess/eject from UI (mirrors F8 handling in [`toggle_play_possession`]).
|
||||
pub fn toggle_play_possession_world(world: &mut World) {
|
||||
if *world.resource::<State<EditorMode>>().get() != EditorMode::Playing {
|
||||
return;
|
||||
}
|
||||
let next = match *world.resource::<PlayPossession>() {
|
||||
PlayPossession::Possessed => PlayPossession::Ejected,
|
||||
PlayPossession::Ejected => PlayPossession::Possessed,
|
||||
};
|
||||
*world.resource_mut::<PlayPossession>() = next;
|
||||
|
||||
let mut cursor = world
|
||||
.query_filtered::<&mut CursorOptions, With<PrimaryWindow>>()
|
||||
.single_mut(world)
|
||||
.expect("primary window cursor");
|
||||
|
||||
match next {
|
||||
PlayPossession::Possessed => grab_play_cursor_internal(&mut cursor),
|
||||
PlayPossession::Ejected => {
|
||||
release_play_cursor_internal(&mut cursor);
|
||||
let camera_pose = world
|
||||
.query_filtered::<&GlobalTransform, With<PlayerCamera>>()
|
||||
.single(world)
|
||||
.ok()
|
||||
.map(|gt| (gt.translation(), gt.rotation()));
|
||||
if let Some((translation, rotation)) = camera_pose {
|
||||
let mut editor_query = world.query_filtered::<&mut Transform, With<EditorCamera>>();
|
||||
for mut editor_transform in editor_query.iter_mut(world) {
|
||||
*editor_transform = Transform {
|
||||
translation,
|
||||
rotation,
|
||||
..default()
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Project workspace I/O, settings UI, and recent-level sync.
|
||||
|
||||
pub mod project_io;
|
||||
pub mod settings_ui;
|
||||
pub mod workspace;
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Project workspace I/O and user-local preferences (separate from `assets/project.ron`).
|
||||
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use settings::{ProjectSettings, ProjectSettingsIo, DEFAULT_PROJECT_PATH};
|
||||
|
||||
use crate::scene_io::SceneIo;
|
||||
|
||||
const USER_CONFIG_DIR: &str = ".config/bevy-fps";
|
||||
const USER_PREFS_FILE: &str = "editor_prefs.ron";
|
||||
|
||||
/// User-local editor preferences (not checked into the repo).
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Resource)]
|
||||
pub struct UserPreferences {
|
||||
pub recent_projects: Vec<String>,
|
||||
pub recent_levels: Vec<String>,
|
||||
pub last_project_root: Option<String>,
|
||||
/// Serialized [`crate::ui::layout::DockLayoutSnapshot`] (RON).
|
||||
pub dock_layout: Option<String>,
|
||||
#[serde(default)]
|
||||
pub save_before_play: bool,
|
||||
/// Hierarchy search filter (persisted between sessions).
|
||||
#[serde(default)]
|
||||
pub hierarchy_filter: String,
|
||||
/// Hierarchy paths expanded in the outliner (name paths like `Group/Cube`).
|
||||
#[serde(default)]
|
||||
pub hierarchy_expanded_paths: Vec<String>,
|
||||
#[serde(default = "default_true")]
|
||||
pub hierarchy_show_generated: bool,
|
||||
#[serde(default)]
|
||||
pub hierarchy_show_runtime: bool,
|
||||
#[serde(default)]
|
||||
pub hierarchy_sort_mode: crate::ui::hierarchy_state::HierarchySort,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Active project workspace metadata (mirrors manifest fields in `ProjectSettings`).
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct ProjectWorkspace {
|
||||
pub root: String,
|
||||
pub settings_path: String,
|
||||
pub settings_dirty: bool,
|
||||
pub layout_dirty: bool,
|
||||
}
|
||||
|
||||
impl Default for ProjectWorkspace {
|
||||
fn default() -> Self {
|
||||
let root = std::env::current_dir()
|
||||
.ok()
|
||||
.and_then(|path| path.into_os_string().into_string().ok())
|
||||
.unwrap_or_else(|| ".".into());
|
||||
Self {
|
||||
root,
|
||||
settings_path: DEFAULT_PROJECT_PATH.into(),
|
||||
settings_dirty: false,
|
||||
layout_dirty: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ProjectIoPlugin;
|
||||
|
||||
impl Plugin for ProjectIoPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<UserPreferences>()
|
||||
.init_resource::<ProjectWorkspace>()
|
||||
.add_systems(Startup, load_user_preferences_on_startup)
|
||||
.add_systems(Update, sync_workspace_from_settings_system);
|
||||
}
|
||||
}
|
||||
|
||||
fn load_user_preferences(mut commands: Commands) {
|
||||
let prefs = read_user_preferences();
|
||||
commands.insert_resource(prefs);
|
||||
}
|
||||
|
||||
/// Startup system; registered before [`crate::ui::apply_ui_state_from_prefs`].
|
||||
pub(crate) fn load_user_preferences_on_startup(commands: Commands) {
|
||||
load_user_preferences(commands);
|
||||
}
|
||||
|
||||
fn sync_workspace_from_settings_system(
|
||||
settings: Res<ProjectSettings>,
|
||||
settings_io: Res<ProjectSettingsIo>,
|
||||
mut workspace: ResMut<ProjectWorkspace>,
|
||||
) {
|
||||
if !settings_io.is_changed() && !settings.is_changed() {
|
||||
return;
|
||||
}
|
||||
sync_workspace_from_settings(&mut workspace, &settings, &settings_io);
|
||||
}
|
||||
|
||||
fn user_prefs_path() -> Option<std::path::PathBuf> {
|
||||
std::env::var_os("HOME").map(|home| {
|
||||
std::path::PathBuf::from(home)
|
||||
.join(USER_CONFIG_DIR)
|
||||
.join(USER_PREFS_FILE)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn read_user_preferences() -> UserPreferences {
|
||||
let Some(path) = user_prefs_path() else {
|
||||
return UserPreferences::default();
|
||||
};
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => ron::from_str(&text).unwrap_or_default(),
|
||||
Err(_) => UserPreferences::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_user_preferences(prefs: &UserPreferences) -> Result<(), String> {
|
||||
let path = user_prefs_path().ok_or_else(|| "HOME not set".to_string())?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let text = ron::ser::to_string_pretty(prefs, ron::ser::PrettyConfig::default())
|
||||
.map_err(|e| e.to_string())?;
|
||||
std::fs::write(path, text).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn push_recent(list: &mut Vec<String>, entry: String, max: usize) {
|
||||
list.retain(|item| item != &entry);
|
||||
list.insert(0, entry);
|
||||
list.truncate(max);
|
||||
}
|
||||
|
||||
pub fn sync_workspace_from_settings(
|
||||
workspace: &mut ProjectWorkspace,
|
||||
settings: &ProjectSettings,
|
||||
settings_io: &ProjectSettingsIo,
|
||||
) {
|
||||
workspace.settings_path = settings_io.path.clone();
|
||||
workspace.settings_dirty = settings_io.dirty;
|
||||
let _ = settings;
|
||||
}
|
||||
|
||||
pub fn window_title(
|
||||
scene_io: &SceneIo,
|
||||
workspace: &ProjectWorkspace,
|
||||
settings: &ProjectSettings,
|
||||
) -> String {
|
||||
let mut parts = vec![format!("{} — Bevy FPS Editor", settings.name)];
|
||||
if !workspace.root.is_empty() && workspace.root != "." {
|
||||
parts.push(workspace.root.clone());
|
||||
}
|
||||
if let Some(path) = &scene_io.active_path {
|
||||
parts.push(path.display().to_string());
|
||||
}
|
||||
if scene_io.dirty {
|
||||
parts.push("*".into());
|
||||
}
|
||||
if workspace.settings_dirty {
|
||||
parts.push("[project*]".into());
|
||||
}
|
||||
if workspace.layout_dirty {
|
||||
parts.push("[layout*]".into());
|
||||
}
|
||||
parts.join(" — ")
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! Editor-only Project Settings panel (egui). Data lives in the `settings` crate.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use game_hot::sync_project_sun_from_settings;
|
||||
use settings::{
|
||||
load_project_settings_from_path, save_project_settings, sync_sim_tuning, ExposureMode,
|
||||
ProjectSettings, ProjectSettingsChanged, ProjectSettingsIo,
|
||||
};
|
||||
|
||||
/// Whether the Project Settings window is visible (editor UI state only).
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct ProjectSettingsPanel {
|
||||
pub open: bool,
|
||||
pub draft: Option<ProjectSettings>,
|
||||
}
|
||||
|
||||
pub struct SettingsUiPlugin;
|
||||
|
||||
impl Plugin for SettingsUiPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<ProjectSettingsPanel>().add_systems(
|
||||
PostUpdate,
|
||||
apply_project_settings_changes
|
||||
.after(crate::scene_view::sync_editor_camera_viewport_target),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_project_settings_panel(panel: &mut ProjectSettingsPanel) {
|
||||
panel.open = true;
|
||||
panel.draft = None;
|
||||
}
|
||||
|
||||
pub fn project_settings_window(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
panel: &mut ProjectSettingsPanel,
|
||||
) {
|
||||
if !panel.open {
|
||||
panel.draft = None;
|
||||
return;
|
||||
}
|
||||
|
||||
if panel.draft.is_none() {
|
||||
panel.draft = Some(world.resource::<ProjectSettings>().clone());
|
||||
}
|
||||
|
||||
let mut open = panel.open;
|
||||
egui::Window::new("Project Settings")
|
||||
.open(&mut open)
|
||||
.default_width(420.0)
|
||||
.show(ctx, |ui| {
|
||||
let Some(draft) = panel.draft.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let io_path = world.resource::<ProjectSettingsIo>().path.clone();
|
||||
let mut io_dirty = world.resource::<ProjectSettingsIo>().dirty;
|
||||
draw_project_settings_form(world, ui, draft, &io_path, &mut io_dirty);
|
||||
world.resource_mut::<ProjectSettingsIo>().dirty = io_dirty;
|
||||
});
|
||||
panel.open = open;
|
||||
if !open {
|
||||
panel.draft = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_project_settings_form(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
draft: &mut ProjectSettings,
|
||||
io_path: &str,
|
||||
io_dirty: &mut bool,
|
||||
) {
|
||||
let caps = world
|
||||
.get_resource::<settings::RenderingCapabilities>()
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
ui.collapsing("Global Illumination", |ui| {
|
||||
egui::ComboBox::from_label("GiMode")
|
||||
.selected_text(format!("{:?}", draft.rendering.gi_mode))
|
||||
.show_ui(ui, |ui| {
|
||||
for mode in [
|
||||
settings::GiMode::Auto,
|
||||
settings::GiMode::Forward,
|
||||
settings::GiMode::Solari,
|
||||
] {
|
||||
if ui
|
||||
.selectable_value(&mut draft.rendering.gi_mode, mode, format!("{mode:?}"))
|
||||
.clicked()
|
||||
{}
|
||||
}
|
||||
});
|
||||
ui.small("Auto uses Solari when RT GPU support is available; otherwise Forward PBR.");
|
||||
let status = match (draft.rendering.gi_mode, caps.rt_supported) {
|
||||
(settings::GiMode::Forward, _) => "Forward PBR",
|
||||
(settings::GiMode::Solari, true) => "Solari active",
|
||||
(settings::GiMode::Solari, false) => "Solari requested — will fall back (no RT)",
|
||||
(settings::GiMode::Auto, true) => "Auto → Solari when playing",
|
||||
(settings::GiMode::Auto, false) => "Auto → Forward fallback (no RT)",
|
||||
};
|
||||
ui.label(format!("Status: {status}"));
|
||||
ui.small("Open Window → Rendering for resolved active-camera stack.");
|
||||
});
|
||||
|
||||
ui.collapsing("Lighting", |ui| {
|
||||
ui.label("Ambient");
|
||||
ui.horizontal(|ui| {
|
||||
let mut rgb = [
|
||||
draft.rendering.ambient_color[0],
|
||||
draft.rendering.ambient_color[1],
|
||||
draft.rendering.ambient_color[2],
|
||||
];
|
||||
if ui.color_edit_button_rgb(&mut rgb).changed() {
|
||||
draft.rendering.ambient_color = rgb;
|
||||
}
|
||||
});
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.rendering.ambient_brightness, 0.0..=200.0)
|
||||
.text("Ambient brightness"),
|
||||
);
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.rendering.sun_illuminance, 1_000.0..=150_000.0)
|
||||
.text("Sun illuminance (lux)"),
|
||||
);
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.rendering.shadow_cascades, 1..=4).text("Shadow cascades"),
|
||||
);
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.rendering.shadow_first_cascade, 1.0..=20.0)
|
||||
.text("First cascade (m)"),
|
||||
);
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.rendering.shadow_max_distance, 50.0..=500.0)
|
||||
.text("Shadow max distance"),
|
||||
);
|
||||
});
|
||||
|
||||
ui.collapsing("Post Process", |ui| {
|
||||
ui.checkbox(&mut draft.rendering.hdr, "HDR");
|
||||
ui.small("The viewport uses HDR when Lit mode is active.");
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Exposure");
|
||||
if ui
|
||||
.selectable_label(
|
||||
draft.rendering.exposure_mode == ExposureMode::Manual,
|
||||
"Manual",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
draft.rendering.exposure_mode = ExposureMode::Manual;
|
||||
}
|
||||
if ui
|
||||
.selectable_label(draft.rendering.exposure_mode == ExposureMode::Auto, "Auto")
|
||||
.clicked()
|
||||
{
|
||||
draft.rendering.exposure_mode = ExposureMode::Auto;
|
||||
}
|
||||
});
|
||||
let manual = draft.rendering.exposure_mode == ExposureMode::Manual;
|
||||
if manual {
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.rendering.exposure_ev100, 0.0..=20.0)
|
||||
.text("Exposure EV100"),
|
||||
);
|
||||
} else {
|
||||
ui.add_enabled(
|
||||
false,
|
||||
egui::Slider::new(&mut draft.rendering.exposure_ev100, 0.0..=20.0)
|
||||
.text("Exposure EV100"),
|
||||
);
|
||||
ui.small("Scene brightness adapts automatically (histogram metering).");
|
||||
ui.add(
|
||||
egui::Slider::new(
|
||||
&mut draft.rendering.auto_exposure_speed_brighten,
|
||||
0.1..=10.0,
|
||||
)
|
||||
.text("Auto brighten (f-stops/s)"),
|
||||
);
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.rendering.auto_exposure_speed_darken, 0.1..=10.0)
|
||||
.text("Auto darken (f-stops/s)"),
|
||||
);
|
||||
if !draft.rendering.hdr {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Auto exposure requires HDR — enable HDR or use Manual.",
|
||||
);
|
||||
} else {
|
||||
ui.small("Requires GPU compute; see Window → Rendering if unavailable.");
|
||||
}
|
||||
}
|
||||
ui.checkbox(&mut draft.rendering.tonemapping_aces, "Tonemapping ACES");
|
||||
ui.checkbox(&mut draft.rendering.bloom, "Bloom");
|
||||
ui.checkbox(&mut draft.rendering.taa, "TAA");
|
||||
ui.checkbox(&mut draft.rendering.ssao, "SSAO");
|
||||
ui.checkbox(&mut draft.rendering.atmosphere, "Atmosphere");
|
||||
ui.label("Fog");
|
||||
ui.horizontal(|ui| {
|
||||
let mut fog_rgb = draft.rendering.fog_color;
|
||||
if ui.color_edit_button_rgb(&mut fog_rgb).changed() {
|
||||
draft.rendering.fog_color = fog_rgb;
|
||||
}
|
||||
});
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.rendering.fog_density, 0.0..=0.01)
|
||||
.logarithmic(true)
|
||||
.text("Fog density"),
|
||||
);
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
ui.heading("Physics");
|
||||
ui.add(egui::Slider::new(&mut draft.physics.walk_speed, 1.0..=15.0).text("Walk speed"));
|
||||
ui.add(egui::Slider::new(&mut draft.physics.run_speed, 1.0..=20.0).text("Run speed"));
|
||||
ui.add(egui::Slider::new(&mut draft.physics.gravity, 5.0..=40.0).text("Gravity"));
|
||||
ui.add(egui::Slider::new(&mut draft.physics.jump_speed, 3.0..=15.0).text("Jump speed"));
|
||||
|
||||
ui.separator();
|
||||
ui.heading("Input");
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.input.yaw_sensitivity, 0.0005..=0.01).text("Yaw sensitivity"),
|
||||
);
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.input.pitch_sensitivity, 0.0005..=0.01)
|
||||
.text("Pitch sensitivity"),
|
||||
);
|
||||
ui.add(
|
||||
egui::Slider::new(&mut draft.input.editor_fly_speed, 2.0..=40.0).text("Editor fly speed"),
|
||||
);
|
||||
|
||||
ui.separator();
|
||||
if ui.button("Apply").clicked() {
|
||||
commit_project_settings(world, draft);
|
||||
*io_dirty = true;
|
||||
}
|
||||
if ui.button("Save to disk").clicked() {
|
||||
commit_project_settings(world, draft);
|
||||
let settings = world.resource::<ProjectSettings>().clone();
|
||||
let mut io = world.resource_mut::<ProjectSettingsIo>();
|
||||
if let Err(error) = save_project_settings(&settings, &mut io) {
|
||||
warn!("Save project settings failed: {error}");
|
||||
} else {
|
||||
*io_dirty = false;
|
||||
}
|
||||
}
|
||||
if ui.button("Revert from disk").clicked() {
|
||||
*draft = load_project_settings_from_path(io_path);
|
||||
commit_project_settings(world, draft);
|
||||
world.resource_mut::<ProjectSettingsIo>().dirty = false;
|
||||
*io_dirty = false;
|
||||
}
|
||||
if *io_dirty {
|
||||
ui.label(egui::RichText::new("Unsaved changes").color(egui::Color32::YELLOW));
|
||||
}
|
||||
}
|
||||
|
||||
fn commit_project_settings(world: &mut World, draft: &ProjectSettings) {
|
||||
let previous = world.resource::<ProjectSettings>().rendering.gi_mode;
|
||||
*world.resource_mut::<ProjectSettings>() = draft.clone();
|
||||
if previous != draft.rendering.gi_mode {
|
||||
info!(
|
||||
"Project settings GI mode changed: {:?} -> {:?}",
|
||||
previous, draft.rendering.gi_mode
|
||||
);
|
||||
} else {
|
||||
debug!(
|
||||
"Project settings applied: gi_mode={:?}",
|
||||
draft.rendering.gi_mode
|
||||
);
|
||||
}
|
||||
world.write_message(ProjectSettingsChanged);
|
||||
}
|
||||
|
||||
fn apply_project_settings_changes(
|
||||
mut reader: MessageReader<ProjectSettingsChanged>,
|
||||
mut commands: Commands,
|
||||
settings: Res<ProjectSettings>,
|
||||
tuning: ResMut<settings::SimTuning>,
|
||||
scene_suns: Query<
|
||||
(&shared::LightDesc, Option<&shared::InspectorOrder>),
|
||||
With<shared::LevelObject>,
|
||||
>,
|
||||
project_suns: Query<(&mut DirectionalLight, &mut Visibility), With<shared::ProjectSun>>,
|
||||
) {
|
||||
if reader.read().next().is_none() {
|
||||
return;
|
||||
}
|
||||
sync_sim_tuning(&settings, tuning);
|
||||
{
|
||||
let ambient = settings.rendering.clone();
|
||||
commands.insert_resource(GlobalAmbientLight {
|
||||
color: Color::srgb(
|
||||
ambient.ambient_color[0],
|
||||
ambient.ambient_color[1],
|
||||
ambient.ambient_color[2],
|
||||
),
|
||||
brightness: ambient.ambient_brightness,
|
||||
..default()
|
||||
});
|
||||
}
|
||||
sync_project_sun_from_settings(settings, scene_suns, project_suns);
|
||||
// Full stack refresh runs next frame via `render_view::sync_project_render_view`
|
||||
// when `ProjectSettings` changes.
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Project workspace New/Open and recent scene switcher (H2).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use settings::{
|
||||
load_project_settings_from_path, ProjectSettings, ProjectSettingsIo, DEFAULT_PROJECT_PATH,
|
||||
};
|
||||
|
||||
use crate::history::EditorHistory;
|
||||
use crate::project_io::{push_recent, ProjectWorkspace, UserPreferences};
|
||||
use crate::scene_io::{SceneIo, SceneIoRequest};
|
||||
|
||||
pub struct WorkspacePlugin;
|
||||
|
||||
impl Plugin for WorkspacePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<WorkspaceState>()
|
||||
.init_resource::<WorkspaceIoRequest>()
|
||||
.add_systems(Update, process_workspace_requests);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct WorkspaceState {
|
||||
pub project_name: String,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default, Debug)]
|
||||
pub struct WorkspaceIoRequest {
|
||||
pub new_project: bool,
|
||||
pub open_project: bool,
|
||||
}
|
||||
|
||||
pub fn request_new_project(world: &mut World) {
|
||||
world.resource_mut::<WorkspaceIoRequest>().new_project = true;
|
||||
}
|
||||
|
||||
pub fn request_open_project(world: &mut World) {
|
||||
world.resource_mut::<WorkspaceIoRequest>().open_project = true;
|
||||
}
|
||||
|
||||
pub fn request_open_recent_scene(world: &mut World, index: usize) {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::OpenRecent(index));
|
||||
}
|
||||
|
||||
pub fn sync_recent_levels_to_scene_io(world: &mut World) {
|
||||
let recent: Vec<PathBuf> = world
|
||||
.resource::<UserPreferences>()
|
||||
.recent_levels
|
||||
.iter()
|
||||
.map(PathBuf::from)
|
||||
.collect();
|
||||
world.resource_mut::<SceneIo>().recent_paths = recent;
|
||||
}
|
||||
|
||||
pub fn remember_opened_level(world: &mut World, path: String) {
|
||||
if let Some(mut prefs) = world.get_resource_mut::<UserPreferences>() {
|
||||
push_recent(&mut prefs.recent_levels, path, 8);
|
||||
let _ = crate::project_io::write_user_preferences(&prefs);
|
||||
}
|
||||
}
|
||||
|
||||
fn process_workspace_requests(world: &mut World) {
|
||||
let (new_project, open_project) = {
|
||||
let mut req = world.resource_mut::<WorkspaceIoRequest>();
|
||||
let new_project = req.new_project;
|
||||
let open_project = req.open_project;
|
||||
req.new_project = false;
|
||||
req.open_project = false;
|
||||
(new_project, open_project)
|
||||
};
|
||||
|
||||
if new_project {
|
||||
world.resource_mut::<SceneIo>().status = apply_new_project(world);
|
||||
} else if open_project {
|
||||
world.resource_mut::<SceneIo>().status = apply_open_project(world);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_new_project(world: &mut World) -> String {
|
||||
let default_settings = ProjectSettings::default();
|
||||
let settings_path = DEFAULT_PROJECT_PATH.to_string();
|
||||
|
||||
*world.resource_mut::<ProjectSettings>() = default_settings.clone();
|
||||
world.resource_mut::<ProjectSettingsIo>().path = settings_path.clone();
|
||||
world.resource_mut::<ProjectSettingsIo>().dirty = false;
|
||||
|
||||
if let Some(mut workspace) = world.get_resource_mut::<ProjectWorkspace>() {
|
||||
workspace.root = std::env::current_dir()
|
||||
.ok()
|
||||
.and_then(|p| p.into_os_string().into_string().ok())
|
||||
.unwrap_or_else(|| ".".into());
|
||||
workspace.settings_path = settings_path;
|
||||
workspace.settings_dirty = false;
|
||||
}
|
||||
|
||||
world.resource_mut::<WorkspaceState>().project_name = default_settings.name.clone();
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::New);
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
sync_recent_levels_to_scene_io(world);
|
||||
format!("New project: {}", default_settings.name)
|
||||
}
|
||||
|
||||
fn apply_open_project(world: &mut World) -> String {
|
||||
let Some(root) = rfd::FileDialog::new()
|
||||
.set_title("Open Project Folder")
|
||||
.pick_folder()
|
||||
else {
|
||||
return "Open project cancelled".to_string();
|
||||
};
|
||||
|
||||
let settings_path = root.join("assets/project.ron");
|
||||
if !settings_path.exists() {
|
||||
return format!(
|
||||
"No assets/project.ron in {} — pick a project root folder",
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
|
||||
let settings_path_label = settings_path.display().to_string();
|
||||
let settings = load_project_settings_from_path(&settings_path_label);
|
||||
|
||||
*world.resource_mut::<ProjectSettings>() = settings.clone();
|
||||
world.resource_mut::<ProjectSettingsIo>().path = settings_path_label.clone();
|
||||
world.resource_mut::<ProjectSettingsIo>().dirty = false;
|
||||
|
||||
if let Some(mut workspace) = world.get_resource_mut::<ProjectWorkspace>() {
|
||||
workspace.root = root.display().to_string();
|
||||
workspace.settings_path = settings_path_label;
|
||||
workspace.settings_dirty = false;
|
||||
}
|
||||
|
||||
if let Some(mut prefs) = world.get_resource_mut::<UserPreferences>() {
|
||||
push_recent(&mut prefs.recent_projects, workspace_root_label(&root), 8);
|
||||
prefs.last_project_root = Some(root.display().to_string());
|
||||
let _ = crate::project_io::write_user_preferences(&prefs);
|
||||
}
|
||||
|
||||
world.resource_mut::<WorkspaceState>().project_name = settings.name.clone();
|
||||
sync_recent_levels_to_scene_io(world);
|
||||
format!("Opened project: {}", settings.name)
|
||||
}
|
||||
|
||||
fn workspace_root_label(path: &Path) -> String {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| path.display().to_string())
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Shared HDR render-to-texture helpers for editor viewport panels.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::render::render_resource::TextureFormat;
|
||||
|
||||
/// Offscreen render target displayed by the primary editor viewport.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ViewportTarget {
|
||||
pub image: Handle<Image>,
|
||||
}
|
||||
|
||||
/// Current primary viewport render target, if the panel has a valid size.
|
||||
#[derive(Resource, Default, Debug, Clone)]
|
||||
pub struct ViewportRenderTarget(pub Option<ViewportTarget>);
|
||||
|
||||
/// Allocates or reuses an HDR offscreen color target when the panel size changes.
|
||||
pub fn ensure_hdr_panel_target(
|
||||
physical_size: UVec2,
|
||||
last_size: &mut Option<UVec2>,
|
||||
images: &mut Assets<Image>,
|
||||
) -> Option<Handle<Image>> {
|
||||
if *last_size == Some(physical_size) {
|
||||
return None;
|
||||
}
|
||||
*last_size = Some(physical_size);
|
||||
Some(images.add(Image::new_target_texture(
|
||||
physical_size.x,
|
||||
physical_size.y,
|
||||
TextureFormat::Rgba16Float,
|
||||
None,
|
||||
)))
|
||||
}
|
||||
|
||||
/// Standard HDR format for editor panel render targets.
|
||||
pub const PANEL_TARGET_FORMAT: TextureFormat = TextureFormat::Rgba16Float;
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Scene I/O, schema validation, and viewport render-target setup.
|
||||
|
||||
pub mod scene_io;
|
||||
pub mod scene_schema;
|
||||
pub mod scene_view;
|
||||
@@ -0,0 +1,628 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::ecs::entity::EntityHashMap;
|
||||
use bevy::ecs::system::SystemState;
|
||||
use bevy::prelude::*;
|
||||
use bevy::scene::serde::SceneDeserializer;
|
||||
use bevy::scene::DynamicScene;
|
||||
use bevy::scene::DynamicSceneBuilder;
|
||||
use bevy::window::PrimaryWindow;
|
||||
use scene::{migrate_scene_text, stamp_schema_version, strip_schema_version, validate_level_text};
|
||||
use serde::de::DeserializeSeed;
|
||||
use shared::{
|
||||
flush_level_object_hydration, infer_actor_kind, strip_hydrated_entity, validate_actor, ActorId,
|
||||
ActorKind, ActorName, ActorValidationError, ColliderDesc, EditorVisibility,
|
||||
HierarchySiblingIndex, InspectorOrder, LevelObject, LightDesc, MaterialDesc, MaterialOverride,
|
||||
ModelRef, ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance,
|
||||
PrefabRef, Primitive, RigidBodyDesc, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
|
||||
};
|
||||
|
||||
use crate::assets::{import_external_assets, EditorAssets};
|
||||
use crate::history::{clear_level_objects, snapshot_entity, EditorHistory};
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::ui::hierarchy_ops::{
|
||||
backfill_missing_editor_visibility, backfill_missing_sibling_indices,
|
||||
};
|
||||
use crate::ui::UiState;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SceneIoRequest {
|
||||
New,
|
||||
Open,
|
||||
Save,
|
||||
SaveAs,
|
||||
ImportAssets,
|
||||
ExportSelection,
|
||||
SaveSelectionAsPrefab,
|
||||
OpenRecent(usize),
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug)]
|
||||
pub struct SceneIo {
|
||||
pub active_path: Option<PathBuf>,
|
||||
pub recent_paths: Vec<PathBuf>,
|
||||
pub request: Option<SceneIoRequest>,
|
||||
pub status: String,
|
||||
pub dirty: bool,
|
||||
/// When set, the next I/O request needs unsaved-changes confirmation.
|
||||
pub pending_request: Option<SceneIoRequest>,
|
||||
}
|
||||
|
||||
impl Default for SceneIo {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
active_path: Some(PathBuf::from("assets/levels/editor_scene.scn.ron")),
|
||||
recent_paths: Vec::new(),
|
||||
request: None,
|
||||
status: "Ready".to_string(),
|
||||
dirty: false,
|
||||
pending_request: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SceneIo {
|
||||
pub fn mark_dirty(&mut self) {
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
pub fn mark_clean(&mut self) {
|
||||
self.dirty = false;
|
||||
}
|
||||
|
||||
pub fn active_path_label(&self) -> String {
|
||||
self.active_path
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|| "Unsaved scene".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct LoadedSceneRoot;
|
||||
|
||||
pub struct SceneIoPlugin;
|
||||
|
||||
impl Plugin for SceneIoPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<SceneIo>()
|
||||
.add_systems(
|
||||
Update,
|
||||
(process_scene_io_requests, update_window_title).chain(),
|
||||
)
|
||||
.add_systems(PostStartup, load_startup_scene);
|
||||
}
|
||||
}
|
||||
|
||||
fn load_startup_scene(world: &mut World) {
|
||||
let active_path = world.resource::<SceneIo>().active_path.clone();
|
||||
let default_path = PathBuf::from(
|
||||
world
|
||||
.resource::<settings::ProjectSettings>()
|
||||
.default_level
|
||||
.clone(),
|
||||
);
|
||||
let path = active_path.unwrap_or(default_path);
|
||||
|
||||
match load_level(world, &path) {
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
world.resource_mut::<SceneIo>().status = format!("Loaded {}", path.display());
|
||||
}
|
||||
Err(err) => {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("Startup scene load failed: {err}; using generated starter arena");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_scene_io_requests(world: &mut World) {
|
||||
let request = {
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
if let Some(pending) = io.pending_request.take() {
|
||||
pending
|
||||
} else {
|
||||
match io.request.take() {
|
||||
Some(req) if io.dirty && needs_dirty_confirm(&req) => {
|
||||
io.pending_request = Some(req);
|
||||
return;
|
||||
}
|
||||
Some(req) => req,
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if world.resource::<SceneIo>().dirty && needs_dirty_confirm(&request) {
|
||||
match confirm_discard_or_save() {
|
||||
DirtyConfirm::Save => {
|
||||
let save_status = save_active_or_prompt(world);
|
||||
if save_status.starts_with("Save failed") || save_status.ends_with("cancelled") {
|
||||
world.resource_mut::<SceneIo>().status = save_status;
|
||||
return;
|
||||
}
|
||||
}
|
||||
DirtyConfirm::Discard => {}
|
||||
DirtyConfirm::Cancel => {
|
||||
world.resource_mut::<SceneIo>().status = "Operation cancelled".to_string();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let status = match request {
|
||||
SceneIoRequest::New => {
|
||||
clear_loaded_scene_roots(world);
|
||||
clear_level_objects(world);
|
||||
world.resource_mut::<SceneIo>().active_path = None;
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
"Created a new empty level".to_string()
|
||||
}
|
||||
SceneIoRequest::Save => save_active_or_prompt(world),
|
||||
SceneIoRequest::SaveAs => save_with_dialog(world),
|
||||
SceneIoRequest::Open => open_with_dialog(world),
|
||||
SceneIoRequest::ImportAssets => import_with_dialog(world),
|
||||
SceneIoRequest::ExportSelection => export_selection_with_dialog(world),
|
||||
SceneIoRequest::SaveSelectionAsPrefab => save_selection_as_prefab(world),
|
||||
SceneIoRequest::OpenRecent(index) => open_recent(world, index),
|
||||
};
|
||||
|
||||
world.resource_mut::<SceneIo>().status = status;
|
||||
}
|
||||
|
||||
enum DirtyConfirm {
|
||||
Save,
|
||||
Discard,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
fn needs_dirty_confirm(request: &SceneIoRequest) -> bool {
|
||||
matches!(
|
||||
request,
|
||||
SceneIoRequest::New | SceneIoRequest::Open | SceneIoRequest::OpenRecent(_)
|
||||
)
|
||||
}
|
||||
|
||||
fn confirm_discard_or_save() -> DirtyConfirm {
|
||||
use rfd::{MessageButtons, MessageDialog, MessageLevel};
|
||||
match MessageDialog::new()
|
||||
.set_title("Unsaved Changes")
|
||||
.set_description("The scene has unsaved changes. Save before continuing?")
|
||||
.set_level(MessageLevel::Warning)
|
||||
.set_buttons(MessageButtons::YesNoCancel)
|
||||
.show()
|
||||
{
|
||||
rfd::MessageDialogResult::Yes => DirtyConfirm::Save,
|
||||
rfd::MessageDialogResult::No => DirtyConfirm::Discard,
|
||||
_ => DirtyConfirm::Cancel,
|
||||
}
|
||||
}
|
||||
|
||||
fn open_recent(world: &mut World, index: usize) -> String {
|
||||
let path = world.resource::<SceneIo>().recent_paths.get(index).cloned();
|
||||
let Some(path) = path else {
|
||||
return "Recent scene not found".to_string();
|
||||
};
|
||||
match load_level(world, &path) {
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
format!("Loading {}", path.display())
|
||||
}
|
||||
Err(err) => format!("Open failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_selection_as_prefab(world: &mut World) -> String {
|
||||
let selection: Vec<Entity> = world
|
||||
.get_resource::<UiState>()
|
||||
.map(|ui| {
|
||||
ui.selected_entities
|
||||
.iter()
|
||||
.filter(|entity| {
|
||||
world
|
||||
.get_entity(*entity)
|
||||
.is_ok_and(|e| e.contains::<LevelObject>())
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if selection.is_empty() {
|
||||
return "Select level objects to save as prefab".to_string();
|
||||
}
|
||||
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_directory("assets/prefabs")
|
||||
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
||||
.set_file_name("prefab.scn.ron")
|
||||
.save_file()
|
||||
else {
|
||||
return "Save prefab cancelled".to_string();
|
||||
};
|
||||
|
||||
match save_entities(world, &path, selection) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<EditorAssets>().refresh();
|
||||
format!(
|
||||
"Saved prefab with {count} root entity(s) to {}",
|
||||
path.display()
|
||||
)
|
||||
}
|
||||
Err(err) => format!("Save prefab failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Save helper for play-mode and other cross-module callers.
|
||||
pub fn save_active_or_prompt_world(world: &mut World) -> String {
|
||||
save_active_or_prompt(world)
|
||||
}
|
||||
|
||||
fn save_active_or_prompt(world: &mut World) -> String {
|
||||
let path = world.resource::<SceneIo>().active_path.clone();
|
||||
match path {
|
||||
Some(path) => match save_level(world, &path) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
format!("Saved {count} level entities to {}", path.display())
|
||||
}
|
||||
Err(err) => format!("Save failed: {err}"),
|
||||
},
|
||||
None => save_with_dialog(world),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_with_dialog(world: &mut World) -> String {
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_directory("assets/levels")
|
||||
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
||||
.set_file_name("editor_scene.scn.ron")
|
||||
.save_file()
|
||||
else {
|
||||
return "Save cancelled".to_string();
|
||||
};
|
||||
|
||||
match save_level(world, &path) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
format!("Saved {count} level entities to {}", path.display())
|
||||
}
|
||||
Err(err) => format!("Save failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_with_dialog(world: &mut World) -> String {
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_directory("assets/levels")
|
||||
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
||||
.pick_file()
|
||||
else {
|
||||
return "Open cancelled".to_string();
|
||||
};
|
||||
|
||||
match load_level(world, &path) {
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
format!("Loading {}", path.display())
|
||||
}
|
||||
Err(err) => format!("Open failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn import_with_dialog(world: &mut World) -> String {
|
||||
let Some(paths) = rfd::FileDialog::new()
|
||||
.add_filter(
|
||||
"Editor assets",
|
||||
&["gltf", "glb", "fbx", "png", "jpg", "jpeg", "webp", "ktx2"],
|
||||
)
|
||||
.pick_files()
|
||||
else {
|
||||
return "Import cancelled".to_string();
|
||||
};
|
||||
|
||||
match import_external_assets(&paths) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<EditorAssets>().refresh();
|
||||
format!("Imported {count} asset(s)")
|
||||
}
|
||||
Err(err) => format!("Import failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn export_selection_with_dialog(world: &mut World) -> String {
|
||||
let Some(entity) = world.resource::<SelectedEntity>().0 else {
|
||||
return "Nothing selected to export".to_string();
|
||||
};
|
||||
if snapshot_entity(world, entity).is_none() {
|
||||
return "Selected entity is not an authored level object".to_string();
|
||||
}
|
||||
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_directory("assets/levels")
|
||||
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
||||
.set_file_name("selection.scn.ron")
|
||||
.save_file()
|
||||
else {
|
||||
return "Export cancelled".to_string();
|
||||
};
|
||||
|
||||
match save_entities(world, &path, vec![entity]) {
|
||||
Ok(count) => format!("Exported {count} selected entity to {}", path.display()),
|
||||
Err(err) => format!("Export failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_loaded_scene_roots(world: &mut World) {
|
||||
let mut query = world.query_filtered::<Entity, With<LoadedSceneRoot>>();
|
||||
let entities: Vec<Entity> = query.iter(world).collect();
|
||||
for entity in entities {
|
||||
if let Ok(entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save_level(world: &mut World, path: &Path) -> Result<usize, String> {
|
||||
let mut query = world
|
||||
.try_query_filtered::<Entity, With<LevelObject>>()
|
||||
.ok_or_else(|| "could not create LevelObject query".to_string())?;
|
||||
let entities: Vec<Entity> = query.iter(world).collect();
|
||||
save_entities(world, path, entities)
|
||||
}
|
||||
|
||||
fn format_actor_validation(err: ActorValidationError) -> String {
|
||||
match err {
|
||||
ActorValidationError::MissingActorKind => {
|
||||
"Save failed: level object missing ActorKind (re-open scene to migrate)".into()
|
||||
}
|
||||
ActorValidationError::MissingTransform => {
|
||||
"Save failed: level object missing Transform".into()
|
||||
}
|
||||
ActorValidationError::StaticMeshMissingPrimitive => {
|
||||
"Save failed: StaticMesh actor requires Primitive or StaticMeshRenderer with a mesh slot"
|
||||
.into()
|
||||
}
|
||||
ActorValidationError::StaticMeshHasLight => {
|
||||
"Save failed: StaticMesh actor cannot have LightDesc".into()
|
||||
}
|
||||
ActorValidationError::StaticMeshHasModelRef => {
|
||||
"Save failed: StaticMesh actor cannot have ModelRef".into()
|
||||
}
|
||||
ActorValidationError::ImportedModelMissingModelRef => {
|
||||
"Save failed: ImportedModel actor requires ModelRef".into()
|
||||
}
|
||||
ActorValidationError::ImportedModelHasPrimitive => {
|
||||
"Save failed: ImportedModel actor cannot have Primitive".into()
|
||||
}
|
||||
ActorValidationError::ImportedModelHasStaticMeshRenderer => {
|
||||
"Save failed: ImportedModel actor cannot have StaticMeshRenderer".into()
|
||||
}
|
||||
ActorValidationError::LightMissingLightDesc => {
|
||||
"Save failed: Light actor requires LightDesc".into()
|
||||
}
|
||||
ActorValidationError::LightHasPrimitive => {
|
||||
"Save failed: Light actor cannot have Primitive".into()
|
||||
}
|
||||
ActorValidationError::LightHasModelRef => {
|
||||
"Save failed: Light actor cannot have ModelRef".into()
|
||||
}
|
||||
ActorValidationError::LightHasStaticMeshRenderer => {
|
||||
"Save failed: Light actor cannot have StaticMeshRenderer".into()
|
||||
}
|
||||
ActorValidationError::PostProcessVolumeMissingDesc => {
|
||||
"Save failed: PostProcessVolume actor requires PostProcessVolumeDesc".into()
|
||||
}
|
||||
ActorValidationError::PostProcessVolumeInvalidHalfExtents => {
|
||||
"Save failed: post-process volume half_extents must be positive".into()
|
||||
}
|
||||
ActorValidationError::PostProcessVolumeInvalidBlendDistance => {
|
||||
"Save failed: post-process volume blend_distance must be non-negative".into()
|
||||
}
|
||||
ActorValidationError::PostProcessVolumeInvalidOverrideScalar => {
|
||||
"Save failed: post-process volume override contains invalid scalar".into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save_entities(world: &mut World, path: &Path, entities: Vec<Entity>) -> Result<usize, String> {
|
||||
let count = entities.len();
|
||||
|
||||
for entity in &entities {
|
||||
let entity_ref = world.entity(*entity);
|
||||
if let Err(err) = validate_actor(entity_ref) {
|
||||
return Err(format_actor_validation(err));
|
||||
}
|
||||
}
|
||||
|
||||
for entity in &entities {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
|
||||
strip_hydrated_entity(&mut entity_mut);
|
||||
}
|
||||
}
|
||||
|
||||
let scene = DynamicSceneBuilder::from_world(world)
|
||||
.deny_all()
|
||||
.allow_component::<Name>()
|
||||
.allow_component::<Transform>()
|
||||
.allow_component::<ChildOf>()
|
||||
.allow_component::<LevelObject>()
|
||||
.allow_component::<ActorId>()
|
||||
.allow_component::<ActorName>()
|
||||
.allow_component::<ActorKind>()
|
||||
.allow_component::<InspectorOrder>()
|
||||
.allow_component::<Primitive>()
|
||||
.allow_component::<StaticMeshRenderer>()
|
||||
.allow_component::<MaterialDesc>()
|
||||
.allow_component::<MaterialOverride>()
|
||||
.allow_component::<RigidBodyDesc>()
|
||||
.allow_component::<ColliderDesc>()
|
||||
.allow_component::<PhysicsBody>()
|
||||
.allow_component::<LightDesc>()
|
||||
.allow_component::<PlayerSpawn>()
|
||||
.allow_component::<ModelRef>()
|
||||
.allow_component::<PrefabRef>()
|
||||
.allow_component::<PrefabInstance>()
|
||||
.allow_component::<WeaponSpawn>()
|
||||
.allow_component::<TriggerVolume>()
|
||||
.allow_component::<PostProcessVolumeDesc>()
|
||||
.allow_component::<TeamSpawn>()
|
||||
.allow_component::<ObjectiveMarker>()
|
||||
.allow_component::<HierarchySiblingIndex>()
|
||||
.allow_component::<EditorVisibility>()
|
||||
.extract_entities(entities.into_iter())
|
||||
.remove_empty_entities()
|
||||
.build();
|
||||
|
||||
let ron = {
|
||||
let registry = world.resource::<AppTypeRegistry>().read();
|
||||
scene
|
||||
.serialize(®istry)
|
||||
.map_err(|err| format!("could not serialize scene: {err}"))?
|
||||
};
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|err| format!("could not create {}: {err}", parent.display()))?;
|
||||
}
|
||||
let stamped = stamp_schema_version(&ron)?;
|
||||
std::fs::write(path, stamped)
|
||||
.map_err(|err| format!("could not write {}: {err}", path.display()))?;
|
||||
finalize_scene_load(world);
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn load_level(world: &mut World, path: &Path) -> Result<(), String> {
|
||||
if !path.exists() {
|
||||
return Err(format!("{} does not exist yet", path.display()));
|
||||
}
|
||||
|
||||
let text = std::fs::read_to_string(path)
|
||||
.map_err(|err| format!("could not read {}: {err}", path.display()))?;
|
||||
validate_level_text(&text)?;
|
||||
let normalized = migrate_scene_text(&text)?;
|
||||
let bevy_ron = strip_schema_version(&normalized)?;
|
||||
|
||||
clear_loaded_scene_roots(world);
|
||||
clear_level_objects(world);
|
||||
|
||||
let dynamic_scene: DynamicScene = {
|
||||
let registry = world.resource::<AppTypeRegistry>().read();
|
||||
let scene_deserializer = SceneDeserializer {
|
||||
type_registry: ®istry,
|
||||
};
|
||||
let mut deserializer =
|
||||
ron::de::Deserializer::from_str(&bevy_ron).map_err(|err| err.to_string())?;
|
||||
scene_deserializer
|
||||
.deserialize(&mut deserializer)
|
||||
.map_err(|err| format!("could not deserialize scene: {err}"))?
|
||||
};
|
||||
|
||||
dynamic_scene
|
||||
.write_to_world(world, &mut EntityHashMap::default())
|
||||
.map_err(|err| format!("could not spawn scene: {err}"))?;
|
||||
|
||||
backfill_missing_actor_kinds(world);
|
||||
backfill_missing_sibling_indices(world);
|
||||
backfill_missing_editor_visibility(world);
|
||||
finalize_scene_load(world);
|
||||
|
||||
if world.contains_resource::<crate::scene_schema::SceneSchemaState>() {
|
||||
world
|
||||
.resource_mut::<crate::scene_schema::SceneSchemaState>()
|
||||
.last_validated = scene::CURRENT_SCENE_SCHEMA_VERSION;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finalize_scene_load(world: &mut World) {
|
||||
flush_level_object_hydration(world);
|
||||
|
||||
let rendering = world
|
||||
.resource::<settings::ProjectSettings>()
|
||||
.rendering
|
||||
.clone();
|
||||
world.insert_resource(GlobalAmbientLight {
|
||||
color: Color::srgb(
|
||||
rendering.ambient_color[0],
|
||||
rendering.ambient_color[1],
|
||||
rendering.ambient_color[2],
|
||||
),
|
||||
brightness: rendering.ambient_brightness,
|
||||
..default()
|
||||
});
|
||||
|
||||
let mut state: SystemState<(
|
||||
Res<settings::ProjectSettings>,
|
||||
Query<(&LightDesc, Option<&InspectorOrder>), With<LevelObject>>,
|
||||
Query<(&mut DirectionalLight, &mut Visibility), With<shared::ProjectSun>>,
|
||||
)> = SystemState::new(world);
|
||||
|
||||
{
|
||||
let (settings, scene_suns, project_suns) = state.get_mut(world);
|
||||
game_hot::sync_project_sun_from_settings(settings, scene_suns, project_suns);
|
||||
}
|
||||
state.apply(world);
|
||||
}
|
||||
|
||||
fn backfill_missing_actor_kinds(world: &mut World) {
|
||||
let mut query = world.query_filtered::<Entity, With<LevelObject>>();
|
||||
let entities: Vec<Entity> = query.iter(world).collect();
|
||||
for entity in entities {
|
||||
let Ok(entity_ref) = world.get_entity(entity) else {
|
||||
continue;
|
||||
};
|
||||
if entity_ref.get::<ActorKind>().is_some() {
|
||||
continue;
|
||||
}
|
||||
if let Some(kind) = infer_actor_kind(entity_ref) {
|
||||
world.entity_mut(entity).insert(kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_path(world: &mut World, path: PathBuf) {
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
io.recent_paths.retain(|recent| recent != &path);
|
||||
io.recent_paths.insert(0, path.clone());
|
||||
io.recent_paths.truncate(8);
|
||||
|
||||
if world.contains_resource::<crate::project_io::UserPreferences>() {
|
||||
let path_label = path.display().to_string();
|
||||
let mut prefs = world.resource_mut::<crate::project_io::UserPreferences>();
|
||||
crate::project_io::push_recent(&mut prefs.recent_levels, path_label, 8);
|
||||
if let Err(error) = crate::project_io::write_user_preferences(&prefs) {
|
||||
warn!("Failed to save editor preferences: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_window_title(
|
||||
io: Res<SceneIo>,
|
||||
workspace: Res<crate::project_io::ProjectWorkspace>,
|
||||
settings: Res<settings::ProjectSettings>,
|
||||
settings_io: Res<settings::ProjectSettingsIo>,
|
||||
mut window: Single<&mut Window, With<PrimaryWindow>>,
|
||||
) {
|
||||
if !io.is_changed()
|
||||
&& !workspace.is_changed()
|
||||
&& !settings.is_changed()
|
||||
&& !settings_io.is_changed()
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
window.title = crate::project_io::window_title(&io, &workspace, &settings);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Scene format versioning plugin (editor); logic lives in the `scene` crate.
|
||||
|
||||
use bevy::prelude::*;
|
||||
pub use scene::{
|
||||
migrate_scene_text, stamp_schema_version, strip_schema_version, validate_level_file,
|
||||
validate_level_text, SceneSchemaHeader, CURRENT_SCENE_SCHEMA_VERSION,
|
||||
};
|
||||
|
||||
pub struct SceneSchemaPlugin;
|
||||
|
||||
impl Plugin for SceneSchemaPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<SceneSchemaState>();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct SceneSchemaState {
|
||||
pub last_validated: u32,
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Primary editor viewport render-to-texture target and editor camera binding.
|
||||
|
||||
use bevy::camera::RenderTarget;
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{PrimaryWindow, WindowRef};
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::render_target::{ensure_hdr_panel_target, ViewportRenderTarget, ViewportTarget};
|
||||
use crate::state::{EditorMode, PlayPossession};
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::panel_physical_size;
|
||||
|
||||
pub struct SceneViewPlugin;
|
||||
|
||||
impl Plugin for SceneViewPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<ViewportRenderTarget>().add_systems(
|
||||
PostUpdate,
|
||||
(
|
||||
ensure_viewport_render_target,
|
||||
sync_editor_camera_viewport_target,
|
||||
)
|
||||
.chain()
|
||||
.after(crate::ui::show_ui_system),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_viewport_render_target(
|
||||
ui_state: Res<UiState>,
|
||||
window: Single<&Window, With<PrimaryWindow>>,
|
||||
mut images: ResMut<Assets<Image>>,
|
||||
mut target: ResMut<ViewportRenderTarget>,
|
||||
mut last_size: Local<Option<UVec2>>,
|
||||
) {
|
||||
let Some(physical_size) = panel_physical_size(&window, ui_state.viewport_rect) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(handle) = ensure_hdr_panel_target(physical_size, &mut last_size, &mut images) {
|
||||
target.0 = Some(ViewportTarget { image: handle });
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sync_editor_camera_viewport_target(
|
||||
mode: Res<State<EditorMode>>,
|
||||
possession: Res<PlayPossession>,
|
||||
target: Res<ViewportRenderTarget>,
|
||||
mut cameras: Query<(Entity, &mut Camera), With<EditorCamera>>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
let scene_active = matches!(*mode.get(), EditorMode::Editing)
|
||||
|| (*mode.get() == EditorMode::Playing && *possession == PlayPossession::Ejected);
|
||||
|
||||
for (entity, mut camera) in &mut cameras {
|
||||
if scene_active {
|
||||
let Some(viewport_target) = target.0.as_ref() else {
|
||||
camera.viewport = None;
|
||||
camera.is_active = false;
|
||||
continue;
|
||||
};
|
||||
// Render the full offscreen target. A panel-sized
|
||||
// viewport on `RenderTarget::Image` can exceed the texture for a frame after
|
||||
// resize (wgpu: scissor rect not contained in render target).
|
||||
camera.viewport = None;
|
||||
camera.is_active = true;
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(RenderTarget::Image(viewport_target.image.clone().into()));
|
||||
} else {
|
||||
camera.viewport = None;
|
||||
camera.is_active = false;
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(RenderTarget::Window(WindowRef::Primary));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Actor-centric inspector (authoring components only).
|
||||
|
||||
mod transform;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
use shared::{ActorId, ActorKind, ActorName, LevelObject};
|
||||
|
||||
use crate::ext::extensibility::ActorInspectorSectionRegistry;
|
||||
use crate::ui::inspector;
|
||||
use crate::ui::theme::{panel_heading, BORDER, TEXT_DIM, WIDGET_BG};
|
||||
use crate::ui::widgets::phosphor_icon;
|
||||
|
||||
use transform::transform_inspector_ui;
|
||||
|
||||
const COMPACT_ACTOR_HEADER_WIDTH: f32 = 360.0;
|
||||
|
||||
pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let Some(entity_ref) = world.get_entity(entity).ok() else {
|
||||
ui.label("Entity no longer exists.");
|
||||
return;
|
||||
};
|
||||
if !entity_ref.contains::<LevelObject>() {
|
||||
ui.label("Not a level object.");
|
||||
return;
|
||||
}
|
||||
|
||||
let kind = entity_ref
|
||||
.get::<ActorKind>()
|
||||
.copied()
|
||||
.unwrap_or(ActorKind::Empty);
|
||||
|
||||
egui::Frame::new()
|
||||
.fill(WIDGET_BG)
|
||||
.stroke(egui::Stroke::new(1.0, BORDER))
|
||||
.corner_radius(egui::CornerRadius::same(4))
|
||||
.inner_margin(egui::Margin::symmetric(8, 8))
|
||||
.show(ui, |ui| {
|
||||
let compact = ui.available_width() < COMPACT_ACTOR_HEADER_WIDTH;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(phosphor_icon(actor_icon(kind), 28.0).color(TEXT_DIM));
|
||||
let text_max_width = (ui.available_width() - 28.0).max(96.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_max_width(text_max_width);
|
||||
let name = entity_ref
|
||||
.get::<ActorName>()
|
||||
.map(|name| name.0.as_str())
|
||||
.or_else(|| entity_ref.get::<Name>().map(|name| name.as_str()))
|
||||
.unwrap_or("Unnamed");
|
||||
let actor_id = entity_ref
|
||||
.get::<ActorId>()
|
||||
.map(|id| id.0.as_str())
|
||||
.filter(|id| !id.trim().is_empty())
|
||||
.unwrap_or("unpersisted");
|
||||
ui.add(egui::Label::new(panel_heading(name)).truncate());
|
||||
if compact {
|
||||
ui.small(
|
||||
egui::RichText::new(format!("{kind:?} | Actor {actor_id}"))
|
||||
.color(TEXT_DIM),
|
||||
);
|
||||
ui.small(
|
||||
egui::RichText::new(format!("Runtime {entity:?}")).color(TEXT_DIM),
|
||||
);
|
||||
} else {
|
||||
ui.small(
|
||||
egui::RichText::new(format!(
|
||||
"{kind:?} | Actor {actor_id} | Runtime {entity:?}"
|
||||
))
|
||||
.color(TEXT_DIM),
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(phosphor_icon(icons::DOTS_THREE_VERTICAL, 16.0).color(TEXT_DIM));
|
||||
ui.label(phosphor_icon(icons::LOCK_SIMPLE, 16.0).color(TEXT_DIM));
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
|
||||
let footer_reserve = 52.0;
|
||||
let body_height = (ui.available_height() - footer_reserve).max(1.0);
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(ui.available_width(), body_height),
|
||||
egui::Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
transform_inspector_ui(world, ui, entity);
|
||||
|
||||
match kind {
|
||||
ActorKind::StaticMesh
|
||||
| ActorKind::ImportedModel
|
||||
| ActorKind::Light
|
||||
| ActorKind::Empty
|
||||
| ActorKind::PrefabAnchor
|
||||
| ActorKind::PlayerSpawn
|
||||
| ActorKind::WeaponSpawn
|
||||
| ActorKind::TriggerVolume
|
||||
| ActorKind::PostProcessVolume
|
||||
| ActorKind::TeamSpawn
|
||||
| ActorKind::Objective => {
|
||||
inspector::authoring_inspector_ui(world, ui, entity);
|
||||
}
|
||||
}
|
||||
|
||||
world.resource_scope(|world, registry: Mut<ActorInspectorSectionRegistry>| {
|
||||
registry.draw_sections(world, ui, entity);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
inspector::add_component_footer(world, ui, entity);
|
||||
}
|
||||
|
||||
fn actor_icon(kind: ActorKind) -> egui_phosphor_icons::Icon {
|
||||
match kind {
|
||||
ActorKind::StaticMesh | ActorKind::ImportedModel => icons::CUBE,
|
||||
ActorKind::Light => icons::LIGHTBULB,
|
||||
ActorKind::PrefabAnchor => icons::PACKAGE,
|
||||
ActorKind::PlayerSpawn => icons::PERSON_SIMPLE_RUN,
|
||||
ActorKind::WeaponSpawn => icons::CROSSHAIR,
|
||||
ActorKind::TriggerVolume => icons::SELECTION,
|
||||
ActorKind::PostProcessVolume => icons::APERTURE,
|
||||
ActorKind::TeamSpawn | ActorKind::Objective => icons::FLAG,
|
||||
ActorKind::Empty => icons::CIRCLE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_multi_actor_inspector(world: &mut World, ui: &mut egui::Ui, entities: &[Entity]) {
|
||||
ui.heading(format!("{} objects selected", entities.len()));
|
||||
ui.label("Multi-edit: use the viewport gizmo for shared transform.");
|
||||
if entities.len() == 1 {
|
||||
draw_actor_inspector(world, ui, entities[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Transform section (authoring) for the actor inspector.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::history::set_transform_with_history;
|
||||
use crate::ui::inspector::{
|
||||
apply_component_card_response, component_card, component_card_context, ComponentCardOptions,
|
||||
COMPONENT_TRANSFORM,
|
||||
};
|
||||
use crate::ui::theme::TEXT_DIM;
|
||||
|
||||
const WIDE_TRANSFORM_ROW_WIDTH: f32 = 360.0;
|
||||
const TRANSFORM_LABEL_WIDTH: f32 = 124.0;
|
||||
const AXIS_FIELD_WIDTH: f32 = 76.0;
|
||||
|
||||
pub fn transform_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let Some(mut transform) = world.get::<Transform>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let old = transform;
|
||||
let mut changed = false;
|
||||
|
||||
let card = component_card_context(
|
||||
world,
|
||||
entity,
|
||||
ComponentCardOptions::fixed(COMPONENT_TRANSFORM, "Transform", icons::ARROWS_OUT_CARDINAL),
|
||||
);
|
||||
let card_response = component_card(ui, &card, |ui| {
|
||||
if transform_row(ui, "Position", &mut transform.translation, 0.1) {
|
||||
changed = true;
|
||||
}
|
||||
|
||||
let (yaw, pitch, roll) = transform.rotation.to_euler(EulerRot::YXZ);
|
||||
let mut rotation_deg = Vec3::new(pitch.to_degrees(), yaw.to_degrees(), roll.to_degrees());
|
||||
if transform_row(ui, "Rotation (degrees)", &mut rotation_deg, 0.5) {
|
||||
transform.rotation = Quat::from_euler(
|
||||
EulerRot::YXZ,
|
||||
rotation_deg.y.to_radians(),
|
||||
rotation_deg.x.to_radians(),
|
||||
rotation_deg.z.to_radians(),
|
||||
);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if transform_row(ui, "Scale", &mut transform.scale, 0.05) {
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
let reset = card_response.reset;
|
||||
apply_component_card_response(world, entity, card_response);
|
||||
|
||||
if reset {
|
||||
set_transform_with_history(world, entity, old, Transform::default());
|
||||
} else if changed {
|
||||
set_transform_with_history(world, entity, old, transform);
|
||||
}
|
||||
}
|
||||
|
||||
fn transform_row(ui: &mut egui::Ui, label: &str, value: &mut Vec3, speed: f64) -> bool {
|
||||
let mut changed = false;
|
||||
if ui.available_width() < WIDE_TRANSFORM_ROW_WIDTH {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(label);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
changed |= axis_drag(ui, "X", &mut value.x, speed);
|
||||
changed |= axis_drag(ui, "Y", &mut value.y, speed);
|
||||
changed |= axis_drag(ui, "Z", &mut value.z, speed);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_sized(
|
||||
[TRANSFORM_LABEL_WIDTH.min(ui.available_width()), 20.0],
|
||||
egui::Label::new(label),
|
||||
);
|
||||
changed |= axis_drag(ui, "X", &mut value.x, speed);
|
||||
changed |= axis_drag(ui, "Y", &mut value.y, speed);
|
||||
changed |= axis_drag(ui, "Z", &mut value.z, speed);
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn axis_drag(ui: &mut egui::Ui, axis: &str, value: &mut f32, speed: f64) -> bool {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(axis).color(axis_color(axis)).strong());
|
||||
ui.add_sized(
|
||||
[AXIS_FIELD_WIDTH.min(ui.available_width().max(44.0)), 20.0],
|
||||
egui::DragValue::new(value)
|
||||
.speed(speed)
|
||||
.max_decimals(3)
|
||||
.min_decimals(1),
|
||||
)
|
||||
.changed()
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
fn axis_color(axis: &str) -> egui::Color32 {
|
||||
match axis {
|
||||
"X" => egui::Color32::from_rgb(229, 82, 73),
|
||||
"Y" => egui::Color32::from_rgb(103, 190, 92),
|
||||
"Z" => egui::Color32::from_rgb(88, 132, 241),
|
||||
_ => TEXT_DIM,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
mod panel;
|
||||
mod state;
|
||||
|
||||
pub use panel::*;
|
||||
pub use state::AssetBrowserUiState;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,62 @@
|
||||
//! Asset browser UI state and view enums.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::assets::{ASSETS_ROOT, BUILTINS_FOLDER};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AssetBrowserView {
|
||||
Grid,
|
||||
List,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AssetSort {
|
||||
Name,
|
||||
Kind,
|
||||
Modified,
|
||||
Size,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AssetKindFilter {
|
||||
All,
|
||||
Model,
|
||||
Texture,
|
||||
Material,
|
||||
Level,
|
||||
Prefab,
|
||||
Builtin,
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug)]
|
||||
pub struct AssetBrowserUiState {
|
||||
pub(crate) search: String,
|
||||
pub(crate) view: AssetBrowserView,
|
||||
pub(crate) sort: AssetSort,
|
||||
pub(crate) kind_filter: AssetKindFilter,
|
||||
pub(crate) thumbnail_size: f32,
|
||||
pub(crate) recursive: bool,
|
||||
pub(crate) show_details: bool,
|
||||
pub(crate) expanded_folders: HashSet<String>,
|
||||
}
|
||||
|
||||
impl Default for AssetBrowserUiState {
|
||||
fn default() -> Self {
|
||||
let mut expanded_folders = HashSet::new();
|
||||
expanded_folders.insert(ASSETS_ROOT.to_string());
|
||||
expanded_folders.insert(BUILTINS_FOLDER.to_string());
|
||||
Self {
|
||||
search: String::new(),
|
||||
view: AssetBrowserView::Grid,
|
||||
sort: AssetSort::Name,
|
||||
kind_filter: AssetKindFilter::All,
|
||||
thumbnail_size: 72.0,
|
||||
recursive: false,
|
||||
show_details: true,
|
||||
expanded_folders,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Editor-visible component registry for actor inspector palettes.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EditorComponentCategory {
|
||||
Rendering,
|
||||
Physics,
|
||||
Gameplay,
|
||||
Editor,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EditorComponentDescriptor {
|
||||
pub type_name: &'static str,
|
||||
pub display_name: &'static str,
|
||||
pub category: EditorComponentCategory,
|
||||
pub addable: bool,
|
||||
pub removable: bool,
|
||||
pub reorderable: bool,
|
||||
pub icon: &'static str,
|
||||
pub search_terms: &'static [&'static str],
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct EditorComponentRegistry {
|
||||
pub descriptors: Vec<EditorComponentDescriptor>,
|
||||
}
|
||||
|
||||
impl Default for EditorComponentRegistry {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
descriptors: vec![
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::StaticMeshRenderer",
|
||||
display_name: "Static Mesh Renderer",
|
||||
category: EditorComponentCategory::Rendering,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::CUBE.as_str(),
|
||||
search_terms: &["mesh", "renderer", "rendering", "model"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::MaterialDesc",
|
||||
display_name: "Authoring Material",
|
||||
category: EditorComponentCategory::Rendering,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::PALETTE.as_str(),
|
||||
search_terms: &["material", "shader", "texture"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::RigidBodyDesc",
|
||||
display_name: "Rigid Body",
|
||||
category: EditorComponentCategory::Physics,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::SPHERE.as_str(),
|
||||
search_terms: &["body", "physics", "rigidbody"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::ColliderDesc",
|
||||
display_name: "Collider",
|
||||
category: EditorComponentCategory::Physics,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::SELECTION.as_str(),
|
||||
search_terms: &["collision", "trigger", "physics"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::LightDesc",
|
||||
display_name: "Light",
|
||||
category: EditorComponentCategory::Rendering,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::LIGHTBULB.as_str(),
|
||||
search_terms: &["light", "lamp", "illumination"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::Primitive",
|
||||
display_name: "Primitive",
|
||||
category: EditorComponentCategory::Rendering,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::CUBE.as_str(),
|
||||
search_terms: &["box", "sphere", "ramp", "primitive"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::PlayerSpawn",
|
||||
display_name: "Player Spawn",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::PERSON_SIMPLE_RUN.as_str(),
|
||||
search_terms: &["player", "spawn", "start"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::WeaponSpawn",
|
||||
display_name: "Weapon Spawn",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::CROSSHAIR.as_str(),
|
||||
search_terms: &["weapon", "spawn"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::TriggerVolume",
|
||||
display_name: "Trigger Volume",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::SELECTION.as_str(),
|
||||
search_terms: &["trigger", "volume", "event"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::TeamSpawn",
|
||||
display_name: "Team Spawn",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::FLAG.as_str(),
|
||||
search_terms: &["team", "spawn"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::ObjectiveMarker",
|
||||
display_name: "Objective Marker",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::FLAG.as_str(),
|
||||
search_terms: &["objective", "marker", "gameplay"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::InspectorOrder",
|
||||
display_name: "Inspector Order",
|
||||
category: EditorComponentCategory::Editor,
|
||||
addable: false,
|
||||
removable: false,
|
||||
reorderable: false,
|
||||
icon: icons::LIST_BULLETS.as_str(),
|
||||
search_terms: &["editor", "order"],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Detailed diagnostics (relocated from Status dock tab).
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use shared::LevelObject;
|
||||
|
||||
use crate::assets::EditorAssets;
|
||||
use crate::history::EditorHistory;
|
||||
use crate::project_io::ProjectWorkspace;
|
||||
use crate::scene_io::SceneIo;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct DiagnosticsPanel {
|
||||
pub open: bool,
|
||||
}
|
||||
|
||||
pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
|
||||
let scene_io = world.resource::<SceneIo>();
|
||||
let dirty = if scene_io.dirty { " (dirty)" } else { "" };
|
||||
ui.label(format!("Scene: {}{dirty}", scene_io.active_path_label()));
|
||||
ui.label(format!("Status: {}", scene_io.status));
|
||||
ui.label(format!(
|
||||
"History: {}",
|
||||
world.resource::<EditorHistory>().status
|
||||
));
|
||||
ui.label(format!(
|
||||
"Assets: {}",
|
||||
world.resource::<EditorAssets>().status
|
||||
));
|
||||
|
||||
let workspace = world.resource::<ProjectWorkspace>();
|
||||
ui.label(format!("Project root: {}", workspace.root));
|
||||
ui.label(format!(
|
||||
"Project settings: {}{}",
|
||||
workspace.settings_path,
|
||||
if workspace.settings_dirty {
|
||||
" (dirty)"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
));
|
||||
if workspace.layout_dirty {
|
||||
ui.small("Dock layout modified (unsaved)");
|
||||
}
|
||||
|
||||
let mut level_query = world.query_filtered::<Entity, With<LevelObject>>();
|
||||
let count = level_query.iter(world).count();
|
||||
ui.label(format!("Level objects: {count}"));
|
||||
|
||||
ui.separator();
|
||||
ui.small("Native Bevy scenes are saved to assets/levels/*.scn.ron");
|
||||
ui.small("BRP is enabled on the editor for external tooling.");
|
||||
}
|
||||
|
||||
pub fn diagnostics_window(world: &mut World, ctx: &egui::Context, open: &mut bool) {
|
||||
if !*open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Diagnostics")
|
||||
.open(open)
|
||||
.default_width(420.0)
|
||||
.show(ctx, |ui| {
|
||||
diagnostics_ui(world, ui);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Dock tab open/focus helpers and default panel node placement.
|
||||
|
||||
use egui_dock::{DockState, Node, NodeIndex, SurfaceIndex, TabIndex, Tree};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::EditorTab;
|
||||
|
||||
/// Preferred leaf nodes for re-opening closed panels (updated when layout is built or loaded).
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
pub struct PanelNodes {
|
||||
pub main_view: usize,
|
||||
pub hierarchy: usize,
|
||||
pub inspector: usize,
|
||||
pub bottom: usize,
|
||||
}
|
||||
|
||||
impl PanelNodes {
|
||||
pub fn main_view(&self) -> NodeIndex {
|
||||
NodeIndex::from(self.main_view)
|
||||
}
|
||||
|
||||
pub fn hierarchy(&self) -> NodeIndex {
|
||||
NodeIndex::from(self.hierarchy)
|
||||
}
|
||||
|
||||
pub fn inspector(&self) -> NodeIndex {
|
||||
NodeIndex::from(self.inspector)
|
||||
}
|
||||
|
||||
pub fn bottom(&self) -> NodeIndex {
|
||||
NodeIndex::from(self.bottom)
|
||||
}
|
||||
|
||||
pub fn preferred_node(&self, tab: &EditorTab) -> NodeIndex {
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => self.main_view(),
|
||||
EditorTab::Hierarchy => self.hierarchy(),
|
||||
EditorTab::Inspector => self.inspector(),
|
||||
EditorTab::AssetBrowser | EditorTab::Toolbar => self.bottom(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan the main surface for open tabs and refresh node indices (handles user drag/split).
|
||||
pub fn discover(dock: &DockState<EditorTab>, fallback: Self) -> Self {
|
||||
let mut nodes = fallback;
|
||||
for ((surface, node_idx), tab) in dock.iter_all_tabs() {
|
||||
if surface != SurfaceIndex::main() {
|
||||
continue;
|
||||
}
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => nodes.main_view = node_idx.0,
|
||||
EditorTab::Hierarchy => nodes.hierarchy = node_idx.0,
|
||||
EditorTab::Inspector => nodes.inspector = node_idx.0,
|
||||
EditorTab::AssetBrowser | EditorTab::Toolbar => nodes.bottom = node_idx.0,
|
||||
}
|
||||
}
|
||||
nodes
|
||||
}
|
||||
}
|
||||
|
||||
pub const PANEL_TABS: [EditorTab; 4] = [
|
||||
EditorTab::Viewport,
|
||||
EditorTab::Hierarchy,
|
||||
EditorTab::Inspector,
|
||||
EditorTab::AssetBrowser,
|
||||
];
|
||||
|
||||
pub fn tab_label(tab: &EditorTab) -> &'static str {
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => "Viewport",
|
||||
EditorTab::Hierarchy => "Hierarchy",
|
||||
EditorTab::Inspector => "Inspector",
|
||||
EditorTab::AssetBrowser => "Asset Browser",
|
||||
EditorTab::Toolbar => "Toolbar (legacy)",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tab_is_open(dock: &DockState<EditorTab>, tab: &EditorTab) -> bool {
|
||||
dock.find_main_surface_tab(tab).is_some()
|
||||
}
|
||||
|
||||
/// Opens `tab` on the main surface if missing, then focuses it.
|
||||
pub fn open_and_focus_tab(
|
||||
dock: &mut DockState<EditorTab>,
|
||||
tab: EditorTab,
|
||||
panels: &PanelNodes,
|
||||
) -> (NodeIndex, TabIndex) {
|
||||
let (node, tab_idx) = if let Some(loc) = dock.find_main_surface_tab(&tab) {
|
||||
loc
|
||||
} else {
|
||||
let tree = dock.main_surface_mut();
|
||||
let node = panels.preferred_node(&tab);
|
||||
let tab_idx = push_tab_to_node(tree, node, tab);
|
||||
(node, tab_idx)
|
||||
};
|
||||
dock.set_active_tab((SurfaceIndex::main(), node, tab_idx));
|
||||
dock.set_focused_node_and_surface((SurfaceIndex::main(), node));
|
||||
(node, tab_idx)
|
||||
}
|
||||
|
||||
pub fn ensure_viewport_for_play(dock: &mut DockState<EditorTab>, panels: &PanelNodes) {
|
||||
open_and_focus_tab(dock, EditorTab::Viewport, panels);
|
||||
}
|
||||
|
||||
/// Migrates old saved layouts by replacing/removing legacy Game View tabs.
|
||||
pub fn normalize_unified_viewport_tabs(dock: &mut DockState<EditorTab>) {
|
||||
let has_viewport = dock
|
||||
.iter_all_tabs()
|
||||
.any(|(_, tab)| matches!(tab, EditorTab::Viewport));
|
||||
|
||||
if !has_viewport {
|
||||
if let Some((_, tab)) = dock
|
||||
.iter_all_tabs_mut()
|
||||
.find(|(_, tab)| matches!(tab, EditorTab::GameView))
|
||||
{
|
||||
*tab = EditorTab::Viewport;
|
||||
}
|
||||
}
|
||||
|
||||
let mut seen_viewport = false;
|
||||
dock.retain_tabs(|tab| match tab {
|
||||
EditorTab::GameView => false,
|
||||
EditorTab::Viewport => {
|
||||
if seen_viewport {
|
||||
false
|
||||
} else {
|
||||
seen_viewport = true;
|
||||
true
|
||||
}
|
||||
}
|
||||
_ => true,
|
||||
});
|
||||
|
||||
if !seen_viewport {
|
||||
dock.main_surface_mut()
|
||||
.push_to_first_leaf(EditorTab::Viewport);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_tab_to_node(tree: &mut Tree<EditorTab>, node_index: NodeIndex, tab: EditorTab) -> TabIndex {
|
||||
match &mut tree[node_index] {
|
||||
Node::Leaf(leaf) => {
|
||||
let tab_idx = TabIndex(leaf.tabs.len());
|
||||
leaf.tabs.push(tab);
|
||||
leaf.active = tab_idx;
|
||||
tab_idx
|
||||
}
|
||||
Node::Empty => {
|
||||
tree[node_index] = Node::leaf(tab);
|
||||
TabIndex(0)
|
||||
}
|
||||
_ => {
|
||||
let kind = tab.clone();
|
||||
tree.push_to_first_leaf(tab);
|
||||
tree.find_tab(&kind).expect("tab was just pushed").1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Phosphor icon font registration for the primary egui context.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::{EguiContext, PrimaryEguiContext};
|
||||
|
||||
pub struct EditorFontsPlugin;
|
||||
|
||||
impl Plugin for EditorFontsPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Update, configure_editor_fonts);
|
||||
}
|
||||
}
|
||||
|
||||
fn configure_editor_fonts(mut contexts: Query<&mut EguiContext, Added<PrimaryEguiContext>>) {
|
||||
let Some(mut ctx) = contexts.iter_mut().next() else {
|
||||
return;
|
||||
};
|
||||
let mut fonts = bevy_egui::egui::FontDefinitions::default();
|
||||
egui_phosphor_icons::add_fonts(&mut fonts);
|
||||
ctx.get_mut().set_fonts(fonts);
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Spawn helpers, bookmarks, hierarchy tree, and asset labeling.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use shared::{
|
||||
AuthoringLightKind, LevelObject, LightDesc, MaterialDesc, PlayerSpawn, PrimitiveShape,
|
||||
ProjectSun,
|
||||
};
|
||||
use sim::Player;
|
||||
|
||||
use crate::assets::{snapshot_for_asset, EditorAsset, EditorAssetKind};
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
|
||||
use crate::history::{set_material_with_history, spawn_with_history, EditorEntitySnapshot};
|
||||
use crate::play::default_player_spawn;
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::viewport::{recall_camera_bookmark, save_camera_bookmark, CameraBookmarks};
|
||||
|
||||
pub use super::play_controls::{toggle_play_mode, toggle_play_paused, toggle_possession};
|
||||
pub use super::selection_ops::{
|
||||
delete_selection, duplicate_selection, entity_name, focus_editor_camera_on_selection,
|
||||
is_level_object, selected_level_entities,
|
||||
};
|
||||
|
||||
pub fn set_gizmo_mode(world: &mut World, mode: EditorGizmoMode) {
|
||||
*world.resource_mut::<EditorGizmoMode>() = mode;
|
||||
}
|
||||
|
||||
pub fn set_gizmo_space(world: &mut World, space: EditorGizmoSpace) {
|
||||
*world.resource_mut::<EditorGizmoSpace>() = space;
|
||||
}
|
||||
|
||||
pub fn viewport_save_bookmark(world: &mut World) {
|
||||
let scene_key = world
|
||||
.resource::<SceneIo>()
|
||||
.active_path
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|| "__unsaved__".into());
|
||||
let Some(transform) = world
|
||||
.query_filtered::<&Transform, With<EditorCamera>>()
|
||||
.single(world)
|
||||
.ok()
|
||||
.copied()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut bookmarks = world.resource_mut::<CameraBookmarks>();
|
||||
save_camera_bookmark(&mut bookmarks, &scene_key, transform);
|
||||
}
|
||||
|
||||
pub fn viewport_recall_bookmark(world: &mut World) {
|
||||
let scene_key = world
|
||||
.resource::<SceneIo>()
|
||||
.active_path
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|| "__unsaved__".into());
|
||||
let saved = {
|
||||
let bookmarks = world.resource::<CameraBookmarks>();
|
||||
match recall_camera_bookmark(bookmarks, &scene_key) {
|
||||
Some(transform) => transform,
|
||||
None => return,
|
||||
}
|
||||
};
|
||||
for mut transform in world
|
||||
.query_filtered::<&mut Transform, With<EditorCamera>>()
|
||||
.iter_mut(world)
|
||||
{
|
||||
*transform = saved;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn primitive_snapshot(name: &str, shape: PrimitiveShape, origin: Vec3) -> EditorEntitySnapshot {
|
||||
let asset = EditorAsset {
|
||||
label: name.to_string(),
|
||||
path: None,
|
||||
folder_path: crate::assets::BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::Primitive(shape),
|
||||
};
|
||||
snapshot_for_asset(&asset, origin).expect("primitive assets are spawnable")
|
||||
}
|
||||
|
||||
pub fn light_snapshot(name: &str, translation: Vec3) -> EditorEntitySnapshot {
|
||||
EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: shared::ActorKind::Light,
|
||||
actor_name: None,
|
||||
name: Some(name.to_string()),
|
||||
transform: Transform::from_translation(translation),
|
||||
primitive: None,
|
||||
static_mesh_renderer: None,
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: None,
|
||||
collider: None,
|
||||
physics: None,
|
||||
light: Some(LightDesc::default()),
|
||||
player_spawn: false,
|
||||
model: None,
|
||||
prefab: None,
|
||||
prefab_instance: None,
|
||||
weapon_spawn: None,
|
||||
trigger_volume: None,
|
||||
post_process_volume: None,
|
||||
team_spawn: None,
|
||||
objective: None,
|
||||
hierarchy_sibling_index: 0,
|
||||
editor_visibility: shared::EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ensure_player_spawn_for_edit(world: &mut World) -> Entity {
|
||||
if let Some(entity) = world
|
||||
.query_filtered::<Entity, With<PlayerSpawn>>()
|
||||
.iter(world)
|
||||
.next()
|
||||
{
|
||||
return entity;
|
||||
}
|
||||
|
||||
let transform = world
|
||||
.query_filtered::<&Transform, With<Player>>()
|
||||
.iter(world)
|
||||
.next()
|
||||
.copied()
|
||||
.unwrap_or_else(default_player_spawn);
|
||||
|
||||
spawn_with_history(
|
||||
world,
|
||||
EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: shared::ActorKind::PlayerSpawn,
|
||||
actor_name: None,
|
||||
name: Some("Player Start".to_string()),
|
||||
transform,
|
||||
primitive: None,
|
||||
static_mesh_renderer: None,
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: None,
|
||||
collider: None,
|
||||
physics: None,
|
||||
light: None,
|
||||
player_spawn: true,
|
||||
model: None,
|
||||
prefab: None,
|
||||
prefab_instance: None,
|
||||
weapon_spawn: None,
|
||||
trigger_volume: None,
|
||||
post_process_volume: None,
|
||||
team_spawn: None,
|
||||
objective: None,
|
||||
hierarchy_sibling_index: 0,
|
||||
editor_visibility: shared::EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes all authored [`LightDesc`] so project sun/ambient drive outdoor lighting.
|
||||
pub fn reset_scene_lighting_to_project_defaults(world: &mut World) {
|
||||
let mut query = world.query_filtered::<Entity, With<LevelObject>>();
|
||||
let with_lights: Vec<Entity> = query
|
||||
.iter(world)
|
||||
.filter(|entity| world.get::<LightDesc>(*entity).is_some())
|
||||
.collect();
|
||||
for entity in with_lights {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.remove::<LightDesc>();
|
||||
}
|
||||
}
|
||||
world
|
||||
.resource_mut::<crate::scene_io::SceneIo>()
|
||||
.mark_dirty();
|
||||
}
|
||||
|
||||
/// Removes authored directional lights so [`ProjectSun`] drives outdoor lighting.
|
||||
pub fn use_project_sun(world: &mut World) {
|
||||
let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>();
|
||||
let directionals: Vec<Entity> = query
|
||||
.iter(world)
|
||||
.filter(|(_, light)| matches!(light.kind, AuthoringLightKind::Directional))
|
||||
.map(|(e, _)| e)
|
||||
.collect();
|
||||
for entity in directionals {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.remove::<LightDesc>();
|
||||
}
|
||||
}
|
||||
world
|
||||
.resource_mut::<crate::scene_io::SceneIo>()
|
||||
.mark_dirty();
|
||||
}
|
||||
|
||||
pub fn create_scene_sun_override_from_project_settings(world: &mut World) -> Entity {
|
||||
let (transform, light) = {
|
||||
let sun_illuminance = world
|
||||
.resource::<settings::ProjectSettings>()
|
||||
.rendering
|
||||
.sun_illuminance;
|
||||
let transform = world
|
||||
.query_filtered::<&Transform, With<ProjectSun>>()
|
||||
.iter(world)
|
||||
.next()
|
||||
.copied()
|
||||
.unwrap_or_else(|| {
|
||||
Transform::from_xyz(0.0, 0.0, 0.0)
|
||||
.looking_to(Vec3::new(-0.35, -0.85, -0.4), Vec3::Y)
|
||||
});
|
||||
let mut light = LightDesc::for_kind(AuthoringLightKind::Directional);
|
||||
light.intensity = sun_illuminance;
|
||||
(transform, light)
|
||||
};
|
||||
|
||||
spawn_with_history(
|
||||
world,
|
||||
EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: shared::ActorKind::Light,
|
||||
actor_name: None,
|
||||
name: Some("Scene Sun".to_string()),
|
||||
transform,
|
||||
primitive: None,
|
||||
static_mesh_renderer: None,
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: None,
|
||||
collider: None,
|
||||
physics: None,
|
||||
light: Some(light),
|
||||
player_spawn: false,
|
||||
model: None,
|
||||
prefab: None,
|
||||
prefab_instance: None,
|
||||
weapon_spawn: None,
|
||||
trigger_volume: None,
|
||||
post_process_volume: None,
|
||||
team_spawn: None,
|
||||
objective: None,
|
||||
hierarchy_sibling_index: 0,
|
||||
editor_visibility: shared::EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn asset_label(asset: &EditorAsset) -> String {
|
||||
let prefix = match asset.kind {
|
||||
EditorAssetKind::Primitive(_) => "Primitive",
|
||||
EditorAssetKind::Light(_) => "Light",
|
||||
EditorAssetKind::Model => "Model",
|
||||
EditorAssetKind::Texture => "Texture",
|
||||
EditorAssetKind::Material => "Material",
|
||||
EditorAssetKind::Level => "Level",
|
||||
EditorAssetKind::Prefab => "Prefab",
|
||||
EditorAssetKind::PostProcessVolume => "Post Process Volume",
|
||||
EditorAssetKind::PostProcessEffect => "Post FX",
|
||||
EditorAssetKind::RenderingProfile => "Rendering Profile",
|
||||
EditorAssetKind::ShaderSchema => "Shader Schema",
|
||||
};
|
||||
format!("{prefix}: {}", asset.label)
|
||||
}
|
||||
|
||||
pub fn apply_texture_to_selection(
|
||||
world: &mut World,
|
||||
asset: &EditorAsset,
|
||||
selected: &SelectedEntities,
|
||||
) {
|
||||
let Some(path) = asset.path.clone() else {
|
||||
return;
|
||||
};
|
||||
for entity in selected_level_entities(world, selected) {
|
||||
let mut material = world
|
||||
.get::<MaterialDesc>(entity)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
material.base_color_texture = Some(path.clone());
|
||||
set_material_with_history(world, entity, material);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_material_asset_to_selection(
|
||||
world: &mut World,
|
||||
asset: &EditorAsset,
|
||||
selected: &SelectedEntities,
|
||||
) {
|
||||
crate::assets::materials::apply_material_asset_to_selection(world, asset, selected);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HierarchyNodeKind {
|
||||
Authored,
|
||||
Runtime,
|
||||
Generated,
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
//! Hierarchy outliner: tree view, drag-and-drop, visibility, and lock toggles.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use egui::containers::scroll_area::ScrollSource;
|
||||
use egui_phosphor_icons::icons;
|
||||
use shared::EditorVisibility;
|
||||
|
||||
use crate::history::{
|
||||
create_empty_child_with_history, delete_entities_with_history, duplicate_entities_with_history,
|
||||
group_selection_with_history, rename_entity_with_history, reorder_siblings_with_history,
|
||||
reparent_with_history, set_editor_visibility_with_history,
|
||||
};
|
||||
use crate::project_io::UserPreferences;
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::ui::helpers::{
|
||||
entity_name, focus_editor_camera_on_selection, is_level_object, HierarchyNodeKind,
|
||||
};
|
||||
use crate::ui::hierarchy_ops::{
|
||||
authored_children, editor_visibility, entity_hierarchy_path, entity_matches_filter,
|
||||
hierarchy_label_for_entity, is_entity_locked, level_object_roots, sort_siblings,
|
||||
would_create_cycle,
|
||||
};
|
||||
use crate::ui::hierarchy_state::{HierarchyPanelState, HierarchySort};
|
||||
use crate::ui::theme::panel_heading;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct HierarchyDragPayload {
|
||||
entities: Vec<Entity>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum DropTarget {
|
||||
Root,
|
||||
On(Entity),
|
||||
Before(Entity),
|
||||
}
|
||||
|
||||
pub fn hierarchy_panel_ui(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
selected_entities: &mut SelectedEntities,
|
||||
renaming_entity: &mut Option<Entity>,
|
||||
rename_buffer: &mut String,
|
||||
) {
|
||||
let (filter, sort_mode, show_generated, show_runtime, _expanded, _locked, prefs_paths) = {
|
||||
let state = world.resource::<HierarchyPanelState>();
|
||||
(
|
||||
state.filter.clone(),
|
||||
state.sort_mode,
|
||||
state.show_generated,
|
||||
state.show_runtime,
|
||||
state.expanded.clone(),
|
||||
state.locked.clone(),
|
||||
world
|
||||
.resource::<UserPreferences>()
|
||||
.hierarchy_expanded_paths
|
||||
.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
if _expanded.is_empty() && !prefs_paths.is_empty() {
|
||||
let synced = crate::ui::hierarchy_state::expanded_entities_for_paths(world, &prefs_paths);
|
||||
world.resource_mut::<HierarchyPanelState>().expanded = synced;
|
||||
}
|
||||
|
||||
let expanded = world.resource::<HierarchyPanelState>().expanded.clone();
|
||||
let locked = world.resource::<HierarchyPanelState>().locked.clone();
|
||||
|
||||
let mut filter = filter;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(icons::MAGNIFYING_GLASS.regular());
|
||||
if ui
|
||||
.add(
|
||||
egui::TextEdit::singleline(&mut filter)
|
||||
.hint_text("Search hierarchy...")
|
||||
.desired_width(f32::INFINITY),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
world.resource_mut::<HierarchyPanelState>().filter = filter.clone();
|
||||
world.resource_mut::<HierarchyPanelState>().mark_dirty();
|
||||
}
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Sort:");
|
||||
let mut sort = sort_mode;
|
||||
egui::ComboBox::from_id_salt("hierarchy_sort")
|
||||
.selected_text(sort_label(sort))
|
||||
.show_ui(ui, |ui| {
|
||||
for candidate in [
|
||||
HierarchySort::Manual,
|
||||
HierarchySort::Name,
|
||||
HierarchySort::Type,
|
||||
] {
|
||||
if ui
|
||||
.selectable_value(&mut sort, candidate, sort_label(candidate))
|
||||
.clicked()
|
||||
{
|
||||
world.resource_mut::<HierarchyPanelState>().sort_mode = candidate;
|
||||
world.resource_mut::<HierarchyPanelState>().mark_dirty();
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut show_gen = show_generated;
|
||||
if ui.checkbox(&mut show_gen, "Generated").changed() {
|
||||
world.resource_mut::<HierarchyPanelState>().show_generated = show_gen;
|
||||
world.resource_mut::<HierarchyPanelState>().mark_dirty();
|
||||
}
|
||||
let mut show_rt = show_runtime;
|
||||
if ui.checkbox(&mut show_rt, "Runtime").changed() {
|
||||
world.resource_mut::<HierarchyPanelState>().show_runtime = show_rt;
|
||||
world.resource_mut::<HierarchyPanelState>().mark_dirty();
|
||||
}
|
||||
});
|
||||
|
||||
ui.add_space(4.0);
|
||||
ui.label(panel_heading("Scene"));
|
||||
|
||||
if ui.input(|input| input.key_pressed(egui::Key::F2)) {
|
||||
if let Some(entity) = selected_entities.as_slice().first().copied() {
|
||||
if is_level_object(world, entity) {
|
||||
*renaming_entity = Some(entity);
|
||||
*rename_buffer = entity_name(world, entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let filter_lower = filter.trim().to_lowercase();
|
||||
let mut drop_target = None;
|
||||
let mut invalid_drop = false;
|
||||
|
||||
let dragging = world
|
||||
.resource::<HierarchyPanelState>()
|
||||
.active_drag
|
||||
.is_some();
|
||||
|
||||
egui::ScrollArea::vertical()
|
||||
.scroll_source(ScrollSource {
|
||||
scroll_bar: true,
|
||||
drag: !dragging,
|
||||
mouse_wheel: true,
|
||||
})
|
||||
.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
|
||||
if dragging {
|
||||
draw_root_drop_zone(ui, &mut drop_target);
|
||||
}
|
||||
|
||||
let mut roots = level_object_roots(world);
|
||||
sort_siblings(world, &mut roots, sort_mode);
|
||||
|
||||
let visible_roots: Vec<Entity> = roots
|
||||
.into_iter()
|
||||
.filter(|entity| subtree_matches_filter(world, *entity, &filter_lower, sort_mode))
|
||||
.collect();
|
||||
|
||||
for entity in visible_roots {
|
||||
draw_authored_node(
|
||||
world,
|
||||
ui,
|
||||
entity,
|
||||
0,
|
||||
selected_entities,
|
||||
renaming_entity,
|
||||
rename_buffer,
|
||||
&filter_lower,
|
||||
sort_mode,
|
||||
show_generated,
|
||||
dragging,
|
||||
&expanded,
|
||||
&locked,
|
||||
&prefs_paths,
|
||||
&mut drop_target,
|
||||
&mut invalid_drop,
|
||||
);
|
||||
}
|
||||
|
||||
if show_runtime {
|
||||
let runtime_roots = runtime_roots(world);
|
||||
if !runtime_roots.is_empty() {
|
||||
ui.add_space(6.0);
|
||||
ui.small(egui::RichText::new("Runtime").weak());
|
||||
for entity in runtime_roots {
|
||||
draw_runtime_node(world, ui, entity, 0, selected_entities, show_runtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if ui.ctx().input(|input| input.pointer.any_released()) {
|
||||
if let Some(target) = drop_target {
|
||||
let drag_entities = world
|
||||
.resource_mut::<HierarchyPanelState>()
|
||||
.active_drag
|
||||
.take();
|
||||
if let Some(entities) = drag_entities {
|
||||
let payload = HierarchyDragPayload { entities };
|
||||
apply_drop(world, &payload, target, invalid_drop);
|
||||
}
|
||||
} else {
|
||||
world.resource_mut::<HierarchyPanelState>().active_drag = None;
|
||||
}
|
||||
}
|
||||
|
||||
if selected_entities.as_slice().first().copied() != world.resource::<SelectedEntity>().0 {
|
||||
world.resource_mut::<SelectedEntity>().0 = selected_entities.as_slice().first().copied();
|
||||
}
|
||||
}
|
||||
|
||||
fn sort_label(sort: HierarchySort) -> &'static str {
|
||||
match sort {
|
||||
HierarchySort::Manual => "Manual",
|
||||
HierarchySort::Name => "Name",
|
||||
HierarchySort::Type => "Type",
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_root_drop_zone(ui: &mut egui::Ui, drop_target: &mut Option<DropTarget>) {
|
||||
let (rect, response) =
|
||||
ui.allocate_exact_size(egui::vec2(ui.available_width(), 2.0), egui::Sense::hover());
|
||||
if let Some(hover) = response.dnd_hover_payload::<HierarchyDragPayload>() {
|
||||
ui.painter()
|
||||
.rect_filled(rect, 1.0, egui::Color32::from_rgb(80, 120, 200));
|
||||
*drop_target = Some(DropTarget::Root);
|
||||
let _ = hover;
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_authored_node(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
depth: usize,
|
||||
selected_entities: &mut SelectedEntities,
|
||||
renaming_entity: &mut Option<Entity>,
|
||||
rename_buffer: &mut String,
|
||||
filter_lower: &str,
|
||||
sort_mode: HierarchySort,
|
||||
show_generated: bool,
|
||||
drag_active: bool,
|
||||
expanded: &std::collections::HashSet<Entity>,
|
||||
locked: &std::collections::HashSet<Entity>,
|
||||
prefs_paths: &[String],
|
||||
drop_target: &mut Option<DropTarget>,
|
||||
invalid_drop: &mut bool,
|
||||
) {
|
||||
let path = entity_hierarchy_path(world, entity);
|
||||
let mut is_expanded = expanded.contains(&entity) || prefs_paths.iter().any(|p| p == &path);
|
||||
let has_children = authored_children(world, entity)
|
||||
.iter()
|
||||
.any(|child| subtree_matches_filter(world, *child, filter_lower, sort_mode))
|
||||
|| (show_generated
|
||||
&& world.get::<Children>(entity).is_some_and(|children| {
|
||||
children
|
||||
.iter()
|
||||
.any(|child| is_hierarchy_generated_child(world, child))
|
||||
}));
|
||||
|
||||
draw_drop_before(
|
||||
world,
|
||||
ui,
|
||||
entity,
|
||||
depth,
|
||||
drag_active,
|
||||
drop_target,
|
||||
invalid_drop,
|
||||
);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(depth as f32 * 14.0);
|
||||
if has_children {
|
||||
let twistie = if is_expanded {
|
||||
icons::CARET_DOWN
|
||||
} else {
|
||||
icons::CARET_RIGHT
|
||||
};
|
||||
if ui.small_button(twistie.as_str()).clicked() {
|
||||
let path = path.clone();
|
||||
let expanding = !world
|
||||
.resource::<HierarchyPanelState>()
|
||||
.expanded
|
||||
.contains(&entity);
|
||||
{
|
||||
let mut state = world.resource_mut::<HierarchyPanelState>();
|
||||
if expanding {
|
||||
state.expanded.insert(entity);
|
||||
} else {
|
||||
state.expanded.remove(&entity);
|
||||
}
|
||||
state.mark_dirty();
|
||||
}
|
||||
let mut prefs = world.resource_mut::<UserPreferences>();
|
||||
if expanding {
|
||||
if !prefs
|
||||
.hierarchy_expanded_paths
|
||||
.iter()
|
||||
.any(|entry| entry == &path)
|
||||
{
|
||||
prefs.hierarchy_expanded_paths.push(path);
|
||||
}
|
||||
} else {
|
||||
prefs
|
||||
.hierarchy_expanded_paths
|
||||
.retain(|entry| entry != &path);
|
||||
}
|
||||
is_expanded = expanding;
|
||||
}
|
||||
} else {
|
||||
ui.add_space(18.0);
|
||||
}
|
||||
|
||||
let visible = editor_visibility(world, entity).visible;
|
||||
let eye_icon = if visible {
|
||||
icons::EYE.regular()
|
||||
} else {
|
||||
icons::EYE_SLASH.regular()
|
||||
};
|
||||
if ui.small_button(eye_icon).clicked() {
|
||||
set_editor_visibility_with_history(
|
||||
world,
|
||||
entity,
|
||||
EditorVisibility { visible: !visible },
|
||||
);
|
||||
}
|
||||
|
||||
let is_locked = is_entity_locked(locked, entity);
|
||||
let lock_icon = if is_locked {
|
||||
icons::LOCK.regular()
|
||||
} else {
|
||||
icons::LOCK_OPEN.regular()
|
||||
};
|
||||
if ui.small_button(lock_icon).clicked() {
|
||||
let mut state = world.resource_mut::<HierarchyPanelState>();
|
||||
if is_locked {
|
||||
state.locked.remove(&entity);
|
||||
} else {
|
||||
state.locked.insert(entity);
|
||||
}
|
||||
}
|
||||
|
||||
if *renaming_entity == Some(entity) {
|
||||
let response = ui.text_edit_singleline(rename_buffer);
|
||||
let commit =
|
||||
response.lost_focus() || ui.input(|input| input.key_pressed(egui::Key::Enter));
|
||||
if commit {
|
||||
rename_entity_with_history(world, entity, rename_buffer.clone());
|
||||
*renaming_entity = None;
|
||||
}
|
||||
} else {
|
||||
let selected = selected_entities.contains(entity);
|
||||
let label = hierarchy_label_for_entity(world, entity, HierarchyNodeKind::Authored);
|
||||
let response = ui.selectable_label(selected, label);
|
||||
if response.clicked() && !is_locked {
|
||||
let additive = ui.input(|input| {
|
||||
input.modifiers.shift || input.modifiers.command || input.modifiers.ctrl
|
||||
});
|
||||
if additive {
|
||||
selected_entities.select_maybe_add(entity, true);
|
||||
} else {
|
||||
selected_entities.select_replace(entity);
|
||||
}
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(entity);
|
||||
}
|
||||
if response.double_clicked() && is_level_object(world, entity) {
|
||||
*renaming_entity = Some(entity);
|
||||
*rename_buffer = entity_name(world, entity);
|
||||
}
|
||||
|
||||
if response.drag_started() {
|
||||
let drag_entities: Vec<Entity> = if selected_entities.contains(entity) {
|
||||
selected_entities
|
||||
.iter()
|
||||
.filter(|e| is_level_object(world, *e))
|
||||
.collect()
|
||||
} else {
|
||||
vec![entity]
|
||||
};
|
||||
response.dnd_set_drag_payload(HierarchyDragPayload {
|
||||
entities: drag_entities.clone(),
|
||||
});
|
||||
world.resource_mut::<HierarchyPanelState>().active_drag = Some(drag_entities);
|
||||
}
|
||||
|
||||
if let Some(hover) = response.dnd_hover_payload::<HierarchyDragPayload>() {
|
||||
let invalid = would_create_cycle(world, &hover.entities, Some(entity));
|
||||
*invalid_drop = invalid;
|
||||
*drop_target = Some(DropTarget::On(entity));
|
||||
if invalid {
|
||||
ui.painter().rect_stroke(
|
||||
response.rect,
|
||||
2.0,
|
||||
egui::Stroke::new(2.0, egui::Color32::RED),
|
||||
egui::StrokeKind::Outside,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
response.context_menu(|ui| {
|
||||
authored_context_menu(
|
||||
world,
|
||||
ui,
|
||||
entity,
|
||||
selected_entities,
|
||||
renaming_entity,
|
||||
rename_buffer,
|
||||
)
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if !is_expanded {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut children = authored_children(world, entity);
|
||||
sort_siblings(world, &mut children, sort_mode);
|
||||
for child in children {
|
||||
if subtree_matches_filter(world, child, filter_lower, sort_mode) {
|
||||
draw_authored_node(
|
||||
world,
|
||||
ui,
|
||||
child,
|
||||
depth + 1,
|
||||
selected_entities,
|
||||
renaming_entity,
|
||||
rename_buffer,
|
||||
filter_lower,
|
||||
sort_mode,
|
||||
show_generated,
|
||||
drag_active,
|
||||
expanded,
|
||||
locked,
|
||||
prefs_paths,
|
||||
drop_target,
|
||||
invalid_drop,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if show_generated {
|
||||
if let Some(children) = world.get::<Children>(entity) {
|
||||
for child in children.iter() {
|
||||
if is_hierarchy_generated_child(world, child) {
|
||||
draw_generated_node(world, ui, child, depth + 1, expanded, show_generated);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_drop_before(
|
||||
world: &World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
depth: usize,
|
||||
drag_active: bool,
|
||||
drop_target: &mut Option<DropTarget>,
|
||||
invalid_drop: &mut bool,
|
||||
) {
|
||||
if !drag_active {
|
||||
return;
|
||||
}
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(depth as f32 * 14.0 + 18.0);
|
||||
let (rect, response) =
|
||||
ui.allocate_exact_size(egui::vec2(ui.available_width(), 2.0), egui::Sense::hover());
|
||||
if let Some(hover) = response.dnd_hover_payload::<HierarchyDragPayload>() {
|
||||
*invalid_drop = would_create_cycle(
|
||||
world,
|
||||
&hover.entities,
|
||||
world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent()),
|
||||
);
|
||||
*drop_target = Some(DropTarget::Before(entity));
|
||||
let color = if *invalid_drop {
|
||||
egui::Color32::RED
|
||||
} else {
|
||||
egui::Color32::from_rgb(80, 120, 200)
|
||||
};
|
||||
ui.painter().rect_filled(rect, 1.0, color);
|
||||
let _ = hover;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn draw_generated_node(
|
||||
world: &World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
depth: usize,
|
||||
expanded: &std::collections::HashSet<Entity>,
|
||||
show_generated: bool,
|
||||
) {
|
||||
let _ = show_generated;
|
||||
let has_children = world.get::<Children>(entity).is_some_and(|children| {
|
||||
children
|
||||
.iter()
|
||||
.any(|child| is_hierarchy_generated_child(world, child))
|
||||
});
|
||||
let mut is_expanded = expanded.contains(&entity);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(depth as f32 * 14.0);
|
||||
if has_children {
|
||||
let twistie = if is_expanded {
|
||||
icons::CARET_DOWN
|
||||
} else {
|
||||
icons::CARET_RIGHT
|
||||
};
|
||||
if ui.small_button(twistie.as_str()).clicked() {
|
||||
is_expanded = !is_expanded;
|
||||
}
|
||||
} else {
|
||||
ui.add_space(18.0);
|
||||
}
|
||||
ui.add_enabled(
|
||||
false,
|
||||
egui::Label::new(
|
||||
egui::RichText::new(hierarchy_label_for_entity(
|
||||
world,
|
||||
entity,
|
||||
HierarchyNodeKind::Generated,
|
||||
))
|
||||
.weak(),
|
||||
),
|
||||
);
|
||||
});
|
||||
if !is_expanded {
|
||||
return;
|
||||
}
|
||||
if let Some(children) = world.get::<Children>(entity) {
|
||||
for child in children.iter() {
|
||||
if is_hierarchy_generated_child(world, child) {
|
||||
draw_generated_node(world, ui, child, depth + 1, expanded, show_generated);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_runtime_node(
|
||||
world: &World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
depth: usize,
|
||||
selected_entities: &mut SelectedEntities,
|
||||
show_runtime: bool,
|
||||
) {
|
||||
let _ = show_runtime;
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(depth as f32 * 14.0);
|
||||
ui.add_space(18.0);
|
||||
let label = hierarchy_label_for_entity(world, entity, HierarchyNodeKind::Runtime);
|
||||
let response = ui.selectable_label(selected_entities.contains(entity), label);
|
||||
if response.clicked() {
|
||||
selected_entities.select_replace(entity);
|
||||
}
|
||||
response.context_menu(|ui| {
|
||||
if ui.button("Focus").clicked() {
|
||||
selected_entities.select_replace(entity);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(children) = world.get::<Children>(entity) {
|
||||
for child in children.iter() {
|
||||
if is_runtime_hierarchy_entity(world, child) {
|
||||
draw_runtime_node(world, ui, child, depth + 1, selected_entities, show_runtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn authored_context_menu(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
selected_entities: &mut SelectedEntities,
|
||||
renaming_entity: &mut Option<Entity>,
|
||||
rename_buffer: &mut String,
|
||||
) {
|
||||
if ui.button("Rename").clicked() {
|
||||
*renaming_entity = Some(entity);
|
||||
*rename_buffer = entity_name(world, entity);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Duplicate").clicked() {
|
||||
duplicate_entities_with_history(world, &[entity]);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Delete").clicked() {
|
||||
delete_entities_with_history(world, &[entity]);
|
||||
ui.close();
|
||||
}
|
||||
if selected_entities.len() >= 2 && selected_entities.contains(entity) {
|
||||
if ui.button("Group").clicked() {
|
||||
let entities: Vec<Entity> = selected_entities
|
||||
.iter()
|
||||
.filter(|e| is_level_object(world, *e))
|
||||
.collect();
|
||||
group_selection_with_history(world, &entities);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if ui.button("Unparent").clicked() {
|
||||
reparent_with_history(world, entity, None);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Create child Empty").clicked() {
|
||||
create_empty_child_with_history(world, entity);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Focus").clicked() {
|
||||
selected_entities.select_replace(entity);
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(entity);
|
||||
focus_editor_camera_on_selection(world);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_drop(world: &mut World, drag: &HierarchyDragPayload, target: DropTarget, invalid: bool) {
|
||||
if invalid || drag.entities.is_empty() {
|
||||
return;
|
||||
}
|
||||
match target {
|
||||
DropTarget::Root => {
|
||||
reorder_siblings_with_history(world, &drag.entities, None, i32::MAX);
|
||||
}
|
||||
DropTarget::On(parent) => {
|
||||
reorder_siblings_with_history(world, &drag.entities, Some(parent), i32::MAX);
|
||||
}
|
||||
DropTarget::Before(before) => {
|
||||
let parent = world
|
||||
.get::<ChildOf>(before)
|
||||
.map(|child_of| child_of.parent());
|
||||
let siblings = match parent {
|
||||
Some(parent) => authored_children(world, parent),
|
||||
None => level_object_roots(world),
|
||||
};
|
||||
let insert_index = siblings
|
||||
.iter()
|
||||
.position(|entity| *entity == before)
|
||||
.unwrap_or(siblings.len()) as i32;
|
||||
reorder_siblings_with_history(world, &drag.entities, parent, insert_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn subtree_matches_filter(
|
||||
world: &World,
|
||||
entity: Entity,
|
||||
filter_lower: &str,
|
||||
sort_mode: HierarchySort,
|
||||
) -> bool {
|
||||
if filter_lower.is_empty() {
|
||||
return true;
|
||||
}
|
||||
if entity_matches_filter(world, entity, filter_lower) {
|
||||
return true;
|
||||
}
|
||||
let mut children = authored_children(world, entity);
|
||||
sort_siblings(world, &mut children, sort_mode);
|
||||
children
|
||||
.iter()
|
||||
.any(|child| subtree_matches_filter(world, *child, filter_lower, sort_mode))
|
||||
}
|
||||
|
||||
fn runtime_roots(world: &mut World) -> Vec<Entity> {
|
||||
use shared::ProjectSun;
|
||||
use sim::{Player, PlayerCamera};
|
||||
|
||||
let mut query = world.query_filtered::<
|
||||
(Entity, Option<&ChildOf>),
|
||||
Or<(With<Player>, With<PlayerCamera>, With<ProjectSun>)>,
|
||||
>();
|
||||
query
|
||||
.iter(world)
|
||||
.filter_map(|(entity, parent)| {
|
||||
if parent
|
||||
.map(|parent| is_runtime_hierarchy_entity(world, parent.parent()))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
None
|
||||
} else {
|
||||
Some(entity)
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn is_hierarchy_generated_child(world: &World, entity: Entity) -> bool {
|
||||
use shared::LevelObject;
|
||||
world.get_entity(entity).is_ok_and(|entity_ref| {
|
||||
!entity_ref.contains::<crate::infra::EditorOnly>()
|
||||
&& !entity_ref.contains::<LevelObject>()
|
||||
&& !entity_ref.contains::<crate::visualizers::EditorVisualizerProxy>()
|
||||
&& (entity_ref.contains::<Transform>() || entity_ref.contains::<GlobalTransform>())
|
||||
&& (entity_ref.contains::<Name>()
|
||||
|| entity_ref.contains::<Mesh3d>()
|
||||
|| entity_ref.contains::<SceneRoot>())
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_runtime_hierarchy_entity(world: &World, entity: Entity) -> bool {
|
||||
use shared::ProjectSun;
|
||||
use sim::{Player, PlayerCamera};
|
||||
|
||||
world.get_entity(entity).is_ok_and(|entity_ref| {
|
||||
!entity_ref.contains::<crate::infra::EditorOnly>()
|
||||
&& (entity_ref.contains::<Player>()
|
||||
|| entity_ref.contains::<PlayerCamera>()
|
||||
|| entity_ref.contains::<ProjectSun>())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
//! Hierarchy tree building, sibling ordering, and reparent helpers.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
ActorKind, AuthoringLightKind, EditorVisibility, HierarchySiblingIndex, LevelObject, LightDesc,
|
||||
ModelRef, PhysicsBody, PlayerSpawn,
|
||||
};
|
||||
|
||||
use super::helpers::{entity_name, is_level_object, HierarchyNodeKind};
|
||||
use super::hierarchy_state::HierarchySort;
|
||||
use crate::history::SiblingChange;
|
||||
|
||||
pub fn sibling_index(world: &World, entity: Entity) -> i32 {
|
||||
world
|
||||
.get::<HierarchySiblingIndex>(entity)
|
||||
.map(|index| index.0)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn is_ancestor(world: &World, ancestor: Entity, descendant: Entity) -> bool {
|
||||
if ancestor == descendant {
|
||||
return true;
|
||||
}
|
||||
let mut current = world
|
||||
.get::<ChildOf>(descendant)
|
||||
.map(|child_of| child_of.parent());
|
||||
while let Some(entity) = current {
|
||||
if entity == ancestor {
|
||||
return true;
|
||||
}
|
||||
current = world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent());
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn would_create_cycle(world: &World, targets: &[Entity], new_parent: Option<Entity>) -> bool {
|
||||
let Some(parent) = new_parent else {
|
||||
return false;
|
||||
};
|
||||
targets
|
||||
.iter()
|
||||
.any(|entity| is_ancestor(world, *entity, parent))
|
||||
}
|
||||
|
||||
pub fn level_object_roots(world: &mut World) -> Vec<Entity> {
|
||||
let mut query = world.query_filtered::<(Entity, Option<&ChildOf>), With<LevelObject>>();
|
||||
query
|
||||
.iter(world)
|
||||
.filter_map(|(entity, parent)| match parent {
|
||||
Some(parent) if is_level_object(world, parent.parent()) => None,
|
||||
_ => Some(entity),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn authored_children(world: &World, parent: Entity) -> Vec<Entity> {
|
||||
world
|
||||
.get::<Children>(parent)
|
||||
.map(|children| {
|
||||
children
|
||||
.iter()
|
||||
.filter(|child| is_level_object(world, *child))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn entity_tie_break(a: Entity, b: Entity) -> std::cmp::Ordering {
|
||||
a.to_bits().cmp(&b.to_bits())
|
||||
}
|
||||
|
||||
pub fn sort_siblings(world: &World, entities: &mut [Entity], sort_mode: HierarchySort) {
|
||||
match sort_mode {
|
||||
HierarchySort::Manual => {
|
||||
entities.sort_by(|a, b| {
|
||||
sibling_index(world, *a)
|
||||
.cmp(&sibling_index(world, *b))
|
||||
.then_with(|| entity_tie_break(*a, *b))
|
||||
});
|
||||
}
|
||||
HierarchySort::Name => {
|
||||
entities.sort_by(|a, b| {
|
||||
entity_name(world, *a)
|
||||
.cmp(&entity_name(world, *b))
|
||||
.then_with(|| sibling_index(world, *a).cmp(&sibling_index(world, *b)))
|
||||
.then_with(|| entity_tie_break(*a, *b))
|
||||
});
|
||||
}
|
||||
HierarchySort::Type => {
|
||||
entities.sort_by(|a, b| {
|
||||
actor_kind_sort_key(world, *a)
|
||||
.cmp(&actor_kind_sort_key(world, *b))
|
||||
.then_with(|| entity_name(world, *a).cmp(&entity_name(world, *b)))
|
||||
.then_with(|| sibling_index(world, *a).cmp(&sibling_index(world, *b)))
|
||||
.then_with(|| entity_tie_break(*a, *b))
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn actor_kind_sort_key(world: &World, entity: Entity) -> u8 {
|
||||
world
|
||||
.get::<ActorKind>(entity)
|
||||
.copied()
|
||||
.map(|kind| match kind {
|
||||
ActorKind::Empty => 0,
|
||||
ActorKind::StaticMesh | ActorKind::ImportedModel => 1,
|
||||
ActorKind::Light => 2,
|
||||
ActorKind::PrefabAnchor => 3,
|
||||
ActorKind::PlayerSpawn => 4,
|
||||
ActorKind::WeaponSpawn => 5,
|
||||
ActorKind::TriggerVolume => 6,
|
||||
ActorKind::PostProcessVolume => 6,
|
||||
ActorKind::TeamSpawn => 7,
|
||||
ActorKind::Objective => 8,
|
||||
})
|
||||
.unwrap_or(9)
|
||||
}
|
||||
|
||||
pub fn entity_hierarchy_path(world: &World, entity: Entity) -> String {
|
||||
let mut parts = vec![entity_name(world, entity)];
|
||||
let mut current = world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent());
|
||||
while let Some(parent) = current {
|
||||
if !is_level_object(world, parent) {
|
||||
break;
|
||||
}
|
||||
parts.push(entity_name(world, parent));
|
||||
current = world
|
||||
.get::<ChildOf>(parent)
|
||||
.map(|child_of| child_of.parent());
|
||||
}
|
||||
parts.reverse();
|
||||
parts.join("/")
|
||||
}
|
||||
|
||||
pub fn next_sibling_index(world: &mut World, parent: Option<Entity>) -> i32 {
|
||||
let siblings = match parent {
|
||||
Some(parent) => authored_children(world, parent),
|
||||
None => level_object_roots(world),
|
||||
};
|
||||
siblings
|
||||
.iter()
|
||||
.map(|entity| sibling_index(world, *entity))
|
||||
.max()
|
||||
.map(|max| max + 1)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn renumber_siblings(world: &mut World, parent: Option<Entity>, ordered: &[Entity]) {
|
||||
for (index, entity) in ordered.iter().enumerate() {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
|
||||
entity_mut.insert(HierarchySiblingIndex(index as i32));
|
||||
}
|
||||
}
|
||||
let _ = parent;
|
||||
}
|
||||
|
||||
pub fn capture_sibling_state(world: &World, entity: Entity) -> SiblingChange {
|
||||
SiblingChange {
|
||||
entity,
|
||||
old_parent: world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent()),
|
||||
new_parent: world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent()),
|
||||
old_index: sibling_index(world, entity),
|
||||
new_index: sibling_index(world, entity),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_sibling_change(world: &mut World, change: &SiblingChange) {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(change.entity) {
|
||||
if let Some(parent) = change.old_parent {
|
||||
entity_mut.insert(ChildOf(parent));
|
||||
} else {
|
||||
entity_mut.remove::<ChildOf>();
|
||||
}
|
||||
entity_mut.insert(HierarchySiblingIndex(change.old_index));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_sibling_change_new(world: &mut World, change: &SiblingChange) {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(change.entity) {
|
||||
if let Some(parent) = change.new_parent {
|
||||
entity_mut.insert(ChildOf(parent));
|
||||
} else {
|
||||
entity_mut.remove::<ChildOf>();
|
||||
}
|
||||
entity_mut.insert(HierarchySiblingIndex(change.new_index));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reorder_entities_under_parent(
|
||||
world: &mut World,
|
||||
moving: &[Entity],
|
||||
new_parent: Option<Entity>,
|
||||
insert_index: i32,
|
||||
) -> Vec<SiblingChange> {
|
||||
let mut changes = Vec::new();
|
||||
let old_parents: std::collections::HashSet<Option<Entity>> = moving
|
||||
.iter()
|
||||
.map(|entity| {
|
||||
world
|
||||
.get::<ChildOf>(*entity)
|
||||
.map(|child_of| child_of.parent())
|
||||
})
|
||||
.collect();
|
||||
|
||||
changes.extend(renumber_inserted_siblings(
|
||||
world,
|
||||
moving,
|
||||
new_parent,
|
||||
insert_index,
|
||||
));
|
||||
|
||||
for old_parent in old_parents {
|
||||
if old_parent == new_parent {
|
||||
continue;
|
||||
}
|
||||
changes.extend(renumber_existing_siblings(world, old_parent, moving));
|
||||
}
|
||||
|
||||
changes
|
||||
}
|
||||
|
||||
fn renumber_inserted_siblings(
|
||||
world: &mut World,
|
||||
moving: &[Entity],
|
||||
new_parent: Option<Entity>,
|
||||
insert_index: i32,
|
||||
) -> Vec<SiblingChange> {
|
||||
let mut siblings = match new_parent {
|
||||
Some(parent) => authored_children(world, parent),
|
||||
None => level_object_roots(world),
|
||||
};
|
||||
siblings.retain(|entity| !moving.contains(entity));
|
||||
let insert = insert_index.clamp(0, siblings.len() as i32) as usize;
|
||||
for (offset, entity) in moving.iter().enumerate() {
|
||||
siblings.insert(insert + offset, *entity);
|
||||
}
|
||||
apply_sibling_order(world, new_parent, &siblings)
|
||||
}
|
||||
|
||||
fn renumber_existing_siblings(
|
||||
world: &mut World,
|
||||
parent: Option<Entity>,
|
||||
exclude: &[Entity],
|
||||
) -> Vec<SiblingChange> {
|
||||
let mut siblings = match parent {
|
||||
Some(parent) => authored_children(world, parent),
|
||||
None => level_object_roots(world),
|
||||
};
|
||||
siblings.retain(|entity| !exclude.contains(entity));
|
||||
sort_siblings(world, &mut siblings, HierarchySort::Manual);
|
||||
apply_sibling_order(world, parent, &siblings)
|
||||
}
|
||||
|
||||
fn apply_sibling_order(
|
||||
world: &mut World,
|
||||
parent: Option<Entity>,
|
||||
siblings: &[Entity],
|
||||
) -> Vec<SiblingChange> {
|
||||
let mut changes = Vec::new();
|
||||
for (index, entity) in siblings.iter().enumerate() {
|
||||
let old_parent = world
|
||||
.get::<ChildOf>(*entity)
|
||||
.map(|child_of| child_of.parent());
|
||||
let old_index = sibling_index(world, *entity);
|
||||
let new_index = index as i32;
|
||||
if old_parent != parent || old_index != new_index {
|
||||
changes.push(SiblingChange {
|
||||
entity: *entity,
|
||||
old_parent,
|
||||
new_parent: parent,
|
||||
old_index,
|
||||
new_index,
|
||||
});
|
||||
}
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
|
||||
if let Some(parent) = parent {
|
||||
entity_mut.insert(ChildOf(parent));
|
||||
} else {
|
||||
entity_mut.remove::<ChildOf>();
|
||||
}
|
||||
entity_mut.insert(HierarchySiblingIndex(new_index));
|
||||
}
|
||||
}
|
||||
changes
|
||||
}
|
||||
|
||||
pub fn backfill_missing_editor_visibility(world: &mut World) {
|
||||
let mut query =
|
||||
world.query_filtered::<Entity, (With<LevelObject>, Without<EditorVisibility>)>();
|
||||
let entities: Vec<Entity> = query.iter(world).collect();
|
||||
for entity in entities {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert(EditorVisibility::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backfill_missing_sibling_indices(world: &mut World) {
|
||||
let mut roots = level_object_roots(world);
|
||||
if roots
|
||||
.iter()
|
||||
.any(|entity| world.get::<HierarchySiblingIndex>(*entity).is_none())
|
||||
{
|
||||
sort_siblings(world, &mut roots, HierarchySort::Manual);
|
||||
renumber_siblings(world, None, &roots);
|
||||
}
|
||||
for root in roots {
|
||||
backfill_children(world, root);
|
||||
}
|
||||
}
|
||||
|
||||
fn backfill_children(world: &mut World, parent: Entity) {
|
||||
let mut children = authored_children(world, parent);
|
||||
if children
|
||||
.iter()
|
||||
.any(|entity| world.get::<HierarchySiblingIndex>(*entity).is_none())
|
||||
{
|
||||
sort_siblings(world, &mut children, HierarchySort::Manual);
|
||||
renumber_siblings(world, Some(parent), &children);
|
||||
}
|
||||
for child in children {
|
||||
backfill_children(world, child);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn actor_kind_icon(kind: ActorKind) -> &'static str {
|
||||
use egui_phosphor_icons::icons;
|
||||
match kind {
|
||||
ActorKind::Empty => icons::FOLDER.as_str(),
|
||||
ActorKind::StaticMesh => icons::CUBE.as_str(),
|
||||
ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(),
|
||||
ActorKind::Light => icons::LIGHTBULB.as_str(),
|
||||
ActorKind::PrefabAnchor => icons::PACKAGE.as_str(),
|
||||
ActorKind::PlayerSpawn => icons::USER_CIRCLE.as_str(),
|
||||
ActorKind::WeaponSpawn => icons::CROSSHAIR.as_str(),
|
||||
ActorKind::TriggerVolume => icons::BROADCAST.as_str(),
|
||||
ActorKind::PostProcessVolume => icons::CAMERA.as_str(),
|
||||
ActorKind::TeamSpawn => icons::FLAG.as_str(),
|
||||
ActorKind::Objective => icons::TARGET.as_str(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hierarchy_label_for_entity(
|
||||
world: &World,
|
||||
entity: Entity,
|
||||
kind: HierarchyNodeKind,
|
||||
) -> String {
|
||||
use egui_phosphor_icons::icons;
|
||||
let icon = world
|
||||
.get::<ActorKind>(entity)
|
||||
.copied()
|
||||
.map(actor_kind_icon)
|
||||
.unwrap_or_else(|| match kind {
|
||||
HierarchyNodeKind::Authored => icons::CUBE.as_str(),
|
||||
HierarchyNodeKind::Generated => icons::STACK.as_str(),
|
||||
HierarchyNodeKind::Runtime => icons::CPU.as_str(),
|
||||
});
|
||||
let mut label = format!("{} {}", icon, entity_name(world, entity));
|
||||
if let Some(light) = world.get::<LightDesc>(entity) {
|
||||
if matches!(light.kind, AuthoringLightKind::Directional) {
|
||||
label.push_str(" ☀");
|
||||
}
|
||||
}
|
||||
match kind {
|
||||
HierarchyNodeKind::Authored => {}
|
||||
HierarchyNodeKind::Generated => label.push_str(" (generated)"),
|
||||
HierarchyNodeKind::Runtime => label.push_str(" (runtime)"),
|
||||
}
|
||||
label
|
||||
}
|
||||
|
||||
pub fn entity_matches_filter(world: &World, entity: Entity, filter_lower: &str) -> bool {
|
||||
if filter_lower.is_empty() {
|
||||
return true;
|
||||
}
|
||||
if entity_name(world, entity)
|
||||
.to_lowercase()
|
||||
.contains(filter_lower)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if let Some(kind) = world.get::<ActorKind>(entity) {
|
||||
if format!("{kind:?}").to_lowercase().contains(filter_lower) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let tags = [
|
||||
world.get::<LightDesc>(entity).is_some().then_some("light"),
|
||||
world
|
||||
.get::<PlayerSpawn>(entity)
|
||||
.is_some()
|
||||
.then_some("spawn"),
|
||||
world.get::<ModelRef>(entity).is_some().then_some("model"),
|
||||
world
|
||||
.get::<PhysicsBody>(entity)
|
||||
.is_some()
|
||||
.then_some("physics"),
|
||||
world
|
||||
.get::<shared::PostProcessVolumeDesc>(entity)
|
||||
.is_some()
|
||||
.then_some("postprocess volume"),
|
||||
];
|
||||
tags.into_iter()
|
||||
.flatten()
|
||||
.any(|tag| tag.contains(filter_lower))
|
||||
}
|
||||
|
||||
pub fn editor_visibility(world: &World, entity: Entity) -> EditorVisibility {
|
||||
world
|
||||
.get::<EditorVisibility>(entity)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn is_entity_locked(locked: &std::collections::HashSet<Entity>, entity: Entity) -> bool {
|
||||
locked.contains(&entity)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sort_by_name_is_stable_for_duplicate_names() {
|
||||
let mut world = World::new();
|
||||
let a = world.spawn((LevelObject, Name::new("Pillar"))).id();
|
||||
let b = world.spawn((LevelObject, Name::new("Pillar"))).id();
|
||||
let mut entities = vec![a, b];
|
||||
|
||||
sort_siblings(&world, &mut entities, HierarchySort::Name);
|
||||
let first = entities.clone();
|
||||
|
||||
sort_siblings(&world, &mut entities, HierarchySort::Name);
|
||||
assert_eq!(entities, first, "duplicate-name sort must be deterministic");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Hierarchy panel UI state and user-preference persistence.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::project_io::{write_user_preferences, UserPreferences};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub enum HierarchySort {
|
||||
#[default]
|
||||
Manual,
|
||||
Name,
|
||||
Type,
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug)]
|
||||
pub struct HierarchyPanelState {
|
||||
pub expanded: HashSet<Entity>,
|
||||
pub filter: String,
|
||||
pub show_generated: bool,
|
||||
pub show_runtime: bool,
|
||||
pub sort_mode: HierarchySort,
|
||||
/// Editor-session lock: prevents selection and gizmo manipulation.
|
||||
pub locked: HashSet<Entity>,
|
||||
/// Active hierarchy drag (release payload for egui 0.33+).
|
||||
pub active_drag: Option<Vec<Entity>>,
|
||||
save_timer: f32,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
impl Default for HierarchyPanelState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
expanded: HashSet::new(),
|
||||
filter: String::new(),
|
||||
show_generated: true,
|
||||
show_runtime: false,
|
||||
sort_mode: HierarchySort::default(),
|
||||
locked: HashSet::new(),
|
||||
active_drag: None,
|
||||
save_timer: 0.0,
|
||||
dirty: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HierarchyPanelState {
|
||||
pub fn from_prefs(prefs: &UserPreferences) -> Self {
|
||||
let mut state = Self::default();
|
||||
state.filter = prefs.hierarchy_filter.clone();
|
||||
state.show_generated = prefs.hierarchy_show_generated;
|
||||
state.show_runtime = prefs.hierarchy_show_runtime;
|
||||
state.sort_mode = prefs.hierarchy_sort_mode;
|
||||
state
|
||||
}
|
||||
|
||||
pub fn mark_dirty(&mut self) {
|
||||
self.dirty = true;
|
||||
self.save_timer = 1.0;
|
||||
}
|
||||
|
||||
pub fn toggle_expanded(&mut self, entity: Entity, path: &str, prefs: &mut UserPreferences) {
|
||||
if self.expanded.contains(&entity) {
|
||||
self.expanded.remove(&entity);
|
||||
prefs.hierarchy_expanded_paths.retain(|entry| entry != path);
|
||||
} else {
|
||||
self.expanded.insert(entity);
|
||||
if !prefs
|
||||
.hierarchy_expanded_paths
|
||||
.iter()
|
||||
.any(|entry| entry == path)
|
||||
{
|
||||
prefs.hierarchy_expanded_paths.push(path.to_string());
|
||||
}
|
||||
}
|
||||
self.mark_dirty();
|
||||
}
|
||||
|
||||
pub fn sync_expanded_from_paths(&mut self, world: &mut World, paths: &[String]) {
|
||||
self.expanded = expanded_entities_for_paths(world, paths);
|
||||
}
|
||||
|
||||
fn flush_prefs(&mut self, prefs: &mut UserPreferences) {
|
||||
prefs.hierarchy_filter = self.filter.clone();
|
||||
prefs.hierarchy_show_generated = self.show_generated;
|
||||
prefs.hierarchy_show_runtime = self.show_runtime;
|
||||
prefs.hierarchy_sort_mode = self.sort_mode;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expanded_entities_for_paths(world: &mut World, paths: &[String]) -> HashSet<Entity> {
|
||||
use super::hierarchy_ops::entity_hierarchy_path;
|
||||
|
||||
let mut expanded = HashSet::new();
|
||||
if paths.is_empty() {
|
||||
return expanded;
|
||||
}
|
||||
let mut query = world.query_filtered::<Entity, With<shared::LevelObject>>();
|
||||
for entity in query.iter(world) {
|
||||
let path = entity_hierarchy_path(world, entity);
|
||||
if paths.iter().any(|entry| entry == &path) {
|
||||
expanded.insert(entity);
|
||||
}
|
||||
}
|
||||
expanded
|
||||
}
|
||||
|
||||
pub fn tick_hierarchy_prefs_save(
|
||||
mut state: ResMut<HierarchyPanelState>,
|
||||
mut prefs: ResMut<UserPreferences>,
|
||||
time: Res<Time>,
|
||||
) {
|
||||
if !state.dirty {
|
||||
return;
|
||||
}
|
||||
state.save_timer -= time.delta_secs();
|
||||
if state.save_timer > 0.0 {
|
||||
return;
|
||||
}
|
||||
state.flush_prefs(&mut prefs);
|
||||
if let Err(err) = write_user_preferences(&prefs) {
|
||||
warn!("Failed to save hierarchy preferences: {err}");
|
||||
} else {
|
||||
state.dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_hierarchy_prefs(world: &mut World, prefs: &UserPreferences) {
|
||||
if !world.contains_resource::<HierarchyPanelState>() {
|
||||
return;
|
||||
}
|
||||
let paths = prefs.hierarchy_expanded_paths.clone();
|
||||
let expanded = expanded_entities_for_paths(world, &paths);
|
||||
let mut state = world.resource_mut::<HierarchyPanelState>();
|
||||
state.filter = prefs.hierarchy_filter.clone();
|
||||
state.show_generated = prefs.hierarchy_show_generated;
|
||||
state.show_runtime = prefs.hierarchy_show_runtime;
|
||||
state.sort_mode = prefs.hierarchy_sort_mode;
|
||||
state.expanded = expanded;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,145 @@
|
||||
//! Dock layout persistence in user preferences.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use egui_dock::{DockState, NodeIndex};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::project_io::{write_user_preferences, UserPreferences};
|
||||
|
||||
use super::dock_tabs::{normalize_unified_viewport_tabs, PanelNodes};
|
||||
use super::EditorTab;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DockLayoutSnapshot {
|
||||
pub dock_state: DockState<EditorTab>,
|
||||
pub main_view_node: usize,
|
||||
#[serde(default)]
|
||||
pub panel_nodes: Option<PanelNodes>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct LayoutSaveTimer {
|
||||
pub seconds_until_save: f32,
|
||||
pub last_serialized: Option<String>,
|
||||
}
|
||||
|
||||
const SAVE_DEBOUNCE_SECS: f32 = 1.0;
|
||||
|
||||
pub fn default_dock_layout() -> DockLayoutSnapshot {
|
||||
let mut dock_state = DockState::new(vec![EditorTab::Viewport]);
|
||||
let tree = dock_state.main_surface_mut();
|
||||
let [main_view_node, inspector_node] =
|
||||
tree.split_right(NodeIndex::root(), 0.76, vec![EditorTab::Inspector]);
|
||||
let [main_view_node, hierarchy_node] =
|
||||
tree.split_left(main_view_node, 0.2, vec![EditorTab::Hierarchy]);
|
||||
let [main_view_node, bottom_node] =
|
||||
tree.split_below(main_view_node, 0.88, vec![EditorTab::AssetBrowser]);
|
||||
|
||||
let panel_nodes = PanelNodes {
|
||||
main_view: main_view_node.0,
|
||||
hierarchy: hierarchy_node.0,
|
||||
inspector: inspector_node.0,
|
||||
bottom: bottom_node.0,
|
||||
};
|
||||
|
||||
DockLayoutSnapshot {
|
||||
dock_state,
|
||||
main_view_node: main_view_node.0,
|
||||
panel_nodes: Some(panel_nodes),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_dock_layout(prefs: &UserPreferences) -> DockLayoutSnapshot {
|
||||
let Some(text) = prefs.dock_layout.as_ref() else {
|
||||
return default_dock_layout();
|
||||
};
|
||||
let mut snapshot: DockLayoutSnapshot =
|
||||
ron::from_str(text).unwrap_or_else(|_| default_dock_layout());
|
||||
normalize_unified_viewport_tabs(&mut snapshot.dock_state);
|
||||
if snapshot.panel_nodes.is_none() {
|
||||
let fallback = PanelNodes {
|
||||
main_view: snapshot.main_view_node,
|
||||
hierarchy: snapshot.main_view_node,
|
||||
inspector: snapshot.main_view_node,
|
||||
bottom: snapshot.main_view_node,
|
||||
};
|
||||
snapshot.panel_nodes = Some(PanelNodes::discover(&snapshot.dock_state, fallback));
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
|
||||
pub fn serialize_dock_layout(
|
||||
dock_state: &DockState<EditorTab>,
|
||||
main_view_node: NodeIndex,
|
||||
panel_nodes: PanelNodes,
|
||||
) -> String {
|
||||
let snapshot = DockLayoutSnapshot {
|
||||
dock_state: dock_state.clone(),
|
||||
main_view_node: main_view_node.0,
|
||||
panel_nodes: Some(panel_nodes),
|
||||
};
|
||||
ron::ser::to_string(&snapshot).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn mark_layout_dirty_if_changed(
|
||||
world: &mut World,
|
||||
dock_state: &DockState<EditorTab>,
|
||||
main_view_node: NodeIndex,
|
||||
panel_nodes: PanelNodes,
|
||||
) {
|
||||
let serialized = serialize_dock_layout(dock_state, main_view_node, panel_nodes);
|
||||
let mut timer = world.resource_mut::<LayoutSaveTimer>();
|
||||
if timer.last_serialized.as_ref() == Some(&serialized) {
|
||||
return;
|
||||
}
|
||||
timer.last_serialized = Some(serialized);
|
||||
timer.seconds_until_save = SAVE_DEBOUNCE_SECS;
|
||||
world
|
||||
.resource_mut::<crate::project_io::ProjectWorkspace>()
|
||||
.layout_dirty = true;
|
||||
}
|
||||
|
||||
pub fn tick_layout_save(world: &mut World, dt: f32) {
|
||||
let mut timer = world.resource_mut::<LayoutSaveTimer>();
|
||||
if timer.seconds_until_save <= 0.0 {
|
||||
return;
|
||||
}
|
||||
timer.seconds_until_save -= dt;
|
||||
if timer.seconds_until_save > 0.0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(serialized) = timer.last_serialized.clone() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut prefs = world.resource_mut::<UserPreferences>();
|
||||
prefs.dock_layout = Some(serialized);
|
||||
if let Err(err) = write_user_preferences(&prefs) {
|
||||
warn!("Failed to save editor layout: {err}");
|
||||
} else {
|
||||
world
|
||||
.resource_mut::<crate::project_io::ProjectWorkspace>()
|
||||
.layout_dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset_and_save_layout(world: &mut World) -> DockLayoutSnapshot {
|
||||
let layout = default_dock_layout();
|
||||
let serialized = ron::ser::to_string(&layout).unwrap_or_default();
|
||||
|
||||
{
|
||||
let mut prefs = world.resource_mut::<UserPreferences>();
|
||||
prefs.dock_layout = Some(serialized.clone());
|
||||
let _ = write_user_preferences(&prefs);
|
||||
}
|
||||
|
||||
let mut timer = world.resource_mut::<LayoutSaveTimer>();
|
||||
timer.last_serialized = Some(serialized);
|
||||
timer.seconds_until_save = 0.0;
|
||||
world
|
||||
.resource_mut::<crate::project_io::ProjectWorkspace>()
|
||||
.layout_dirty = false;
|
||||
|
||||
layout
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Top menu bar.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use egui_dock::DockState;
|
||||
|
||||
use crate::history::{apply_command_redo, apply_command_undo, EditorHistory};
|
||||
use crate::scene_io::{SceneIo, SceneIoRequest};
|
||||
use crate::settings_ui::{open_project_settings_panel, ProjectSettingsPanel};
|
||||
use crate::state::{EditorMode, PlayPaused};
|
||||
use crate::workspace::{request_new_project, request_open_project};
|
||||
|
||||
use super::diagnostics::DiagnosticsPanel;
|
||||
use super::dock_tabs::{open_and_focus_tab, tab_is_open, tab_label, PanelNodes, PANEL_TABS};
|
||||
use super::helpers::{
|
||||
delete_selection, duplicate_selection, toggle_play_mode, toggle_play_paused, toggle_possession,
|
||||
};
|
||||
use super::layout::reset_and_save_layout;
|
||||
use super::widgets::menu_item;
|
||||
use super::EditorTab;
|
||||
|
||||
pub fn top_menu_bar(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
selected: &SelectedEntities,
|
||||
dock_state: &mut DockState<EditorTab>,
|
||||
panel_nodes: &mut PanelNodes,
|
||||
) {
|
||||
egui::TopBottomPanel::top("editor_menu_bar").show(ctx, |ui| {
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
ui.menu_button("File", |ui| {
|
||||
ui.menu_button("Project", |ui| {
|
||||
if menu_item(ui, "New Project", None, true).clicked() {
|
||||
request_new_project(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Open Project...", None, true).clicked() {
|
||||
request_open_project(world);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
if menu_item(ui, "New Scene", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::New);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Open Scene...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Open);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Save", Some("Ctrl+S"), true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Save);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Save Scene As...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::SaveAs);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if menu_item(ui, "Import Assets...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::ImportAssets);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Export Selection...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::ExportSelection);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Save Selection As Prefab...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request =
|
||||
Some(SceneIoRequest::SaveSelectionAsPrefab);
|
||||
ui.close();
|
||||
}
|
||||
let recent: Vec<(usize, String)> = world
|
||||
.resource::<SceneIo>()
|
||||
.recent_paths
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, path)| (index, path.display().to_string()))
|
||||
.collect();
|
||||
if !recent.is_empty() {
|
||||
ui.separator();
|
||||
ui.menu_button("Recent Scenes", |ui| {
|
||||
for (index, label) in recent {
|
||||
if menu_item(ui, &label, None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request =
|
||||
Some(SceneIoRequest::OpenRecent(index));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Edit", |ui| {
|
||||
if menu_item(ui, "Project Settings...", None, true).clicked() {
|
||||
open_project_settings_panel(&mut world.resource_mut::<ProjectSettingsPanel>());
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let can_undo = world.resource::<EditorHistory>().can_undo();
|
||||
let can_redo = world.resource::<EditorHistory>().can_redo();
|
||||
if menu_item(ui, "Undo", Some("Ctrl+Z"), can_undo).clicked() {
|
||||
apply_command_undo(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Redo", Some("Ctrl+Y"), can_redo).clicked() {
|
||||
apply_command_redo(world);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let has_selection = !selected.as_slice().is_empty();
|
||||
if menu_item(ui, "Duplicate", Some("Ctrl+D"), has_selection).clicked() {
|
||||
duplicate_selection(world, selected);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Delete", Some("Del"), has_selection).clicked() {
|
||||
delete_selection(world, selected);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Scene", |ui| {
|
||||
if menu_item(ui, "Lighting → Use project sun", None, true).clicked() {
|
||||
super::helpers::use_project_sun(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Lighting → Bake scene sun from project", None, true).clicked() {
|
||||
super::helpers::create_scene_sun_override_from_project_settings(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Create → Post Process Volume", None, true).clicked() {
|
||||
crate::rendering_diagnostics::spawn_post_process_volume_at_camera(world);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("View", |ui| {
|
||||
if menu_item(ui, "Reset Layout", None, true).clicked() {
|
||||
let layout = reset_and_save_layout(world);
|
||||
*dock_state = layout.dock_state;
|
||||
if let Some(nodes) = layout.panel_nodes {
|
||||
*panel_nodes = nodes;
|
||||
}
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Window", |ui| {
|
||||
for tab in PANEL_TABS {
|
||||
let open = tab_is_open(dock_state, &tab);
|
||||
if ui.selectable_label(open, tab_label(&tab)).clicked() {
|
||||
open_and_focus_tab(dock_state, tab, panel_nodes);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
let mut diagnostics = world.resource_mut::<DiagnosticsPanel>();
|
||||
if ui.checkbox(&mut diagnostics.open, "Diagnostics").clicked() {
|
||||
ui.close();
|
||||
}
|
||||
let mut rendering =
|
||||
world.resource_mut::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>();
|
||||
if ui.checkbox(&mut rendering.open, "Rendering").clicked() {
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Play", |ui| {
|
||||
let playing = *world.resource::<State<EditorMode>>().get() == EditorMode::Playing;
|
||||
let paused = world.resource::<PlayPaused>().0;
|
||||
if menu_item(ui, "Toggle Play/Edit", Some("F5"), true).clicked() {
|
||||
toggle_play_mode(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Pause / Resume", Some("F6"), playing).clicked() {
|
||||
toggle_play_paused(world);
|
||||
ui.close();
|
||||
}
|
||||
let possess_label = if playing {
|
||||
"Possess / Eject"
|
||||
} else {
|
||||
"Possess / Eject (while playing)"
|
||||
};
|
||||
if menu_item(ui, possess_label, Some("F8"), playing).clicked() {
|
||||
toggle_possession(world);
|
||||
ui.close();
|
||||
}
|
||||
if playing && paused {
|
||||
ui.label("Simulation paused");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
mod actor_inspector;
|
||||
mod asset_browser;
|
||||
mod component_registry;
|
||||
mod diagnostics;
|
||||
mod dock_tabs;
|
||||
mod fonts;
|
||||
pub(crate) mod helpers;
|
||||
mod hierarchy;
|
||||
pub mod hierarchy_ops;
|
||||
pub mod hierarchy_state;
|
||||
pub(crate) mod inspector;
|
||||
mod layout;
|
||||
mod menu;
|
||||
mod play_controls;
|
||||
mod post_process_volume_ui;
|
||||
pub mod selection_ops;
|
||||
mod status_bar;
|
||||
pub(crate) mod theme;
|
||||
mod toolbar;
|
||||
mod viewport_chrome;
|
||||
mod widgets;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
|
||||
use bevy_egui::{egui, EguiContext, EguiPrimaryContextPass, PrimaryEguiContext};
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use egui_dock::{DockArea, DockState};
|
||||
use egui_phosphor_icons::icons;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::project_io::UserPreferences;
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::state::EditorMode;
|
||||
|
||||
pub use diagnostics::DiagnosticsPanel;
|
||||
pub use layout::LayoutSaveTimer;
|
||||
pub use viewport_chrome::ViewportUiState;
|
||||
|
||||
use diagnostics::diagnostics_window;
|
||||
use dock_tabs::PanelNodes;
|
||||
use hierarchy_state::HierarchyPanelState;
|
||||
use layout::{load_dock_layout, mark_layout_dirty_if_changed, tick_layout_save};
|
||||
use menu::top_menu_bar;
|
||||
use status_bar::status_bar_ui;
|
||||
use theme::{apply_editor_theme, editor_dock_style};
|
||||
use toolbar::editor_toolbar_panel;
|
||||
use viewport_chrome::viewport_tab_ui;
|
||||
|
||||
use crate::settings_ui::{project_settings_window, ProjectSettingsPanel};
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct UiState {
|
||||
pub dock_state: DockState<EditorTab>,
|
||||
pub viewport_rect: egui::Rect,
|
||||
pub pointer_in_viewport: bool,
|
||||
/// Pointer position inside the viewport image (logical screen coords), for picking.
|
||||
pub viewport_pointer_pos: Option<egui::Pos2>,
|
||||
pub selected_entities: SelectedEntities,
|
||||
pub renaming_entity: Option<Entity>,
|
||||
pub rename_buffer: String,
|
||||
pub(crate) inspector_collapsed_components: HashSet<String>,
|
||||
pub(crate) panel_nodes: PanelNodes,
|
||||
last_mode_tab: Option<EditorMode>,
|
||||
}
|
||||
|
||||
impl UiState {
|
||||
pub fn default_layout() -> Self {
|
||||
Self::from_prefs(&UserPreferences::default())
|
||||
}
|
||||
|
||||
pub fn from_prefs(prefs: &UserPreferences) -> Self {
|
||||
let layout = load_dock_layout(prefs);
|
||||
let fallback_nodes = layout.panel_nodes.unwrap_or(PanelNodes {
|
||||
main_view: layout.main_view_node,
|
||||
hierarchy: layout.main_view_node,
|
||||
inspector: layout.main_view_node,
|
||||
bottom: layout.main_view_node,
|
||||
});
|
||||
let panel_nodes = PanelNodes::discover(&layout.dock_state, fallback_nodes);
|
||||
Self {
|
||||
dock_state: layout.dock_state,
|
||||
viewport_rect: egui::Rect::NOTHING,
|
||||
pointer_in_viewport: false,
|
||||
viewport_pointer_pos: None,
|
||||
selected_entities: SelectedEntities::default(),
|
||||
renaming_entity: None,
|
||||
rename_buffer: String::new(),
|
||||
inspector_collapsed_components: HashSet::new(),
|
||||
panel_nodes,
|
||||
last_mode_tab: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ui(&mut self, world: &mut World, ctx: &mut egui::Context, dt: f32) {
|
||||
apply_editor_theme(ctx);
|
||||
|
||||
let mode = *world.resource::<State<EditorMode>>().get();
|
||||
if self.last_mode_tab != Some(mode) {
|
||||
self.last_mode_tab = Some(mode);
|
||||
if mode == EditorMode::Playing {
|
||||
dock_tabs::ensure_viewport_for_play(&mut self.dock_state, &self.panel_nodes);
|
||||
}
|
||||
}
|
||||
|
||||
top_menu_bar(
|
||||
world,
|
||||
ctx,
|
||||
&self.selected_entities,
|
||||
&mut self.dock_state,
|
||||
&mut self.panel_nodes,
|
||||
);
|
||||
|
||||
editor_toolbar_panel(world, ctx);
|
||||
|
||||
self.pointer_in_viewport = false;
|
||||
self.viewport_pointer_pos = None;
|
||||
|
||||
let playing = mode == EditorMode::Playing;
|
||||
let cursor_grabbed = world
|
||||
.query_filtered::<&CursorOptions, With<PrimaryWindow>>()
|
||||
.single(world)
|
||||
.is_ok_and(|cursor| cursor.grab_mode != CursorGrabMode::None);
|
||||
if playing && cursor_grabbed {
|
||||
ctx.input_mut(|input| {
|
||||
input.focused = false;
|
||||
});
|
||||
}
|
||||
|
||||
let mut viewer = TabViewer {
|
||||
world,
|
||||
viewport_rect: &mut self.viewport_rect,
|
||||
pointer_in_viewport: &mut self.pointer_in_viewport,
|
||||
viewport_pointer_pos: &mut self.viewport_pointer_pos,
|
||||
playing,
|
||||
cursor_grabbed,
|
||||
selected_entities: &mut self.selected_entities,
|
||||
renaming_entity: &mut self.renaming_entity,
|
||||
rename_buffer: &mut self.rename_buffer,
|
||||
};
|
||||
|
||||
DockArea::new(&mut self.dock_state)
|
||||
.style(editor_dock_style(ctx))
|
||||
.show(ctx, &mut viewer);
|
||||
|
||||
self.panel_nodes = PanelNodes::discover(&self.dock_state, self.panel_nodes);
|
||||
|
||||
mark_layout_dirty_if_changed(
|
||||
world,
|
||||
&self.dock_state,
|
||||
self.panel_nodes.main_view(),
|
||||
self.panel_nodes,
|
||||
);
|
||||
tick_layout_save(world, dt);
|
||||
|
||||
status_bar_ui(world, ctx, &self.selected_entities, mode);
|
||||
|
||||
let mut diagnostics_open = world.resource::<DiagnosticsPanel>().open;
|
||||
diagnostics_window(world, ctx, &mut diagnostics_open);
|
||||
world.resource_mut::<DiagnosticsPanel>().open = diagnostics_open;
|
||||
|
||||
let mut rendering_open = world
|
||||
.resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
|
||||
.open;
|
||||
crate::rendering_diagnostics::rendering_diagnostics_window(world, ctx, &mut rendering_open);
|
||||
world
|
||||
.resource_mut::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
|
||||
.open = rendering_open;
|
||||
|
||||
world.resource_scope(|world, mut panel: Mut<ProjectSettingsPanel>| {
|
||||
project_settings_window(world, ctx, &mut panel);
|
||||
});
|
||||
|
||||
if ctx.input(|input| input.key_pressed(egui::Key::F1)) {
|
||||
world.resource_mut::<ViewportUiState>().shortcuts_open = true;
|
||||
}
|
||||
|
||||
let selected = self.selected_entities.as_slice().first().copied();
|
||||
world.resource_mut::<SelectedEntity>().0 = selected;
|
||||
}
|
||||
}
|
||||
|
||||
fn tab_title(icon: egui_phosphor_icons::Icon, label: &str) -> egui::WidgetText {
|
||||
let mut job = egui::text::LayoutJob::default();
|
||||
job.append(
|
||||
icon.as_str(),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::new(13.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
color: theme::TEXT,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
job.append(
|
||||
&format!(" {label}"),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::new(13.0, egui::FontFamily::Proportional),
|
||||
color: theme::TEXT,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
job.into()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum EditorTab {
|
||||
Viewport,
|
||||
/// Legacy saved-layout tab. Loaded layouts are migrated to [`EditorTab::Viewport`].
|
||||
GameView,
|
||||
Hierarchy,
|
||||
Inspector,
|
||||
Toolbar,
|
||||
AssetBrowser,
|
||||
}
|
||||
|
||||
pub struct EditorUiPlugin;
|
||||
|
||||
impl Plugin for EditorUiPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_resource(UiState::default_layout())
|
||||
.add_plugins(fonts::EditorFontsPlugin)
|
||||
.init_resource::<DiagnosticsPanel>()
|
||||
.init_resource::<component_registry::EditorComponentRegistry>()
|
||||
.init_resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
|
||||
.init_resource::<asset_browser::AssetBrowserUiState>()
|
||||
.init_resource::<inspector::InspectorClipboard>()
|
||||
.init_resource::<ViewportUiState>()
|
||||
.init_resource::<LayoutSaveTimer>()
|
||||
.add_systems(
|
||||
Startup,
|
||||
init_hierarchy_panel_from_prefs
|
||||
.after(crate::project_io::load_user_preferences_on_startup),
|
||||
)
|
||||
.add_systems(
|
||||
Startup,
|
||||
apply_ui_state_from_prefs
|
||||
.after(crate::project_io::load_user_preferences_on_startup),
|
||||
)
|
||||
.add_systems(EguiPrimaryContextPass, show_ui_system)
|
||||
.add_systems(Update, hierarchy_state::tick_hierarchy_prefs_save);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_ui_state_from_prefs(mut ui_state: ResMut<UiState>, prefs: Res<UserPreferences>) {
|
||||
*ui_state = UiState::from_prefs(&prefs);
|
||||
}
|
||||
|
||||
fn init_hierarchy_panel_from_prefs(mut commands: Commands, prefs: Res<UserPreferences>) {
|
||||
commands.insert_resource(HierarchyPanelState::from_prefs(&prefs));
|
||||
}
|
||||
|
||||
pub(crate) fn show_ui_system(world: &mut World) {
|
||||
let Ok(egui_context) = world
|
||||
.query_filtered::<&mut EguiContext, With<PrimaryEguiContext>>()
|
||||
.single(world)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut egui_context = egui_context.clone();
|
||||
let dt = world
|
||||
.get_resource::<Time>()
|
||||
.map(|time| time.delta_secs())
|
||||
.unwrap_or(0.0);
|
||||
|
||||
world.resource_scope::<UiState, _>(|world, mut ui_state| {
|
||||
ui_state.ui(world, egui_context.get_mut(), dt);
|
||||
});
|
||||
}
|
||||
|
||||
struct TabViewer<'a> {
|
||||
world: &'a mut World,
|
||||
viewport_rect: &'a mut egui::Rect,
|
||||
pointer_in_viewport: &'a mut bool,
|
||||
viewport_pointer_pos: &'a mut Option<egui::Pos2>,
|
||||
playing: bool,
|
||||
cursor_grabbed: bool,
|
||||
selected_entities: &'a mut SelectedEntities,
|
||||
renaming_entity: &'a mut Option<Entity>,
|
||||
rename_buffer: &'a mut String,
|
||||
}
|
||||
|
||||
impl egui_dock::TabViewer for TabViewer<'_> {
|
||||
type Tab = EditorTab;
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, tab: &mut Self::Tab) {
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => {
|
||||
viewport_tab_ui(
|
||||
self.world,
|
||||
ui,
|
||||
self.viewport_rect,
|
||||
self.pointer_in_viewport,
|
||||
self.viewport_pointer_pos,
|
||||
self.selected_entities,
|
||||
self.playing,
|
||||
self.cursor_grabbed,
|
||||
);
|
||||
}
|
||||
EditorTab::Hierarchy => {
|
||||
hierarchy::hierarchy_panel_ui(
|
||||
self.world,
|
||||
ui,
|
||||
self.selected_entities,
|
||||
self.renaming_entity,
|
||||
self.rename_buffer,
|
||||
);
|
||||
}
|
||||
EditorTab::Inspector => match self.selected_entities.as_slice() {
|
||||
&[entity] if self.world.get_entity(entity).is_ok() => {
|
||||
actor_inspector::draw_actor_inspector(self.world, ui, entity);
|
||||
}
|
||||
&[entity] => {
|
||||
ui.label(format!("Entity {entity:?} is no longer in the world."));
|
||||
}
|
||||
entities => {
|
||||
actor_inspector::draw_multi_actor_inspector(self.world, ui, entities);
|
||||
}
|
||||
},
|
||||
EditorTab::Toolbar => {
|
||||
ui.label("Toolbar moved below the menu bar (Play, spawn, save).");
|
||||
}
|
||||
EditorTab::AssetBrowser => {
|
||||
asset_browser::asset_browser_ui(self.world, ui, self.selected_entities);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn title(&mut self, tab: &mut Self::Tab) -> egui::WidgetText {
|
||||
let (icon, label) = match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => (icons::FILM_SLATE, "Viewport"),
|
||||
EditorTab::Hierarchy => (icons::LIST_BULLETS, "Hierarchy"),
|
||||
EditorTab::Inspector => (icons::SLIDERS, "Inspector"),
|
||||
EditorTab::Toolbar => (icons::WRENCH, "Toolbar"),
|
||||
EditorTab::AssetBrowser => (icons::FOLDER, "Asset Browser"),
|
||||
};
|
||||
tab_title(icon, label)
|
||||
}
|
||||
|
||||
fn clear_background(&self, tab: &Self::Tab) -> bool {
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => true,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Play mode toggles and possession controls.
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::play::state::{toggle_play_possession_world, EditorMode, PlayPaused};
|
||||
use crate::project_io::UserPreferences;
|
||||
use crate::scene_io::{save_active_or_prompt_world, SceneIo};
|
||||
|
||||
pub fn toggle_play_mode(world: &mut World) {
|
||||
let entering_play = *world.resource::<State<EditorMode>>().get() == EditorMode::Editing;
|
||||
if entering_play {
|
||||
let save_before = world.resource::<UserPreferences>().save_before_play;
|
||||
if save_before && world.resource::<SceneIo>().dirty {
|
||||
let status = save_active_or_prompt_world(world);
|
||||
if status.contains("failed") || status.contains("cancelled") {
|
||||
world.resource_mut::<SceneIo>().status = status;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let next = if entering_play {
|
||||
EditorMode::Playing
|
||||
} else {
|
||||
EditorMode::Editing
|
||||
};
|
||||
world.resource_mut::<NextState<EditorMode>>().set(next);
|
||||
}
|
||||
|
||||
pub fn toggle_play_paused(world: &mut World) {
|
||||
if *world.resource::<State<EditorMode>>().get() != EditorMode::Playing {
|
||||
return;
|
||||
}
|
||||
let mut paused = world.resource_mut::<PlayPaused>();
|
||||
paused.0 = !paused.0;
|
||||
}
|
||||
|
||||
pub fn toggle_possession(world: &mut World) {
|
||||
toggle_play_possession_world(world);
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! Dedicated post-process volume inspector with inherit/override UX.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
use settings::ProjectSettings;
|
||||
use shared::{ColorDesc, PostProcessVolumeDesc, PostProcessVolumeOverrides, RenderingProfileAsset};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::history::set_post_process_volume_with_history;
|
||||
use crate::ui::inspector::{
|
||||
apply_component_card_response, component_card, component_card_context, ComponentCardOptions,
|
||||
};
|
||||
use crate::ui::inspector::{property_row, text_field_width};
|
||||
use crate::ui::theme::panel_heading;
|
||||
|
||||
pub fn post_process_volume_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let Some(mut volume) = world.get::<PostProcessVolumeDesc>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let project = world.resource::<ProjectSettings>().rendering.clone();
|
||||
let original = volume.clone();
|
||||
let mut changed = false;
|
||||
|
||||
let card = component_card_context(
|
||||
world,
|
||||
entity,
|
||||
ComponentCardOptions::removable(
|
||||
shared::COMPONENT_POST_PROCESS_VOLUME,
|
||||
"Post Process Volume",
|
||||
icons::APERTURE,
|
||||
),
|
||||
);
|
||||
let card_response = component_card(ui, &card, |ui| {
|
||||
property_row(ui, "Label (HUD)", |ui| {
|
||||
let mut label_text = volume.label.clone().unwrap_or_default();
|
||||
if ui
|
||||
.add_sized(
|
||||
[text_field_width(ui), 20.0],
|
||||
egui::TextEdit::singleline(&mut label_text),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
volume.label = if label_text.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(label_text)
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
property_row(ui, "Priority", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.priority, -10..=100));
|
||||
});
|
||||
property_row(ui, "Blend distance", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.blend_distance, 0.0..=20.0));
|
||||
});
|
||||
property_row(ui, "Half X", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.half_extents.x, 0.5..=50.0));
|
||||
});
|
||||
property_row(ui, "Half Y", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.half_extents.y, 0.5..=50.0));
|
||||
});
|
||||
property_row(ui, "Half Z", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.half_extents.z, 0.5..=50.0));
|
||||
});
|
||||
if volume.half_extents != original.half_extents
|
||||
|| volume.priority != original.priority
|
||||
|| volume.blend_distance != original.blend_distance
|
||||
|| volume.label != original.label
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
ui.label(panel_heading("Overrides"));
|
||||
changed |= override_f32_ui(
|
||||
ui,
|
||||
"Exposure EV100",
|
||||
&mut volume.overrides.exposure_ev100,
|
||||
project.exposure_ev100,
|
||||
);
|
||||
changed |= override_bool_ui(ui, "HDR", &mut volume.overrides.hdr, project.hdr);
|
||||
changed |= override_bool_ui(
|
||||
ui,
|
||||
"Tonemapping ACES",
|
||||
&mut volume.overrides.tonemapping_aces,
|
||||
project.tonemapping_aces,
|
||||
);
|
||||
changed |= override_bool_ui(ui, "Bloom", &mut volume.overrides.bloom, project.bloom);
|
||||
changed |= override_bool_ui(ui, "TAA", &mut volume.overrides.taa, project.taa);
|
||||
changed |= override_bool_ui(ui, "SSAO", &mut volume.overrides.ssao, project.ssao);
|
||||
changed |= override_bool_ui(
|
||||
ui,
|
||||
"Atmosphere",
|
||||
&mut volume.overrides.atmosphere,
|
||||
project.atmosphere,
|
||||
);
|
||||
changed |= override_fog_ui(ui, &mut volume.overrides, &project);
|
||||
|
||||
ui.separator();
|
||||
ui.label(panel_heading("Fullscreen Effect"));
|
||||
let effects = scan_post_fx_assets();
|
||||
let current = volume.fullscreen_effect.clone().unwrap_or_default();
|
||||
property_row(ui, "Effect", |ui| {
|
||||
egui::ComboBox::from_id_salt("post_process_fullscreen_effect")
|
||||
.selected_text(if current.is_empty() {
|
||||
"None".to_string()
|
||||
} else {
|
||||
current.clone()
|
||||
})
|
||||
.show_ui(ui, |ui| {
|
||||
if ui
|
||||
.selectable_label(volume.fullscreen_effect.is_none(), "None")
|
||||
.clicked()
|
||||
{
|
||||
volume.fullscreen_effect = None;
|
||||
changed = true;
|
||||
}
|
||||
for path in &effects {
|
||||
if ui
|
||||
.selectable_label(
|
||||
volume.fullscreen_effect.as_deref() == Some(path.as_str()),
|
||||
path,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
volume.fullscreen_effect = Some(path.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
ui.label(panel_heading("Preset"));
|
||||
let profiles = scan_rendering_profiles();
|
||||
property_row(ui, "Profile", |ui| {
|
||||
egui::ComboBox::from_id_salt("post_process_profile")
|
||||
.selected_text(volume.profile.clone().unwrap_or_else(|| "None".to_string()))
|
||||
.show_ui(ui, |ui| {
|
||||
if ui
|
||||
.selectable_label(volume.profile.is_none(), "None")
|
||||
.clicked()
|
||||
{
|
||||
volume.profile = None;
|
||||
changed = true;
|
||||
}
|
||||
for path in &profiles {
|
||||
if ui
|
||||
.selectable_label(
|
||||
volume.profile.as_deref() == Some(path.as_str()),
|
||||
path,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
volume.profile = Some(path.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button("Apply preset").clicked() {
|
||||
if let Some(path) = &volume.profile {
|
||||
if let Ok(preset) = RenderingProfileAsset::load_from_path(path) {
|
||||
volume.overrides = preset.overrides;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ui.button("Revert to preset").clicked() {
|
||||
if let Some(path) = &volume.profile {
|
||||
if let Ok(preset) = RenderingProfileAsset::load_from_path(path) {
|
||||
volume.overrides = preset.overrides;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
apply_component_card_response(world, entity, card_response);
|
||||
|
||||
if changed {
|
||||
set_post_process_volume_with_history(world, entity, volume);
|
||||
}
|
||||
}
|
||||
|
||||
fn override_bool_ui(
|
||||
ui: &mut egui::Ui,
|
||||
label: &str,
|
||||
field: &mut Option<bool>,
|
||||
inherited: bool,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
property_row(ui, label, |ui| {
|
||||
let mut overriding = field.is_some();
|
||||
if ui.checkbox(&mut overriding, "Override").changed() {
|
||||
*field = if overriding { Some(inherited) } else { None };
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if let Some(value) = field.as_mut() {
|
||||
property_row(ui, "Value", |ui| {
|
||||
if ui.checkbox(value, "Enabled").changed() {
|
||||
changed = true;
|
||||
}
|
||||
if ui.small_button("Reset to project").clicked() {
|
||||
*value = inherited;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
property_row(ui, "Inherited", |ui| {
|
||||
ui.label(if inherited { "on" } else { "off" });
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn override_f32_ui(
|
||||
ui: &mut egui::Ui,
|
||||
label: &str,
|
||||
field: &mut Option<f32>,
|
||||
inherited: f32,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
property_row(ui, label, |ui| {
|
||||
let mut overriding = field.is_some();
|
||||
if ui.checkbox(&mut overriding, "Override").changed() {
|
||||
*field = if overriding { Some(inherited) } else { None };
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if let Some(value) = field.as_mut() {
|
||||
property_row(ui, "Value", |ui| {
|
||||
if ui.add(egui::Slider::new(value, 0.0..=20.0)).changed() {
|
||||
changed = true;
|
||||
}
|
||||
if ui.small_button("Reset to project").clicked() {
|
||||
*value = inherited;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
property_row(ui, "Inherited", |ui| {
|
||||
ui.label(format!("{inherited:.2}"));
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn override_fog_ui(
|
||||
ui: &mut egui::Ui,
|
||||
overrides: &mut PostProcessVolumeOverrides,
|
||||
project: &settings::RenderingSettings,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
property_row(ui, "Fog density", |ui| {
|
||||
let mut overriding = overrides.fog_density.is_some();
|
||||
if ui.checkbox(&mut overriding, "Override").changed() {
|
||||
overrides.fog_density = if overriding {
|
||||
Some(project.fog_density)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if let Some(density) = overrides.fog_density.as_mut() {
|
||||
property_row(ui, "Density", |ui| {
|
||||
if ui
|
||||
.add(egui::Slider::new(density, 0.0..=0.01).logarithmic(true))
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
property_row(ui, "Inherited", |ui| {
|
||||
ui.label(format!("{:.4}", project.fog_density));
|
||||
});
|
||||
}
|
||||
|
||||
property_row(ui, "Fog color", |ui| {
|
||||
let mut overriding = overrides.fog_color.is_some();
|
||||
if ui.checkbox(&mut overriding, "Override").changed() {
|
||||
overrides.fog_color = if overriding {
|
||||
Some(ColorDesc::srgb(
|
||||
project.fog_color[0],
|
||||
project.fog_color[1],
|
||||
project.fog_color[2],
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if let Some(color) = overrides.fog_color.as_mut() {
|
||||
property_row(ui, "Color", |ui| {
|
||||
let mut rgb = [color.r, color.g, color.b];
|
||||
if ui.color_edit_button_rgb(&mut rgb).changed() {
|
||||
color.r = rgb[0];
|
||||
color.g = rgb[1];
|
||||
color.b = rgb[2];
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
property_row(ui, "Inherited", |ui| {
|
||||
ui.label(format!(
|
||||
"({:.2}, {:.2}, {:.2})",
|
||||
project.fog_color[0], project.fog_color[1], project.fog_color[2]
|
||||
));
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn scan_post_fx_assets() -> Vec<String> {
|
||||
scan_ron_dir("assets/post_fx")
|
||||
}
|
||||
|
||||
fn scan_rendering_profiles() -> Vec<String> {
|
||||
scan_ron_dir("assets/rendering_profiles")
|
||||
}
|
||||
|
||||
fn scan_ron_dir(root: &str) -> Vec<String> {
|
||||
let mut paths = Vec::new();
|
||||
for entry in WalkDir::new(root).into_iter().filter_map(Result::ok) {
|
||||
if entry.file_type().is_file()
|
||||
&& entry.path().extension().and_then(|e| e.to_str()) == Some("ron")
|
||||
{
|
||||
let path = entry.path().to_string_lossy().replace('\\', "/");
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
paths.sort();
|
||||
paths
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Reflect-driven inspector undo bridge (H2) — scoped to `shared` components.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
|
||||
use shared::LevelObject;
|
||||
|
||||
/// Generic reflect inspector with undo for whitelisted authoring components.
|
||||
pub fn reflect_inspector_ui(_world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
if _world
|
||||
.get_entity(entity)
|
||||
.is_ok_and(|e| e.contains::<LevelObject>())
|
||||
{
|
||||
ui.small("Reflect undo bridge: use typed inspectors for shared components.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Selection delete/duplicate and camera focus helpers.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use shared::LevelObject;
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::history::{delete_entities_with_history, duplicate_entities_with_history};
|
||||
use crate::selection::SelectedEntity;
|
||||
|
||||
pub fn focus_editor_camera_on_selection(world: &mut World) {
|
||||
let Some(entity) = world.resource::<SelectedEntity>().0 else {
|
||||
return;
|
||||
};
|
||||
let Some(target) = world.get::<GlobalTransform>(entity) else {
|
||||
return;
|
||||
};
|
||||
let center = target.translation();
|
||||
let mut cameras = world.query_filtered::<&mut Transform, With<EditorCamera>>();
|
||||
for mut transform in cameras.iter_mut(world) {
|
||||
let offset = transform.translation - center;
|
||||
let distance = offset.length().max(8.0);
|
||||
transform.translation = center - transform.forward().as_vec3() * distance;
|
||||
transform.look_at(center, Vec3::Y);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn selected_level_entities(world: &World, selected: &SelectedEntities) -> Vec<Entity> {
|
||||
selected
|
||||
.iter()
|
||||
.filter(|entity| {
|
||||
world
|
||||
.get_entity(*entity)
|
||||
.is_ok_and(|entity_ref| entity_ref.contains::<LevelObject>())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn entity_name(world: &World, entity: Entity) -> String {
|
||||
world
|
||||
.get::<Name>(entity)
|
||||
.map(|name| name.as_str().to_string())
|
||||
.unwrap_or_else(|| format!("{entity:?}"))
|
||||
}
|
||||
|
||||
pub fn is_level_object(world: &World, entity: Entity) -> bool {
|
||||
world
|
||||
.get_entity(entity)
|
||||
.is_ok_and(|entity_ref| entity_ref.contains::<LevelObject>())
|
||||
}
|
||||
|
||||
pub fn delete_selection(world: &mut World, selected: &SelectedEntities) {
|
||||
let entities = selected_level_entities(world, selected);
|
||||
delete_entities_with_history(world, &entities);
|
||||
}
|
||||
|
||||
pub fn duplicate_selection(world: &mut World, selected: &SelectedEntities) {
|
||||
let entities = selected_level_entities(world, selected);
|
||||
duplicate_entities_with_history(world, &entities);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Fixed bottom status strip.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
|
||||
use crate::history::EditorHistory;
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::state::{EditorMode, PlayPaused};
|
||||
|
||||
use super::theme::{status_bar_frame, TEXT};
|
||||
|
||||
pub fn status_bar_ui(
|
||||
world: &World,
|
||||
ctx: &egui::Context,
|
||||
selected: &SelectedEntities,
|
||||
mode: EditorMode,
|
||||
) {
|
||||
egui::TopBottomPanel::bottom("editor_status_bar")
|
||||
.exact_height(24.0)
|
||||
.frame(status_bar_frame())
|
||||
.show(ctx, |ui| {
|
||||
ui.horizontal_centered(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 16.0;
|
||||
ui.label(egui::RichText::new(scene_line(world)).color(TEXT));
|
||||
|
||||
let mode_label = match mode {
|
||||
EditorMode::Editing => "Edit".to_string(),
|
||||
EditorMode::Playing => {
|
||||
if world.resource::<PlayPaused>().0 {
|
||||
"Play (paused)".to_string()
|
||||
} else {
|
||||
"Play".to_string()
|
||||
}
|
||||
}
|
||||
};
|
||||
ui.label(egui::RichText::new(mode_label).color(TEXT));
|
||||
|
||||
let count = selected.len();
|
||||
let sel = if count == 0 {
|
||||
"None".to_string()
|
||||
} else if count == 1 {
|
||||
"1 selected".to_string()
|
||||
} else {
|
||||
format!("{count} selected")
|
||||
};
|
||||
ui.label(egui::RichText::new(sel).color(TEXT));
|
||||
|
||||
ui.label(
|
||||
egui::RichText::new(world.resource::<EditorHistory>().status.clone())
|
||||
.color(TEXT),
|
||||
);
|
||||
|
||||
#[cfg(feature = "hot-reload")]
|
||||
if let Some(hot) = world.get_resource::<crate::hot_reload::HotReloadState>() {
|
||||
ui.label(egui::RichText::new(hot.label.clone()).color(TEXT));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_line(world: &World) -> String {
|
||||
let scene_io = world.resource::<SceneIo>();
|
||||
let dirty = if scene_io.dirty { " *" } else { "" };
|
||||
format!("Scene: {}{dirty}", scene_io.active_path_label())
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Unity-inspired dark pro theme for editor egui + egui_dock chrome.
|
||||
|
||||
use bevy_egui::egui::{self, Color32, CornerRadius, FontId, Stroke, Visuals};
|
||||
use egui_dock::{Style as DockStyle, TabInteractionStyle, TabStyle};
|
||||
|
||||
pub const PANEL_BG: Color32 = Color32::from_rgb(32, 33, 36);
|
||||
pub const PANEL_BG_DARK: Color32 = Color32::from_rgb(24, 25, 28);
|
||||
pub const WIDGET_BG: Color32 = Color32::from_rgb(42, 43, 47);
|
||||
pub const ELEVATED_BG: Color32 = Color32::from_rgb(55, 57, 63);
|
||||
pub const ACCENT: Color32 = Color32::from_rgb(56, 121, 184);
|
||||
pub const ACCENT_HOVER: Color32 = Color32::from_rgb(72, 143, 211);
|
||||
pub const SELECTION_BG: Color32 = Color32::from_rgb(46, 103, 158);
|
||||
pub const SELECTION_BG_MUTED: Color32 = Color32::from_rgb(43, 75, 108);
|
||||
pub const TEXT: Color32 = Color32::from_rgb(226, 229, 234);
|
||||
pub const TEXT_SELECTED: Color32 = Color32::from_rgb(250, 253, 255);
|
||||
pub const TEXT_DIM: Color32 = Color32::from_rgb(170, 176, 184);
|
||||
pub const TEXT_MUTED: Color32 = Color32::from_rgb(126, 133, 143);
|
||||
pub const BORDER: Color32 = Color32::from_rgb(69, 72, 78);
|
||||
pub const VIEWPORT_OVERLAY: Color32 = Color32::from_rgba_premultiplied(26, 27, 30, 220);
|
||||
|
||||
pub fn apply_editor_theme(ctx: &egui::Context) {
|
||||
let mut visuals = Visuals::dark();
|
||||
visuals.panel_fill = PANEL_BG;
|
||||
visuals.window_fill = WIDGET_BG;
|
||||
visuals.extreme_bg_color = PANEL_BG_DARK;
|
||||
visuals.faint_bg_color = Color32::from_rgb(38, 40, 44);
|
||||
visuals.code_bg_color = PANEL_BG_DARK;
|
||||
visuals.text_edit_bg_color = Some(PANEL_BG_DARK);
|
||||
visuals.weak_text_color = Some(TEXT_MUTED);
|
||||
visuals.widgets.noninteractive.bg_fill = WIDGET_BG;
|
||||
visuals.widgets.noninteractive.fg_stroke = Stroke::new(1.0, TEXT);
|
||||
visuals.widgets.inactive.bg_fill = WIDGET_BG;
|
||||
visuals.widgets.inactive.weak_bg_fill = Color32::from_rgb(47, 49, 54);
|
||||
visuals.widgets.inactive.bg_stroke = Stroke::new(1.0, BORDER);
|
||||
visuals.widgets.inactive.fg_stroke = Stroke::new(1.0, TEXT);
|
||||
visuals.widgets.hovered.bg_fill = ELEVATED_BG;
|
||||
visuals.widgets.hovered.weak_bg_fill = ELEVATED_BG;
|
||||
visuals.widgets.hovered.bg_stroke = Stroke::new(1.0, ACCENT_HOVER);
|
||||
visuals.widgets.hovered.fg_stroke = Stroke::new(1.0, TEXT_SELECTED);
|
||||
visuals.widgets.active.bg_fill = SELECTION_BG;
|
||||
visuals.widgets.active.weak_bg_fill = SELECTION_BG;
|
||||
visuals.widgets.active.bg_stroke = Stroke::new(1.0, ACCENT_HOVER);
|
||||
visuals.widgets.active.fg_stroke = Stroke::new(1.0, TEXT_SELECTED);
|
||||
visuals.widgets.open.bg_fill = ELEVATED_BG;
|
||||
visuals.widgets.open.weak_bg_fill = ELEVATED_BG;
|
||||
visuals.widgets.open.fg_stroke = Stroke::new(1.0, TEXT_SELECTED);
|
||||
visuals.selection.bg_fill = SELECTION_BG;
|
||||
visuals.selection.stroke = Stroke::new(1.0, TEXT_SELECTED);
|
||||
visuals.hyperlink_color = Color32::from_rgb(132, 186, 247);
|
||||
visuals.warn_fg_color = Color32::from_rgb(255, 200, 80);
|
||||
visuals.error_fg_color = Color32::from_rgb(255, 100, 100);
|
||||
visuals.window_stroke = Stroke::new(1.0, BORDER);
|
||||
visuals.window_corner_radius = CornerRadius::same(4);
|
||||
|
||||
let mut style = (*ctx.style()).clone();
|
||||
style.visuals = visuals;
|
||||
style.spacing.item_spacing = egui::vec2(8.0, 6.0);
|
||||
style.spacing.button_padding = egui::vec2(8.0, 4.0);
|
||||
style.spacing.indent = 16.0;
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Body,
|
||||
FontId::new(13.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Button,
|
||||
FontId::new(13.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Heading,
|
||||
FontId::new(15.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
ctx.set_style(style);
|
||||
}
|
||||
|
||||
pub fn editor_dock_style(ctx: &egui::Context) -> DockStyle {
|
||||
let mut style = DockStyle::from_egui(ctx.style().as_ref());
|
||||
style.dock_area_padding = Some(egui::Margin::same(2));
|
||||
style.main_surface_border_stroke = Stroke::new(1.0, BORDER);
|
||||
style.separator.width = 2.0;
|
||||
style.separator.color_idle = BORDER;
|
||||
style.separator.color_hovered = ELEVATED_BG;
|
||||
style.separator.color_dragged = ACCENT_HOVER;
|
||||
|
||||
style.tab_bar.bg_fill = PANEL_BG_DARK;
|
||||
style.tab_bar.height = 26.0;
|
||||
style.tab_bar.hline_color = BORDER;
|
||||
style.tab_bar.corner_radius = CornerRadius::ZERO;
|
||||
|
||||
let active = TabInteractionStyle {
|
||||
outline_color: BORDER,
|
||||
bg_fill: PANEL_BG,
|
||||
text_color: TEXT,
|
||||
corner_radius: CornerRadius::same(3),
|
||||
};
|
||||
let inactive = TabInteractionStyle {
|
||||
outline_color: Color32::TRANSPARENT,
|
||||
bg_fill: WIDGET_BG,
|
||||
text_color: TEXT_DIM,
|
||||
corner_radius: CornerRadius::same(3),
|
||||
};
|
||||
let hovered = TabInteractionStyle {
|
||||
outline_color: BORDER,
|
||||
bg_fill: ELEVATED_BG,
|
||||
text_color: TEXT,
|
||||
corner_radius: CornerRadius::same(3),
|
||||
};
|
||||
|
||||
style.tab = TabStyle {
|
||||
active: active.clone(),
|
||||
inactive: inactive.clone(),
|
||||
focused: active.clone(),
|
||||
hovered,
|
||||
inactive_with_kb_focus: inactive.clone(),
|
||||
active_with_kb_focus: active.clone(),
|
||||
focused_with_kb_focus: active,
|
||||
..style.tab
|
||||
};
|
||||
|
||||
style
|
||||
}
|
||||
|
||||
pub fn panel_heading(text: &str) -> egui::RichText {
|
||||
egui::RichText::new(text).strong().color(TEXT)
|
||||
}
|
||||
|
||||
pub fn status_bar_frame() -> egui::Frame {
|
||||
egui::Frame::new()
|
||||
.fill(Color32::from_rgb(0, 122, 204))
|
||||
.inner_margin(egui::Margin::symmetric(8, 2))
|
||||
}
|
||||
|
||||
pub fn viewport_toolbar_frame() -> egui::Frame {
|
||||
egui::Frame::new()
|
||||
.fill(VIEWPORT_OVERLAY)
|
||||
.corner_radius(CornerRadius::same(4))
|
||||
.inner_margin(egui::Margin::same(4))
|
||||
.stroke(Stroke::new(1.0, BORDER))
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Top editor toolbar (below menu bar): spawn/file left, transport center.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::history::spawn_with_history;
|
||||
use crate::scene_io::{SceneIo, SceneIoRequest};
|
||||
use crate::state::{EditorMode, PlayPaused, PlayPossession};
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::{editor_spawn_ground_position, snap_translation, ViewportSettings};
|
||||
use shared::PrimitiveShape;
|
||||
|
||||
use super::helpers::{
|
||||
light_snapshot, primitive_snapshot, toggle_play_mode, toggle_play_paused, toggle_possession,
|
||||
};
|
||||
use super::widgets::{icon_button, panel_toolbar_row, toolbar_separator, transport_button_large};
|
||||
|
||||
/// Toolbar strip height (menu bar is separate).
|
||||
const TOOLBAR_HEIGHT: f32 = 56.0;
|
||||
|
||||
pub fn editor_toolbar_panel(world: &mut World, ctx: &egui::Context) {
|
||||
egui::TopBottomPanel::top("editor_toolbar")
|
||||
.exact_height(TOOLBAR_HEIGHT)
|
||||
.show(ctx, |ui| {
|
||||
toolbar_ui(world, ui);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn toolbar_ui(world: &mut World, ui: &mut egui::Ui) {
|
||||
let (toolbar_rect, _) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width(), TOOLBAR_HEIGHT - 4.0),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
|
||||
let center_y = toolbar_rect.center().y;
|
||||
let left_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(toolbar_rect.left() + 8.0, center_y - 18.0),
|
||||
egui::pos2(toolbar_rect.right(), center_y + 18.0),
|
||||
);
|
||||
let transport_rect = egui::Rect::from_center_size(
|
||||
egui::pos2(toolbar_rect.center().x, center_y),
|
||||
egui::vec2(transport_width(world), 44.0),
|
||||
);
|
||||
|
||||
let mut left_ui = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.id_salt("toolbar_left")
|
||||
.max_rect(left_rect)
|
||||
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
);
|
||||
left_ui.spacing_mut().item_spacing.x = 6.0;
|
||||
left_toolbar(world, &mut left_ui);
|
||||
|
||||
let mut transport_ui = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.id_salt("toolbar_transport")
|
||||
.max_rect(transport_rect)
|
||||
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
);
|
||||
transport_ui.spacing_mut().item_spacing.x = 10.0;
|
||||
transport_controls(world, &mut transport_ui);
|
||||
}
|
||||
|
||||
fn transport_width(world: &World) -> f32 {
|
||||
let button_count = match *world.resource::<State<EditorMode>>().get() {
|
||||
EditorMode::Editing => 1.0,
|
||||
EditorMode::Playing => 3.0,
|
||||
};
|
||||
let gap_count = button_count - 1.0;
|
||||
|
||||
button_count * 44.0 + gap_count * 10.0
|
||||
}
|
||||
|
||||
fn left_toolbar(world: &mut World, ui: &mut egui::Ui) {
|
||||
panel_toolbar_row(ui, |ui| {
|
||||
if icon_button(ui, icons::CUBE, "Spawn cube").clicked() {
|
||||
spawn_primitive_at_camera(world, PrimitiveShape::Box, "Cube");
|
||||
}
|
||||
if icon_button(ui, icons::MOUNTAINS, "Spawn ramp").clicked() {
|
||||
spawn_primitive_at_camera(world, PrimitiveShape::Ramp, "Ramp");
|
||||
}
|
||||
if icon_button(ui, icons::SPHERE, "Spawn sphere").clicked() {
|
||||
spawn_primitive_at_camera(world, PrimitiveShape::Sphere, "Sphere");
|
||||
}
|
||||
if icon_button(ui, icons::LIGHTBULB, "Spawn point light").clicked() {
|
||||
let pos = camera_ground_spawn(world);
|
||||
spawn_with_history(world, light_snapshot("Point Light", pos));
|
||||
}
|
||||
|
||||
toolbar_separator(ui);
|
||||
|
||||
if icon_button(ui, icons::FILE, "New scene").clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::New);
|
||||
}
|
||||
if icon_button(ui, icons::FOLDER_OPEN, "Open scene").clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Open);
|
||||
}
|
||||
if icon_button(ui, icons::FLOPPY_DISK, "Save scene").clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Save);
|
||||
}
|
||||
if icon_button(ui, icons::COPY, "Save scene as").clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::SaveAs);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn transport_controls(world: &mut World, ui: &mut egui::Ui) {
|
||||
let mode = *world.resource::<State<EditorMode>>().get();
|
||||
match mode {
|
||||
EditorMode::Editing => {
|
||||
if transport_button_large(ui, icons::PLAY, "Play (F5)", true).clicked() {
|
||||
toggle_play_mode(world);
|
||||
}
|
||||
}
|
||||
EditorMode::Playing => {
|
||||
let paused = world.resource::<PlayPaused>().0;
|
||||
let pause_icon = if paused { icons::PLAY } else { icons::PAUSE };
|
||||
let pause_tip = if paused {
|
||||
"Resume simulation (F6)"
|
||||
} else {
|
||||
"Pause simulation (F6)"
|
||||
};
|
||||
if transport_button_large(ui, pause_icon, pause_tip, false).clicked() {
|
||||
toggle_play_paused(world);
|
||||
}
|
||||
if transport_button_large(ui, icons::STOP, "Stop and return to Edit (F5)", false)
|
||||
.clicked()
|
||||
{
|
||||
toggle_play_mode(world);
|
||||
}
|
||||
|
||||
let possession = *world.resource::<PlayPossession>();
|
||||
let (eject_icon, eject_tip) = match possession {
|
||||
PlayPossession::Possessed => (icons::SIGN_OUT, "Eject from player (F8)"),
|
||||
PlayPossession::Ejected => (icons::USER, "Possess player (F8)"),
|
||||
};
|
||||
if transport_button_large(ui, eject_icon, eject_tip, false).clicked() {
|
||||
toggle_possession(world);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn camera_ground_spawn(world: &mut World) -> Vec3 {
|
||||
let rect = world.resource::<UiState>().viewport_rect;
|
||||
let settings = world.resource::<ViewportSettings>().clone();
|
||||
let pos = editor_spawn_ground_position(world, rect);
|
||||
snap_translation(pos, &settings)
|
||||
}
|
||||
|
||||
fn spawn_primitive_at_camera(world: &mut World, shape: PrimitiveShape, name: &str) {
|
||||
let pos = camera_ground_spawn(world);
|
||||
spawn_with_history(world, primitive_snapshot(name, shape, pos));
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
//! Unified viewport overlay chrome (toolbars, badges, HUD).
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::{egui, EguiTextureHandle, EguiUserTextures};
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::assets::EditorAssets;
|
||||
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
|
||||
use crate::render_target::ViewportRenderTarget;
|
||||
use crate::selection::ViewportClick;
|
||||
use crate::state::PlayPossession;
|
||||
use crate::viewport::{
|
||||
snap_translation, viewport_ground_position, EditorViewportMode, ViewportDisplayMode,
|
||||
ViewportSettings,
|
||||
};
|
||||
|
||||
use super::helpers::{
|
||||
focus_editor_camera_on_selection, viewport_recall_bookmark, viewport_save_bookmark,
|
||||
};
|
||||
use super::theme::viewport_toolbar_frame;
|
||||
use super::widgets::{icon_button_small, panel_toolbar_row, tool_button};
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct ViewportUiState {
|
||||
pub options_open: bool,
|
||||
pub shortcuts_open: bool,
|
||||
}
|
||||
|
||||
const VIEWPORT_TOOLTIP: &str = "RMB + WASD/QE: fly | MMB: pan | Scroll: dolly\nW/E/R: gizmo | X: world/local | F: focus | G: game view | Ctrl+G: grid\nTab: cycle overlapping picks | Play/Pause/Stop: main toolbar (F5 / F6)";
|
||||
|
||||
pub fn viewport_tab_ui(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
viewport_rect: &mut egui::Rect,
|
||||
pointer_in_viewport: &mut bool,
|
||||
viewport_pointer_pos: &mut Option<egui::Pos2>,
|
||||
selected_entities: &SelectedEntities,
|
||||
playing: bool,
|
||||
_cursor_grabbed: bool,
|
||||
) {
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
*viewport_rect = rect;
|
||||
|
||||
if rect.width() <= 1.0 || rect.height() <= 1.0 {
|
||||
*pointer_in_viewport = false;
|
||||
*viewport_pointer_pos = None;
|
||||
return;
|
||||
}
|
||||
|
||||
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
|
||||
let response = ui.allocate_rect(rect, egui::Sense::HOVER);
|
||||
*viewport_pointer_pos = response
|
||||
.interact_pointer_pos()
|
||||
.or_else(|| response.hover_pos())
|
||||
.filter(|pos| rect.contains(*pos));
|
||||
*pointer_in_viewport = viewport_pointer_pos.is_some();
|
||||
|
||||
let primary_clicked =
|
||||
ui.input(|input| input.pointer.button_clicked(egui::PointerButton::Primary));
|
||||
if primary_clicked && !clean_game_view {
|
||||
if let Some(pos) = response
|
||||
.interact_pointer_pos()
|
||||
.or_else(|| response.hover_pos())
|
||||
.filter(|pos| rect.contains(*pos))
|
||||
{
|
||||
world.resource_mut::<ViewportClick>().0 = Some(pos);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(target) = world
|
||||
.get_resource::<ViewportRenderTarget>()
|
||||
.and_then(|target| target.0.clone())
|
||||
{
|
||||
let mut textures = world.resource_mut::<EguiUserTextures>();
|
||||
let texture_id = textures
|
||||
.image_id(target.image.id())
|
||||
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(target.image.clone())));
|
||||
|
||||
let painter = ui.painter();
|
||||
painter.rect_filled(rect, 0.0, egui::Color32::BLACK);
|
||||
painter.image(
|
||||
texture_id,
|
||||
rect,
|
||||
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
|
||||
egui::Color32::WHITE,
|
||||
);
|
||||
} else {
|
||||
ui.allocate_rect(rect, egui::Sense::hover());
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.label(egui::RichText::new("Viewport").weak());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if clean_game_view {
|
||||
if playing {
|
||||
game_view_overlay(world, ui.ctx(), rect, playing);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
scene_view_overlay_toolbar(world, ui.ctx(), rect);
|
||||
scene_view_mode_badge(world, ui.ctx(), rect);
|
||||
scene_view_gi_badge(world, ui.ctx(), rect);
|
||||
scene_view_volume_hud(world, ui.ctx(), rect);
|
||||
viewport_asset_drop_ui(world, ui, rect, selected_entities);
|
||||
}
|
||||
|
||||
fn scene_view_mode_badge(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let Some(mode) = world.get_resource::<EditorViewportMode>() else {
|
||||
return;
|
||||
};
|
||||
let mode = *mode;
|
||||
let (label, color) = match mode {
|
||||
EditorViewportMode::Lit => ("Lit", egui::Color32::from_rgb(120, 200, 120)),
|
||||
EditorViewportMode::Unlit => ("Unlit", egui::Color32::from_rgb(200, 200, 120)),
|
||||
EditorViewportMode::Collider => ("Collider", egui::Color32::from_rgb(220, 140, 80)),
|
||||
};
|
||||
|
||||
egui::Area::new(egui::Id::new("scene_view_mode_badge"))
|
||||
.fixed_pos(scene_rect.right_bottom() + egui::vec2(-72.0, -22.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(egui::Color32::from_black_alpha(160))
|
||||
.inner_margin(egui::Margin::symmetric(8, 4))
|
||||
.show(ui, |ui| {
|
||||
ui.colored_label(color, label);
|
||||
});
|
||||
});
|
||||
|
||||
if mode == EditorViewportMode::Collider {
|
||||
egui::Area::new(egui::Id::new("scene_view_collider_warning"))
|
||||
.fixed_pos(scene_rect.left_bottom() + egui::vec2(8.0, -28.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Meshes hidden - switch to Lit (sun icon) for shading",
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn scene_view_gi_badge(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let Some(profile) = world.get_resource::<settings::ActiveCameraRenderProfile>() else {
|
||||
return;
|
||||
};
|
||||
let (label, color) = match profile.gi_path {
|
||||
settings::GiPath::Forward => ("Forward", egui::Color32::from_rgb(140, 180, 255)),
|
||||
settings::GiPath::SolariDeferred => ("Solari", egui::Color32::from_rgb(255, 170, 90)),
|
||||
};
|
||||
egui::Area::new(egui::Id::new("scene_view_gi_badge"))
|
||||
.fixed_pos(scene_rect.right_bottom() + egui::vec2(-148.0, -22.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(egui::Color32::from_black_alpha(160))
|
||||
.inner_margin(egui::Margin::symmetric(8, 4))
|
||||
.show(ui, |ui| {
|
||||
ui.colored_label(color, label);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_view_volume_hud(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let Some(contributions) = world.get_resource::<settings::ActiveVolumeContribution>() else {
|
||||
return;
|
||||
};
|
||||
let Some(primary) = contributions.entries.first() else {
|
||||
return;
|
||||
};
|
||||
egui::Area::new(egui::Id::new("scene_view_volume_hud"))
|
||||
.fixed_pos(scene_rect.left_bottom() + egui::vec2(8.0, -56.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(egui::Color32::from_black_alpha(150))
|
||||
.inner_margin(egui::Margin::symmetric(8, 4))
|
||||
.show(ui, |ui| {
|
||||
ui.label(format!(
|
||||
"Volume: {} ({:.0}%, {} overrides)",
|
||||
primary.label,
|
||||
primary.weight * 100.0,
|
||||
primary.override_count
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let mut options_open = world.resource::<ViewportUiState>().options_open;
|
||||
let mut shortcuts_open = world.resource::<ViewportUiState>().shortcuts_open;
|
||||
|
||||
egui::Area::new(egui::Id::new("scene_view_toolbar"))
|
||||
.fixed_pos(scene_rect.left_top() + egui::vec2(6.0, 6.0))
|
||||
.interactable(true)
|
||||
.show(ctx, |ui| {
|
||||
viewport_toolbar_frame().show(ui, |ui| {
|
||||
panel_toolbar_row(ui, |ui| {
|
||||
let gizmo_mode = *world.resource::<crate::gizmos::EditorGizmoMode>();
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::ARROWS_OUT_CARDINAL,
|
||||
gizmo_mode == EditorGizmoMode::Translate,
|
||||
"Translate (W)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_mode(world, EditorGizmoMode::Translate);
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::ARROWS_CLOCKWISE,
|
||||
gizmo_mode == EditorGizmoMode::Rotate,
|
||||
"Rotate (E)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_mode(world, EditorGizmoMode::Rotate);
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::ARROWS_IN_LINE_HORIZONTAL,
|
||||
gizmo_mode == EditorGizmoMode::Scale,
|
||||
"Scale (R)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_mode(world, EditorGizmoMode::Scale);
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
let space = *world.resource::<EditorGizmoSpace>();
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::GLOBE,
|
||||
space == EditorGizmoSpace::World,
|
||||
"World space (X)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_space(world, EditorGizmoSpace::World);
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::CUBE,
|
||||
space == EditorGizmoSpace::Local,
|
||||
"Local space (X)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_space(world, EditorGizmoSpace::Local);
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
let viewport_mode = *world.resource::<EditorViewportMode>();
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::SUN,
|
||||
viewport_mode == EditorViewportMode::Lit,
|
||||
"Lit shading (WYSIWYG)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
*world.resource_mut::<EditorViewportMode>() = EditorViewportMode::Lit;
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::PAINT_BRUSH,
|
||||
viewport_mode == EditorViewportMode::Unlit,
|
||||
"Unlit base color (debug albedo)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
*world.resource_mut::<EditorViewportMode>() = EditorViewportMode::Unlit;
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::BOUNDING_BOX,
|
||||
viewport_mode == EditorViewportMode::Collider,
|
||||
"Collider view (hide meshes)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
*world.resource_mut::<EditorViewportMode>() = EditorViewportMode::Collider;
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
if let Some(mut settings) = world.get_resource_mut::<ViewportSettings>() {
|
||||
let grid = settings.show_grid;
|
||||
if tool_button(ui, icons::GRID_FOUR, grid, "Toggle grid (Ctrl+G)").clicked()
|
||||
{
|
||||
settings.show_grid = !settings.show_grid;
|
||||
}
|
||||
let snap = settings.snap_translate;
|
||||
if tool_button(ui, icons::MAGNET, snap, "Snap translation").clicked() {
|
||||
settings.snap_translate = !settings.snap_translate;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(mut visualizers) =
|
||||
world.get_resource_mut::<crate::visualizers::EditorVisualizationSettings>()
|
||||
{
|
||||
let enabled = visualizers.enabled;
|
||||
if tool_button(ui, icons::EYE, enabled, "Toggle scene visualizers")
|
||||
.clicked()
|
||||
{
|
||||
visualizers.enabled = !visualizers.enabled;
|
||||
}
|
||||
}
|
||||
|
||||
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::GAME_CONTROLLER,
|
||||
clean_game_view,
|
||||
"Game view overlay (G)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
world.resource_mut::<ViewportDisplayMode>().clean_game_view =
|
||||
!clean_game_view;
|
||||
}
|
||||
|
||||
if icon_button_small(ui, icons::CROSSHAIR, "Focus selection (F)").clicked() {
|
||||
focus_editor_camera_on_selection(world);
|
||||
}
|
||||
|
||||
if icon_button_small(ui, icons::GEAR, "Viewport options").clicked() {
|
||||
options_open = !options_open;
|
||||
}
|
||||
if icon_button_small(ui, icons::QUESTION, VIEWPORT_TOOLTIP).clicked() {
|
||||
shortcuts_open = !shortcuts_open;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if options_open {
|
||||
scene_options_popover(world, ctx, scene_rect, &mut options_open);
|
||||
}
|
||||
if shortcuts_open {
|
||||
viewport_shortcuts_window(ctx, &mut shortcuts_open);
|
||||
}
|
||||
|
||||
world.resource_mut::<ViewportUiState>().options_open = options_open;
|
||||
world.resource_mut::<ViewportUiState>().shortcuts_open = shortcuts_open;
|
||||
}
|
||||
|
||||
fn scene_options_popover(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
scene_rect: egui::Rect,
|
||||
open: &mut bool,
|
||||
) {
|
||||
egui::Area::new(egui::Id::new("scene_view_options"))
|
||||
.fixed_pos(scene_rect.left_top() + egui::vec2(6.0, 44.0))
|
||||
.show(ctx, |ui| {
|
||||
viewport_toolbar_frame().show(ui, |ui| {
|
||||
ui.set_min_width(220.0);
|
||||
ui.heading("Viewport Options");
|
||||
if let Some(mut display) = world.get_resource_mut::<ViewportDisplayMode>() {
|
||||
ui.checkbox(&mut display.clean_game_view, "Game view overlay");
|
||||
ui.small("G toggles game view; Ctrl+G toggles grid");
|
||||
}
|
||||
if let Some(mut settings) = world.get_resource_mut::<ViewportSettings>() {
|
||||
ui.separator();
|
||||
ui.checkbox(&mut settings.show_grid, "Show grid");
|
||||
ui.checkbox(&mut settings.snap_translate, "Snap translation");
|
||||
ui.add(
|
||||
egui::Slider::new(&mut settings.snap_increment, 0.25..=4.0)
|
||||
.text("Snap step"),
|
||||
);
|
||||
}
|
||||
if let Some(mut mode) = world.get_resource_mut::<EditorViewportMode>() {
|
||||
ui.separator();
|
||||
ui.label("Shading");
|
||||
ui.horizontal(|ui| {
|
||||
ui.selectable_value(&mut *mode, EditorViewportMode::Lit, "Lit");
|
||||
ui.selectable_value(&mut *mode, EditorViewportMode::Unlit, "Unlit");
|
||||
ui.selectable_value(&mut *mode, EditorViewportMode::Collider, "Colliders");
|
||||
});
|
||||
}
|
||||
if let Some(mut visualizers) =
|
||||
world.get_resource_mut::<crate::visualizers::EditorVisualizationSettings>()
|
||||
{
|
||||
ui.separator();
|
||||
ui.checkbox(&mut visualizers.enabled, "Show visualizers");
|
||||
ui.add_enabled_ui(visualizers.enabled, |ui| {
|
||||
ui.checkbox(&mut visualizers.show_actor_icons, "Actor root icons");
|
||||
ui.add_enabled_ui(visualizers.show_actor_icons, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_actor, "Actors");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_mesh, "Meshes");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_light, "Lights");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_physics, "Physics");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_gameplay, "Gameplay");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_volume, "Volumes");
|
||||
ui.checkbox(
|
||||
&mut visualizers.show_actor_icon_prefab_model,
|
||||
"Prefabs/models",
|
||||
);
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_debug, "Warnings");
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
ui.checkbox(&mut visualizers.show_colliders, "Colliders");
|
||||
ui.checkbox(&mut visualizers.show_lights, "Lights");
|
||||
ui.checkbox(&mut visualizers.show_spawns, "Player spawns");
|
||||
ui.checkbox(
|
||||
&mut visualizers.show_prefab_model_anchors,
|
||||
"Prefab/model anchors",
|
||||
);
|
||||
ui.checkbox(&mut visualizers.show_runtime, "Runtime player/cameras");
|
||||
ui.checkbox(&mut visualizers.pickable_proxies, "Selectable proxies");
|
||||
});
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Save bookmark").clicked() {
|
||||
viewport_save_bookmark(world);
|
||||
}
|
||||
if ui.button("Recall bookmark").clicked() {
|
||||
viewport_recall_bookmark(world);
|
||||
}
|
||||
});
|
||||
ui.small("Ctrl+Shift+1 save | Ctrl+Shift+2 recall");
|
||||
if ui.button("Close").clicked() {
|
||||
*open = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn viewport_shortcuts_window(ctx: &egui::Context, open: &mut bool) {
|
||||
egui::Window::new("Viewport Shortcuts")
|
||||
.open(open)
|
||||
.default_width(320.0)
|
||||
.show(ctx, |ui| {
|
||||
ui.label("Viewport navigation");
|
||||
ui.small("RMB + WASD/QE - fly camera");
|
||||
ui.small("MMB drag - pan");
|
||||
ui.small("Scroll - dolly");
|
||||
ui.separator();
|
||||
ui.label("Tools");
|
||||
ui.small("W / E / R - translate / rotate / scale gizmo");
|
||||
ui.small("X - toggle world / local space");
|
||||
ui.small("G - toggle game view overlay");
|
||||
ui.small("Ctrl+G - toggle grid");
|
||||
ui.small("F - focus selection");
|
||||
ui.small("Tab - cycle overlapping selection at click");
|
||||
ui.small("F5 - play / stop (main toolbar)");
|
||||
ui.small("F6 - pause / resume (while playing)");
|
||||
ui.small("F8 - possess / eject (while playing)");
|
||||
ui.small("Esc - deselect / free cursor");
|
||||
});
|
||||
}
|
||||
|
||||
fn game_view_overlay(world: &World, ctx: &egui::Context, rect: egui::Rect, playing: bool) {
|
||||
egui::Area::new(egui::Id::new("game_view_hud"))
|
||||
.fixed_pos(rect.left_top() + egui::vec2(6.0, 6.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
viewport_toolbar_frame().show(ui, |ui| {
|
||||
if !playing {
|
||||
ui.label(egui::RichText::new("Game View").strong());
|
||||
ui.small("Press F5 or Play to run here.");
|
||||
return;
|
||||
}
|
||||
|
||||
ui.label(egui::RichText::new("Playing").strong());
|
||||
let possession = *world.resource::<PlayPossession>();
|
||||
let possess_label = match possession {
|
||||
PlayPossession::Possessed => "Possessed",
|
||||
PlayPossession::Ejected => "Ejected (Scene camera)",
|
||||
};
|
||||
ui.small(possess_label);
|
||||
ui.small("F5 stop | F6 pause | F8 possess/eject | Esc free cursor");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn viewport_asset_drop_ui(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
viewport_rect: egui::Rect,
|
||||
selected: &SelectedEntities,
|
||||
) {
|
||||
let pointer_released = ui.input(|input| input.pointer.any_released());
|
||||
if !pointer_released {
|
||||
return;
|
||||
}
|
||||
|
||||
let pointer_pos = ui.input(|input| input.pointer.hover_pos());
|
||||
if !pointer_pos.is_some_and(|pos| viewport_rect.contains(pos)) {
|
||||
world.resource_mut::<EditorAssets>().clear_drag();
|
||||
return;
|
||||
}
|
||||
|
||||
let asset = {
|
||||
let assets = world.resource::<EditorAssets>();
|
||||
assets.dragging_asset().cloned()
|
||||
};
|
||||
world.resource_mut::<EditorAssets>().clear_drag();
|
||||
|
||||
let Some(asset) = asset else {
|
||||
return;
|
||||
};
|
||||
match asset.kind {
|
||||
crate::assets::EditorAssetKind::Texture => {
|
||||
crate::ui::helpers::apply_texture_to_selection(world, &asset, selected);
|
||||
return;
|
||||
}
|
||||
crate::assets::EditorAssetKind::Material => {
|
||||
crate::ui::helpers::apply_material_asset_to_selection(world, &asset, selected);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let placement = viewport_ground_position(world, pointer_pos.unwrap(), viewport_rect)
|
||||
.map(|pos| snap_translation(pos, world.resource::<ViewportSettings>()))
|
||||
.unwrap_or(Vec3::ZERO);
|
||||
crate::assets::spawn_asset_at(world, &asset, placement);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Reusable editor widgets: icon buttons, tool toggles, menu labels.
|
||||
|
||||
use bevy_egui::egui::{self, Button, FontId, RichText, Ui, WidgetText};
|
||||
use egui_phosphor_icons::Icon;
|
||||
|
||||
use super::theme::{ACCENT, ACCENT_HOVER, ELEVATED_BG};
|
||||
|
||||
const PHOSPHOR: &str = "phosphor-regular";
|
||||
|
||||
pub fn phosphor_icon(icon: Icon, size: f32) -> RichText {
|
||||
phosphor_icon_text(icon.as_str(), size)
|
||||
}
|
||||
|
||||
pub fn phosphor_icon_text(icon: &str, size: f32) -> RichText {
|
||||
RichText::new(icon).font(FontId::new(size, egui::FontFamily::Name(PHOSPHOR.into())))
|
||||
}
|
||||
|
||||
/// Large transport control (Play / Pause / Stop / Eject) — icon only, tooltip for label.
|
||||
pub fn transport_button_large(
|
||||
ui: &mut Ui,
|
||||
icon: Icon,
|
||||
tooltip: &str,
|
||||
accent: bool,
|
||||
) -> egui::Response {
|
||||
const SIZE: f32 = 44.0;
|
||||
const ICON_PX: f32 = 22.0;
|
||||
|
||||
let fill = if accent {
|
||||
ACCENT
|
||||
} else {
|
||||
ELEVATED_BG.linear_multiply(0.85)
|
||||
};
|
||||
ui.add(
|
||||
Button::new(phosphor_icon(icon, ICON_PX))
|
||||
.fill(fill)
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0,
|
||||
if accent {
|
||||
ACCENT_HOVER
|
||||
} else {
|
||||
super::theme::BORDER
|
||||
},
|
||||
))
|
||||
.min_size(egui::vec2(SIZE, SIZE))
|
||||
.corner_radius(5.0),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn icon_button(ui: &mut Ui, icon: Icon, tooltip: &str) -> egui::Response {
|
||||
ui.add(
|
||||
Button::new(phosphor_icon(icon, 18.0))
|
||||
.frame(false)
|
||||
.min_size(egui::vec2(32.0, 32.0)),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn icon_button_small(ui: &mut Ui, icon: Icon, tooltip: &str) -> egui::Response {
|
||||
ui.add(
|
||||
Button::new(phosphor_icon(icon, 16.0))
|
||||
.frame(false)
|
||||
.min_size(egui::vec2(22.0, 22.0)),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn tool_button(ui: &mut Ui, icon: Icon, selected: bool, tooltip: &str) -> egui::Response {
|
||||
let fill = if selected {
|
||||
ACCENT
|
||||
} else {
|
||||
ELEVATED_BG.linear_multiply(0.6)
|
||||
};
|
||||
ui.add(
|
||||
Button::new(phosphor_icon(icon, 16.0))
|
||||
.fill(fill)
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0,
|
||||
if selected {
|
||||
ACCENT
|
||||
} else {
|
||||
super::theme::BORDER
|
||||
},
|
||||
))
|
||||
.min_size(egui::vec2(26.0, 26.0))
|
||||
.corner_radius(3.0),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn menu_item(
|
||||
ui: &mut Ui,
|
||||
label: &str,
|
||||
shortcut: Option<&str>,
|
||||
enabled: bool,
|
||||
) -> egui::Response {
|
||||
let text: WidgetText = if let Some(key) = shortcut {
|
||||
RichText::new(format!("{label}\t{key}")).into()
|
||||
} else {
|
||||
label.into()
|
||||
};
|
||||
ui.add_enabled(enabled, egui::Button::new(text))
|
||||
}
|
||||
|
||||
pub fn toolbar_separator(ui: &mut Ui) {
|
||||
ui.add_space(4.0);
|
||||
ui.separator();
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
|
||||
pub fn panel_toolbar_row<R>(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
//! Selectable editor-only billboards at actor roots.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use bevy::asset::{load_internal_binary_asset, uuid_handle, RenderAssetUsages};
|
||||
use bevy::camera::visibility::NoFrustumCulling;
|
||||
use bevy::image::{CompressedImageFormats, ImageSampler, ImageType};
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
ActorKind, AuthoringLightKind, ColliderDesc, LevelObject, LightDesc, ModelRef, ObjectiveMarker,
|
||||
PhysicsBody, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
|
||||
RaytracingExcluded, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
|
||||
};
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::infra::EditorOnly;
|
||||
use crate::state::scene_tools_active;
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::ViewportDisplayMode;
|
||||
use crate::visualizers::EditorVisualizationSettings;
|
||||
|
||||
const ICON_TARGET_PIXELS: f32 = 30.0;
|
||||
const ICON_MIN_WORLD_SIZE: f32 = 0.2;
|
||||
const ICON_MAX_WORLD_SIZE: f32 = 3.0;
|
||||
const DEFAULT_PERSPECTIVE_FOV: f32 = std::f32::consts::FRAC_PI_4;
|
||||
|
||||
const ICON_01_ACTOR_EMPTY: Handle<Image> = uuid_handle!("d87c7796-b219-4011-8305-4db55422f1c7");
|
||||
const ICON_02_ACTOR_GENERIC: Handle<Image> = uuid_handle!("c9a1a84f-4dcd-4a2b-a5b6-c365dc7d6795");
|
||||
const ICON_03_ACTOR_MISSING: Handle<Image> = uuid_handle!("cca7cdf9-0c7d-4546-9bb9-1176e49a635c");
|
||||
const ICON_04_ACTOR_WARNING: Handle<Image> = uuid_handle!("7dba1d9c-0569-40d2-978e-66014377051d");
|
||||
const ICON_05_RENDER_MESH: Handle<Image> = uuid_handle!("10c70a1d-3327-458a-92d2-db41f893432e");
|
||||
const ICON_06_RENDER_DECAL: Handle<Image> = uuid_handle!("8c27ff62-0d94-4184-81cf-977e652a0496");
|
||||
const ICON_07_RENDER_PARTICLE: Handle<Image> = uuid_handle!("0db519d6-0eca-4389-9393-2e0c38f73119");
|
||||
const ICON_08_RENDER_BILLBOARD: Handle<Image> =
|
||||
uuid_handle!("2fcb8e83-8f51-4978-8b29-146e2c44b5e6");
|
||||
const ICON_09_LIGHT_POINT: Handle<Image> = uuid_handle!("ba2cbf62-c547-4cfe-ba61-4081076da93b");
|
||||
const ICON_10_LIGHT_SPOT: Handle<Image> = uuid_handle!("200ee881-9cac-41d1-89be-45581642968f");
|
||||
const ICON_11_LIGHT_DIRECTIONAL: Handle<Image> =
|
||||
uuid_handle!("d9de4730-2463-41dc-87e9-ed99b013d74a");
|
||||
const ICON_12_LIGHT_AREA: Handle<Image> = uuid_handle!("d43ea6a8-15da-4792-8d63-962211f94ad6");
|
||||
const ICON_13_CAMERA_MAIN: Handle<Image> = uuid_handle!("1979cc52-7285-4bb3-88f5-bd82021c10fa");
|
||||
const ICON_14_CAMERA_CAPTURE: Handle<Image> = uuid_handle!("f1fc47d3-eaf4-4aaf-becc-b51a64f0b070");
|
||||
const ICON_15_AUDIO_SOURCE: Handle<Image> = uuid_handle!("2dd3091f-2dea-4626-8430-79fa44a53c68");
|
||||
const ICON_16_AUDIO_LISTENER: Handle<Image> = uuid_handle!("9eb3177f-e3d5-45cb-bd7c-49eecb4eb8e3");
|
||||
const ICON_17_PHYSICS_COLLIDER: Handle<Image> =
|
||||
uuid_handle!("69f02ada-e171-484b-9a46-af753971e9c1");
|
||||
const ICON_18_PHYSICS_RIGIDBODY: Handle<Image> =
|
||||
uuid_handle!("c30ddfb8-a851-45ab-98a9-97add45f1b49");
|
||||
const ICON_19_PHYSICS_TRIGGER: Handle<Image> = uuid_handle!("3cf22740-463a-41b0-a1d7-d0cccc910b70");
|
||||
const ICON_20_PHYSICS_JOINT: Handle<Image> = uuid_handle!("cdb8ef15-d41c-4f34-bc98-4a61f4628508");
|
||||
const ICON_21_GAME_SPAWN: Handle<Image> = uuid_handle!("56719033-f1db-4749-8637-9b004581ce81");
|
||||
const ICON_22_GAME_TRIGGER: Handle<Image> = uuid_handle!("98e42034-1c34-40af-8955-12c12cc2e261");
|
||||
const ICON_23_GAME_MARKER: Handle<Image> = uuid_handle!("7808784d-c117-41a9-84db-fae5d4edbf3a");
|
||||
const ICON_24_GAME_INTERACTABLE: Handle<Image> =
|
||||
uuid_handle!("e61fc53a-5201-49a4-9451-88d7c804a5c5");
|
||||
const ICON_25_NAV_WAYPOINT: Handle<Image> = uuid_handle!("26511234-47bc-4cdc-b24c-39bfec7e46da");
|
||||
const ICON_26_NAV_LINK: Handle<Image> = uuid_handle!("6f4988e9-b571-45af-a3ad-777d80a3d9b6");
|
||||
const ICON_27_NAV_REGION: Handle<Image> = uuid_handle!("02b7ae0d-b3d6-4e46-8be0-8ee590ea71cc");
|
||||
const ICON_28_VOLUME_GENERIC: Handle<Image> = uuid_handle!("670cf8ce-c33e-4f86-ae7e-0311c8917629");
|
||||
const ICON_29_VOLUME_POST_PROCESS: Handle<Image> =
|
||||
uuid_handle!("bc9064bd-b6a8-4b00-95d4-3763325bceb9");
|
||||
const ICON_30_ENVIRONMENT_WIND: Handle<Image> =
|
||||
uuid_handle!("0d4220a6-7abc-42bc-a0d2-b69847061a92");
|
||||
const ICON_31_ENVIRONMENT_SKY: Handle<Image> = uuid_handle!("e4f09ad3-380d-4086-9eb4-e60e69ec1765");
|
||||
const ICON_32_DEBUG_NOTE: Handle<Image> = uuid_handle!("d093e657-6598-4097-8a57-9d445e3a80d7");
|
||||
|
||||
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ActorIconProxy {
|
||||
pub target: Entity,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum ActorIconImage {
|
||||
Empty,
|
||||
Generic,
|
||||
Missing,
|
||||
Warning,
|
||||
Mesh,
|
||||
LightPoint,
|
||||
LightSpot,
|
||||
LightDirectional,
|
||||
PhysicsCollider,
|
||||
GameSpawn,
|
||||
GameTrigger,
|
||||
GameMarker,
|
||||
VolumeGeneric,
|
||||
PostProcessVolume,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum ActorIconCategory {
|
||||
Actor,
|
||||
Mesh,
|
||||
Light,
|
||||
Physics,
|
||||
Gameplay,
|
||||
Volume,
|
||||
PrefabModel,
|
||||
Debug,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct ActorIconSpec {
|
||||
image: ActorIconImage,
|
||||
category: ActorIconCategory,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
struct ActorIconComponents {
|
||||
kind: Option<ActorKind>,
|
||||
light_kind: Option<AuthoringLightKind>,
|
||||
has_primitive: bool,
|
||||
has_static_mesh_renderer: bool,
|
||||
has_model_ref: bool,
|
||||
has_prefab_ref: bool,
|
||||
has_prefab_instance: bool,
|
||||
has_player_spawn: bool,
|
||||
has_weapon_spawn: bool,
|
||||
has_trigger_volume: bool,
|
||||
has_post_process_volume: bool,
|
||||
has_team_spawn: bool,
|
||||
has_objective: bool,
|
||||
has_physics: bool,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct ActorIconAssets {
|
||||
mesh: Handle<Mesh>,
|
||||
materials: HashMap<ActorIconImage, Handle<StandardMaterial>>,
|
||||
}
|
||||
|
||||
pub struct ActorIconsPlugin;
|
||||
|
||||
impl Plugin for ActorIconsPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
register_actor_icon_images(app);
|
||||
app.add_systems(Startup, init_actor_icon_assets)
|
||||
.add_systems(Update, sync_actor_icons.run_if(scene_tools_active));
|
||||
}
|
||||
}
|
||||
|
||||
fn icon_image_from_png(bytes: &[u8], path: String) -> Image {
|
||||
Image::from_buffer(
|
||||
bytes,
|
||||
ImageType::Extension("png"),
|
||||
CompressedImageFormats::NONE,
|
||||
true,
|
||||
ImageSampler::linear(),
|
||||
RenderAssetUsages::default(),
|
||||
)
|
||||
.unwrap_or_else(|err| panic!("failed to load editor actor icon {path}: {err}"))
|
||||
}
|
||||
|
||||
macro_rules! load_actor_icon {
|
||||
($app:ident, $handle:expr, $path:literal) => {
|
||||
load_internal_binary_asset!(
|
||||
$app,
|
||||
$handle,
|
||||
concat!("../../assets/icons/", $path),
|
||||
icon_image_from_png
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
fn register_actor_icon_images(app: &mut App) {
|
||||
load_actor_icon!(app, ICON_01_ACTOR_EMPTY, "01_actor_empty.png");
|
||||
load_actor_icon!(app, ICON_02_ACTOR_GENERIC, "02_actor_generic.png");
|
||||
load_actor_icon!(app, ICON_03_ACTOR_MISSING, "03_actor_missing.png");
|
||||
load_actor_icon!(app, ICON_04_ACTOR_WARNING, "04_actor_warning.png");
|
||||
load_actor_icon!(app, ICON_05_RENDER_MESH, "05_render_mesh.png");
|
||||
load_actor_icon!(app, ICON_06_RENDER_DECAL, "06_render_decal.png");
|
||||
load_actor_icon!(app, ICON_07_RENDER_PARTICLE, "07_render_particle.png");
|
||||
load_actor_icon!(app, ICON_08_RENDER_BILLBOARD, "08_render_billboard.png");
|
||||
load_actor_icon!(app, ICON_09_LIGHT_POINT, "09_light_point.png");
|
||||
load_actor_icon!(app, ICON_10_LIGHT_SPOT, "10_light_spot.png");
|
||||
load_actor_icon!(app, ICON_11_LIGHT_DIRECTIONAL, "11_light_directional.png");
|
||||
load_actor_icon!(app, ICON_12_LIGHT_AREA, "12_light_area.png");
|
||||
load_actor_icon!(app, ICON_13_CAMERA_MAIN, "13_camera_main.png");
|
||||
load_actor_icon!(app, ICON_14_CAMERA_CAPTURE, "14_camera_capture.png");
|
||||
load_actor_icon!(app, ICON_15_AUDIO_SOURCE, "15_audio_source.png");
|
||||
load_actor_icon!(app, ICON_16_AUDIO_LISTENER, "16_audio_listener.png");
|
||||
load_actor_icon!(app, ICON_17_PHYSICS_COLLIDER, "17_physics_collider.png");
|
||||
load_actor_icon!(app, ICON_18_PHYSICS_RIGIDBODY, "18_physics_rigidbody.png");
|
||||
load_actor_icon!(app, ICON_19_PHYSICS_TRIGGER, "19_physics_trigger.png");
|
||||
load_actor_icon!(app, ICON_20_PHYSICS_JOINT, "20_physics_joint.png");
|
||||
load_actor_icon!(app, ICON_21_GAME_SPAWN, "21_game_spawn.png");
|
||||
load_actor_icon!(app, ICON_22_GAME_TRIGGER, "22_game_trigger.png");
|
||||
load_actor_icon!(app, ICON_23_GAME_MARKER, "23_game_marker.png");
|
||||
load_actor_icon!(app, ICON_24_GAME_INTERACTABLE, "24_game_interactable.png");
|
||||
load_actor_icon!(app, ICON_25_NAV_WAYPOINT, "25_nav_waypoint.png");
|
||||
load_actor_icon!(app, ICON_26_NAV_LINK, "26_nav_link.png");
|
||||
load_actor_icon!(app, ICON_27_NAV_REGION, "27_nav_region.png");
|
||||
load_actor_icon!(app, ICON_28_VOLUME_GENERIC, "28_volume_generic.png");
|
||||
load_actor_icon!(
|
||||
app,
|
||||
ICON_29_VOLUME_POST_PROCESS,
|
||||
"29_volume_post_process.png"
|
||||
);
|
||||
load_actor_icon!(app, ICON_30_ENVIRONMENT_WIND, "30_environment_wind.png");
|
||||
load_actor_icon!(app, ICON_31_ENVIRONMENT_SKY, "31_environment_sky.png");
|
||||
load_actor_icon!(app, ICON_32_DEBUG_NOTE, "32_debug_note.png");
|
||||
}
|
||||
|
||||
fn init_actor_icon_assets(
|
||||
mut commands: Commands,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
mut materials: ResMut<Assets<StandardMaterial>>,
|
||||
) {
|
||||
let mesh = meshes.add(Rectangle::new(1.0, 1.0));
|
||||
let mut actor_materials = HashMap::new();
|
||||
for (image, texture) in [
|
||||
(ActorIconImage::Empty, ICON_01_ACTOR_EMPTY),
|
||||
(ActorIconImage::Generic, ICON_02_ACTOR_GENERIC),
|
||||
(ActorIconImage::Missing, ICON_03_ACTOR_MISSING),
|
||||
(ActorIconImage::Warning, ICON_04_ACTOR_WARNING),
|
||||
(ActorIconImage::Mesh, ICON_05_RENDER_MESH),
|
||||
(ActorIconImage::LightPoint, ICON_09_LIGHT_POINT),
|
||||
(ActorIconImage::LightSpot, ICON_10_LIGHT_SPOT),
|
||||
(ActorIconImage::LightDirectional, ICON_11_LIGHT_DIRECTIONAL),
|
||||
(ActorIconImage::PhysicsCollider, ICON_17_PHYSICS_COLLIDER),
|
||||
(ActorIconImage::GameSpawn, ICON_21_GAME_SPAWN),
|
||||
(ActorIconImage::GameTrigger, ICON_22_GAME_TRIGGER),
|
||||
(ActorIconImage::GameMarker, ICON_23_GAME_MARKER),
|
||||
(ActorIconImage::VolumeGeneric, ICON_28_VOLUME_GENERIC),
|
||||
(
|
||||
ActorIconImage::PostProcessVolume,
|
||||
ICON_29_VOLUME_POST_PROCESS,
|
||||
),
|
||||
] {
|
||||
actor_materials.insert(
|
||||
image,
|
||||
materials.add(StandardMaterial {
|
||||
base_color_texture: Some(texture.clone()),
|
||||
alpha_mode: AlphaMode::Blend,
|
||||
unlit: true,
|
||||
cull_mode: None,
|
||||
fog_enabled: false,
|
||||
depth_bias: -40.0,
|
||||
..default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
commands.insert_resource(ActorIconAssets {
|
||||
mesh,
|
||||
materials: actor_materials,
|
||||
});
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||
fn sync_actor_icons(
|
||||
display: Res<ViewportDisplayMode>,
|
||||
settings: Res<EditorVisualizationSettings>,
|
||||
ui_state: Res<UiState>,
|
||||
assets: Res<ActorIconAssets>,
|
||||
mut commands: Commands,
|
||||
mut icons: Query<(
|
||||
Entity,
|
||||
&ActorIconProxy,
|
||||
&MeshMaterial3d<StandardMaterial>,
|
||||
&mut Transform,
|
||||
)>,
|
||||
camera_query: Query<(&Camera, &GlobalTransform, Option<&Projection>), With<EditorCamera>>,
|
||||
actor_roots: Query<
|
||||
(
|
||||
Entity,
|
||||
&GlobalTransform,
|
||||
Option<&ActorKind>,
|
||||
Option<&LightDesc>,
|
||||
Has<Primitive>,
|
||||
Option<&StaticMeshRenderer>,
|
||||
Has<ModelRef>,
|
||||
Has<PrefabRef>,
|
||||
Has<PrefabInstance>,
|
||||
Has<PlayerSpawn>,
|
||||
Has<WeaponSpawn>,
|
||||
Has<TriggerVolume>,
|
||||
Has<PostProcessVolumeDesc>,
|
||||
Has<TeamSpawn>,
|
||||
Has<ObjectiveMarker>,
|
||||
),
|
||||
(With<LevelObject>, Without<EditorOnly>),
|
||||
>,
|
||||
physics: Query<(), Or<(With<PhysicsBody>, With<ColliderDesc>)>>,
|
||||
) {
|
||||
let camera = active_editor_camera(&camera_query);
|
||||
let mut desired = HashMap::new();
|
||||
if !display.clean_game_view && settings.enabled && settings.show_actor_icons {
|
||||
for (
|
||||
target,
|
||||
global,
|
||||
kind,
|
||||
light,
|
||||
has_primitive,
|
||||
static_mesh_renderer,
|
||||
has_model_ref,
|
||||
has_prefab_ref,
|
||||
has_prefab_instance,
|
||||
has_player_spawn,
|
||||
has_weapon_spawn,
|
||||
has_trigger_volume,
|
||||
has_post_process_volume,
|
||||
has_team_spawn,
|
||||
has_objective,
|
||||
) in &actor_roots
|
||||
{
|
||||
let components = ActorIconComponents {
|
||||
kind: kind.copied(),
|
||||
light_kind: light.map(|light| light.kind),
|
||||
has_primitive,
|
||||
has_static_mesh_renderer: static_mesh_renderer
|
||||
.is_some_and(has_resolved_static_mesh_slot),
|
||||
has_model_ref,
|
||||
has_prefab_ref,
|
||||
has_prefab_instance,
|
||||
has_player_spawn,
|
||||
has_weapon_spawn,
|
||||
has_trigger_volume,
|
||||
has_post_process_volume,
|
||||
has_team_spawn,
|
||||
has_objective,
|
||||
has_physics: physics.contains(target),
|
||||
};
|
||||
let spec = icon_for_actor_components(components);
|
||||
if !icon_category_enabled(&settings, spec.category) {
|
||||
continue;
|
||||
}
|
||||
let transform = desired_icon_transform(global, camera, ui_state.viewport_rect.height());
|
||||
desired.insert(target, (spec.image, transform));
|
||||
}
|
||||
}
|
||||
|
||||
let mut existing_targets = HashSet::new();
|
||||
for (entity, proxy, material, mut transform) in &mut icons {
|
||||
let Some((image, desired_transform)) = desired.get(&proxy.target) else {
|
||||
commands.entity(entity).despawn();
|
||||
continue;
|
||||
};
|
||||
let expected_material = assets.materials.get(image);
|
||||
if expected_material.is_none_or(|expected| material.0 != *expected) {
|
||||
commands.entity(entity).despawn();
|
||||
continue;
|
||||
}
|
||||
existing_targets.insert(proxy.target);
|
||||
*transform = *desired_transform;
|
||||
}
|
||||
|
||||
for (
|
||||
target,
|
||||
global,
|
||||
kind,
|
||||
light,
|
||||
has_primitive,
|
||||
static_mesh_renderer,
|
||||
has_model_ref,
|
||||
has_prefab_ref,
|
||||
has_prefab_instance,
|
||||
has_player_spawn,
|
||||
has_weapon_spawn,
|
||||
has_trigger_volume,
|
||||
has_post_process_volume,
|
||||
has_team_spawn,
|
||||
has_objective,
|
||||
) in &actor_roots
|
||||
{
|
||||
if existing_targets.contains(&target) {
|
||||
continue;
|
||||
}
|
||||
let components = ActorIconComponents {
|
||||
kind: kind.copied(),
|
||||
light_kind: light.map(|light| light.kind),
|
||||
has_primitive,
|
||||
has_static_mesh_renderer: static_mesh_renderer
|
||||
.is_some_and(has_resolved_static_mesh_slot),
|
||||
has_model_ref,
|
||||
has_prefab_ref,
|
||||
has_prefab_instance,
|
||||
has_player_spawn,
|
||||
has_weapon_spawn,
|
||||
has_trigger_volume,
|
||||
has_post_process_volume,
|
||||
has_team_spawn,
|
||||
has_objective,
|
||||
has_physics: physics.contains(target),
|
||||
};
|
||||
let spec = icon_for_actor_components(components);
|
||||
if !desired.contains_key(&target) {
|
||||
continue;
|
||||
}
|
||||
let Some(material) = assets.materials.get(&spec.image).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let transform = desired_icon_transform(global, camera, ui_state.viewport_rect.height());
|
||||
commands.spawn((
|
||||
EditorOnly,
|
||||
RaytracingExcluded,
|
||||
NoFrustumCulling,
|
||||
Name::new("Actor Root Icon"),
|
||||
ActorIconProxy { target },
|
||||
Mesh3d(assets.mesh.clone()),
|
||||
MeshMaterial3d(material),
|
||||
transform,
|
||||
Visibility::Visible,
|
||||
ChildOf(target),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn active_editor_camera<'a>(
|
||||
camera_query: &'a Query<(&Camera, &GlobalTransform, Option<&Projection>), With<EditorCamera>>,
|
||||
) -> Option<(&'a Camera, &'a GlobalTransform, Option<&'a Projection>)> {
|
||||
camera_query
|
||||
.iter()
|
||||
.find(|(camera, _, _)| camera.is_active)
|
||||
.or_else(|| camera_query.iter().next())
|
||||
}
|
||||
|
||||
fn desired_icon_transform(
|
||||
parent_global: &GlobalTransform,
|
||||
camera: Option<(&Camera, &GlobalTransform, Option<&Projection>)>,
|
||||
viewport_height: f32,
|
||||
) -> Transform {
|
||||
let translation = parent_global.translation();
|
||||
let Some((_, camera_global, projection)) = camera else {
|
||||
return Transform::from_translation(Vec3::ZERO).with_scale(Vec3::splat(0.5));
|
||||
};
|
||||
let size = icon_world_size(
|
||||
translation,
|
||||
camera_global,
|
||||
projection,
|
||||
viewport_height.max(1.0),
|
||||
);
|
||||
let desired_global = Transform {
|
||||
translation,
|
||||
rotation: camera_global.rotation(),
|
||||
scale: Vec3::splat(size),
|
||||
};
|
||||
let local = parent_global.affine().inverse() * GlobalTransform::from(desired_global).affine();
|
||||
Transform::from_matrix(Mat4::from(local))
|
||||
}
|
||||
|
||||
fn icon_world_size(
|
||||
target: Vec3,
|
||||
camera_global: &GlobalTransform,
|
||||
projection: Option<&Projection>,
|
||||
viewport_height: f32,
|
||||
) -> f32 {
|
||||
let camera_position = camera_global.translation();
|
||||
let pixels_to_view = ICON_TARGET_PIXELS / viewport_height;
|
||||
let world_height = match projection {
|
||||
Some(Projection::Perspective(projection)) => {
|
||||
let distance = camera_position.distance(target).max(0.1);
|
||||
2.0 * distance * (projection.fov * 0.5).tan()
|
||||
}
|
||||
Some(Projection::Orthographic(projection)) => projection.area.height().abs().max(0.1),
|
||||
_ => {
|
||||
let distance = camera_position.distance(target).max(0.1);
|
||||
2.0 * distance * (DEFAULT_PERSPECTIVE_FOV * 0.5).tan()
|
||||
}
|
||||
};
|
||||
(world_height * pixels_to_view).clamp(ICON_MIN_WORLD_SIZE, ICON_MAX_WORLD_SIZE)
|
||||
}
|
||||
|
||||
fn icon_category_enabled(
|
||||
settings: &EditorVisualizationSettings,
|
||||
category: ActorIconCategory,
|
||||
) -> bool {
|
||||
match category {
|
||||
ActorIconCategory::Actor => settings.show_actor_icon_actor,
|
||||
ActorIconCategory::Mesh => settings.show_actor_icon_mesh,
|
||||
ActorIconCategory::Light => settings.show_actor_icon_light,
|
||||
ActorIconCategory::Physics => settings.show_actor_icon_physics,
|
||||
ActorIconCategory::Gameplay => settings.show_actor_icon_gameplay,
|
||||
ActorIconCategory::Volume => settings.show_actor_icon_volume,
|
||||
ActorIconCategory::PrefabModel => settings.show_actor_icon_prefab_model,
|
||||
ActorIconCategory::Debug => settings.show_actor_icon_debug,
|
||||
}
|
||||
}
|
||||
|
||||
fn has_resolved_static_mesh_slot(renderer: &StaticMeshRenderer) -> bool {
|
||||
renderer.slots.iter().any(|slot| slot.mesh.is_resolved())
|
||||
}
|
||||
|
||||
fn icon_for_actor_components(components: ActorIconComponents) -> ActorIconSpec {
|
||||
let warning = ActorIconSpec {
|
||||
image: ActorIconImage::Warning,
|
||||
category: ActorIconCategory::Debug,
|
||||
};
|
||||
let Some(kind) = components.kind else {
|
||||
return ActorIconSpec {
|
||||
image: ActorIconImage::Missing,
|
||||
category: ActorIconCategory::Debug,
|
||||
};
|
||||
};
|
||||
|
||||
match kind {
|
||||
ActorKind::StaticMesh => {
|
||||
if components.has_primitive || components.has_static_mesh_renderer {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::Mesh,
|
||||
category: ActorIconCategory::Mesh,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::ImportedModel => {
|
||||
if components.has_model_ref {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::Mesh,
|
||||
category: ActorIconCategory::PrefabModel,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::Light => match components.light_kind {
|
||||
Some(AuthoringLightKind::Point) => ActorIconSpec {
|
||||
image: ActorIconImage::LightPoint,
|
||||
category: ActorIconCategory::Light,
|
||||
},
|
||||
Some(AuthoringLightKind::Spot) => ActorIconSpec {
|
||||
image: ActorIconImage::LightSpot,
|
||||
category: ActorIconCategory::Light,
|
||||
},
|
||||
Some(AuthoringLightKind::Directional) => ActorIconSpec {
|
||||
image: ActorIconImage::LightDirectional,
|
||||
category: ActorIconCategory::Light,
|
||||
},
|
||||
None => warning,
|
||||
},
|
||||
ActorKind::PrefabAnchor => {
|
||||
if components.has_prefab_ref || components.has_prefab_instance {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::Generic,
|
||||
category: ActorIconCategory::PrefabModel,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::PlayerSpawn => {
|
||||
if components.has_player_spawn {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::GameSpawn,
|
||||
category: ActorIconCategory::Gameplay,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::WeaponSpawn => {
|
||||
if components.has_weapon_spawn {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::GameSpawn,
|
||||
category: ActorIconCategory::Gameplay,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::TriggerVolume => {
|
||||
if components.has_trigger_volume {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::GameTrigger,
|
||||
category: ActorIconCategory::Gameplay,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::PostProcessVolume => {
|
||||
if components.has_post_process_volume {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::PostProcessVolume,
|
||||
category: ActorIconCategory::Volume,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::TeamSpawn => {
|
||||
if components.has_team_spawn {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::GameSpawn,
|
||||
category: ActorIconCategory::Gameplay,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::Objective => {
|
||||
if components.has_objective {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::GameMarker,
|
||||
category: ActorIconCategory::Gameplay,
|
||||
}
|
||||
} else {
|
||||
warning
|
||||
}
|
||||
}
|
||||
ActorKind::Empty => {
|
||||
if components.has_physics {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::PhysicsCollider,
|
||||
category: ActorIconCategory::Physics,
|
||||
}
|
||||
} else {
|
||||
ActorIconSpec {
|
||||
image: ActorIconImage::Empty,
|
||||
category: ActorIconCategory::Actor,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resolves_directional_light_icon() {
|
||||
let spec = icon_for_actor_components(ActorIconComponents {
|
||||
kind: Some(ActorKind::Light),
|
||||
light_kind: Some(AuthoringLightKind::Directional),
|
||||
..default()
|
||||
});
|
||||
|
||||
assert_eq!(spec.image, ActorIconImage::LightDirectional);
|
||||
assert_eq!(spec.category, ActorIconCategory::Light);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_static_mesh_uses_warning_icon() {
|
||||
let spec = icon_for_actor_components(ActorIconComponents {
|
||||
kind: Some(ActorKind::StaticMesh),
|
||||
..default()
|
||||
});
|
||||
|
||||
assert_eq!(spec.image, ActorIconImage::Warning);
|
||||
assert_eq!(spec.category, ActorIconCategory::Debug);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_actor_with_collider_uses_physics_category() {
|
||||
let spec = icon_for_actor_components(ActorIconComponents {
|
||||
kind: Some(ActorKind::Empty),
|
||||
has_physics: true,
|
||||
..default()
|
||||
});
|
||||
|
||||
assert_eq!(spec.image, ActorIconImage::PhysicsCollider);
|
||||
assert_eq!(spec.category, ActorIconCategory::Physics);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
use bevy::camera::visibility::RenderLayers;
|
||||
use bevy::input::mouse::{AccumulatedMouseMotion, MouseWheel};
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::{EguiContexts, EguiGlobalSettings, PrimaryEguiContext};
|
||||
use transform_gizmo_bevy::prelude::GizmoCamera;
|
||||
|
||||
use crate::infra::EditorOnly;
|
||||
use crate::state::scene_tools_active;
|
||||
use crate::ui::UiState;
|
||||
use settings::ProjectSettings;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct EditorCamera {
|
||||
pub fly_speed: f32,
|
||||
pub look_sensitivity: f32,
|
||||
pub pan_speed: f32,
|
||||
}
|
||||
|
||||
impl Default for EditorCamera {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fly_speed: 14.0,
|
||||
look_sensitivity: 0.003,
|
||||
pan_speed: 0.015,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EditorCameraPlugin;
|
||||
|
||||
impl Plugin for EditorCameraPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Startup, spawn_editor_camera).add_systems(
|
||||
Update,
|
||||
(sync_editor_camera_from_settings, update_editor_camera)
|
||||
.chain()
|
||||
.run_if(scene_tools_active),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_editor_camera_from_settings(
|
||||
settings: Res<ProjectSettings>,
|
||||
mut cameras: Query<&mut EditorCamera>,
|
||||
) {
|
||||
if !settings.is_changed() {
|
||||
return;
|
||||
}
|
||||
let input = &settings.input;
|
||||
for mut camera in &mut cameras {
|
||||
camera.fly_speed = input.editor_fly_speed;
|
||||
camera.look_sensitivity = input.editor_look_sensitivity;
|
||||
camera.pan_speed = input.editor_pan_speed;
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_editor_camera(
|
||||
mut commands: Commands,
|
||||
mut egui_global_settings: ResMut<EguiGlobalSettings>,
|
||||
) {
|
||||
// Own the egui primary context explicitly. If bevy_egui auto-attaches it to
|
||||
// a 3D camera, `set_camera_viewport` then crops egui's own screen rect to the
|
||||
// shrinking viewport region, and egui_dock eventually lays out into a NaN
|
||||
// rect (panic: "rect is nan in advance_cursor_after_rect").
|
||||
egui_global_settings.auto_create_primary_context = false;
|
||||
|
||||
commands.spawn((
|
||||
Name::new("Editor Camera"),
|
||||
EditorOnly,
|
||||
EditorCamera::default(),
|
||||
RenderLayers::default(),
|
||||
GizmoCamera,
|
||||
Camera3d::default(),
|
||||
Camera {
|
||||
clear_color: ClearColorConfig::Custom(Color::srgba(0.0, 0.0, 0.0, 1.0)),
|
||||
..default()
|
||||
},
|
||||
Transform::from_xyz(10.0, 8.0, 18.0).looking_at(Vec3::ZERO, Vec3::Y),
|
||||
));
|
||||
|
||||
// Dedicated full-window 2D camera that renders only egui on top of the 3D
|
||||
// scene. Keeping the egui context off the 3D cameras avoids the
|
||||
// viewport-cropping feedback loop described above.
|
||||
commands.spawn((
|
||||
Name::new("Editor Egui Camera"),
|
||||
EditorOnly,
|
||||
Camera2d,
|
||||
PrimaryEguiContext,
|
||||
RenderLayers::none(),
|
||||
Camera {
|
||||
order: 10,
|
||||
clear_color: ClearColorConfig::None,
|
||||
..default()
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn update_editor_camera(
|
||||
time: Res<Time>,
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
buttons: Res<ButtonInput<MouseButton>>,
|
||||
mouse_motion: Res<AccumulatedMouseMotion>,
|
||||
mut scroll: MessageReader<MouseWheel>,
|
||||
mut contexts: EguiContexts,
|
||||
ui_state: Res<UiState>,
|
||||
mut cameras: Query<(&mut Transform, &EditorCamera)>,
|
||||
) -> Result {
|
||||
let ctx = contexts.ctx_mut()?;
|
||||
let in_scene = ui_state.pointer_in_viewport;
|
||||
if ctx.wants_keyboard_input() {
|
||||
return Ok(());
|
||||
}
|
||||
if !in_scene && ctx.wants_pointer_input() {
|
||||
return Ok(());
|
||||
}
|
||||
if in_scene && ctx.wants_pointer_input() && !buttons.pressed(MouseButton::Right) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let dt = time.delta_secs();
|
||||
let scroll_delta: f32 = scroll.read().map(|event| event.y).sum();
|
||||
|
||||
for (mut transform, camera) in &mut cameras {
|
||||
if buttons.pressed(MouseButton::Right) {
|
||||
let delta = mouse_motion.delta;
|
||||
if delta != Vec2::ZERO {
|
||||
let (yaw, pitch, _) = transform.rotation.to_euler(EulerRot::YXZ);
|
||||
let yaw = yaw - delta.x * camera.look_sensitivity;
|
||||
let pitch = (pitch - delta.y * camera.look_sensitivity).clamp(
|
||||
-std::f32::consts::FRAC_PI_2 + 0.01,
|
||||
std::f32::consts::FRAC_PI_2 - 0.01,
|
||||
);
|
||||
transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
let forward = transform.forward().as_vec3();
|
||||
let right = transform.right().as_vec3();
|
||||
let up = Vec3::Y;
|
||||
let mut wish = Vec3::ZERO;
|
||||
|
||||
if keys.pressed(KeyCode::KeyW) {
|
||||
wish += forward;
|
||||
}
|
||||
if keys.pressed(KeyCode::KeyS) {
|
||||
wish -= forward;
|
||||
}
|
||||
if keys.pressed(KeyCode::KeyD) {
|
||||
wish += right;
|
||||
}
|
||||
if keys.pressed(KeyCode::KeyA) {
|
||||
wish -= right;
|
||||
}
|
||||
if keys.pressed(KeyCode::KeyE) {
|
||||
wish += up;
|
||||
}
|
||||
if keys.pressed(KeyCode::KeyQ) {
|
||||
wish -= up;
|
||||
}
|
||||
|
||||
let sprint = if keys.pressed(KeyCode::ShiftLeft) {
|
||||
3.0
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
transform.translation += wish.normalize_or_zero() * camera.fly_speed * sprint * dt;
|
||||
transform.translation += forward * scroll_delta * camera.fly_speed * 0.08;
|
||||
|
||||
if buttons.pressed(MouseButton::Middle) {
|
||||
let delta = mouse_motion.delta;
|
||||
let distance_scale = transform.translation.length().max(1.0).sqrt();
|
||||
transform.translation +=
|
||||
(-right * delta.x + up * delta.y) * camera.pan_speed * distance_scale;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
use bevy::math::Rect;
|
||||
use bevy::prelude::*;
|
||||
use transform_gizmo_bevy::prelude::{GizmoMode, GizmoOptions, GizmoOrientation};
|
||||
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::ViewportDisplayMode;
|
||||
|
||||
#[derive(Resource, Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EditorGizmoMode {
|
||||
#[default]
|
||||
Translate,
|
||||
Rotate,
|
||||
Scale,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EditorGizmoSpace {
|
||||
#[default]
|
||||
World,
|
||||
Local,
|
||||
}
|
||||
|
||||
pub struct EditorGizmoPlugin;
|
||||
|
||||
impl Plugin for EditorGizmoPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<EditorGizmoMode>()
|
||||
.init_resource::<EditorGizmoSpace>()
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
handle_gizmo_hotkeys,
|
||||
sync_gizmo_viewport_rect,
|
||||
sync_gizmo_options,
|
||||
)
|
||||
.chain(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_gizmo_hotkeys(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
mut mode: ResMut<EditorGizmoMode>,
|
||||
mut space: ResMut<EditorGizmoSpace>,
|
||||
) {
|
||||
if display.clean_game_view {
|
||||
return;
|
||||
}
|
||||
if keys.just_pressed(KeyCode::KeyW) {
|
||||
*mode = EditorGizmoMode::Translate;
|
||||
}
|
||||
if keys.just_pressed(KeyCode::KeyE) {
|
||||
*mode = EditorGizmoMode::Rotate;
|
||||
}
|
||||
if keys.just_pressed(KeyCode::KeyR) {
|
||||
*mode = EditorGizmoMode::Scale;
|
||||
}
|
||||
if keys.just_pressed(KeyCode::KeyX) {
|
||||
*space = match *space {
|
||||
EditorGizmoSpace::World => EditorGizmoSpace::Local,
|
||||
EditorGizmoSpace::Local => EditorGizmoSpace::World,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps the viewport egui panel to gizmo cursor space (required for render-to-texture).
|
||||
fn sync_gizmo_viewport_rect(
|
||||
ui_state: Res<UiState>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
mut options: ResMut<GizmoOptions>,
|
||||
) {
|
||||
if display.clean_game_view {
|
||||
options.viewport_rect = None;
|
||||
return;
|
||||
}
|
||||
let panel = ui_state.viewport_rect;
|
||||
options.viewport_rect = if panel.width() > 1.0 && panel.height() > 1.0 {
|
||||
Some(Rect {
|
||||
min: Vec2::new(panel.min.x, panel.min.y),
|
||||
max: Vec2::new(panel.max.x, panel.max.y),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
|
||||
fn sync_gizmo_options(
|
||||
mode: Res<EditorGizmoMode>,
|
||||
space: Res<EditorGizmoSpace>,
|
||||
mut options: ResMut<GizmoOptions>,
|
||||
) {
|
||||
if !mode.is_changed() && !space.is_changed() {
|
||||
return;
|
||||
}
|
||||
|
||||
options.gizmo_modes = match *mode {
|
||||
EditorGizmoMode::Translate => GizmoMode::all_translate(),
|
||||
EditorGizmoMode::Rotate => GizmoMode::all_rotate(),
|
||||
EditorGizmoMode::Scale => GizmoMode::all_scale(),
|
||||
};
|
||||
options.gizmo_orientation = match *space {
|
||||
EditorGizmoSpace::World => GizmoOrientation::Global,
|
||||
EditorGizmoSpace::Local => GizmoOrientation::Local,
|
||||
};
|
||||
options.mode_override = None;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Viewport chrome, editor camera, selection, gizmos, and render views.
|
||||
|
||||
pub mod actor_icons;
|
||||
pub mod camera;
|
||||
pub mod gizmos;
|
||||
mod panel;
|
||||
pub mod render_view;
|
||||
pub mod rendering_diagnostics;
|
||||
pub mod selection;
|
||||
pub mod selection_outline;
|
||||
pub mod viewport_mode;
|
||||
pub mod visualizers;
|
||||
|
||||
pub use actor_icons::ActorIconsPlugin;
|
||||
pub use panel::*;
|
||||
pub use viewport_mode::EditorViewportMode;
|
||||
@@ -0,0 +1,282 @@
|
||||
//! Shared viewport controller: rects, raycast placement, grid, focus, bookmarks.
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::state::scene_tools_active;
|
||||
use crate::viewport::viewport_mode::EditorViewportModePlugin;
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::Window;
|
||||
use bevy_egui::egui;
|
||||
|
||||
/// Viewport display and snapping options (editor-only).
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct ViewportSettings {
|
||||
pub show_grid: bool,
|
||||
pub snap_translate: bool,
|
||||
pub snap_increment: f32,
|
||||
}
|
||||
|
||||
impl Default for ViewportSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
show_grid: true,
|
||||
snap_translate: true,
|
||||
snap_increment: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary viewport display state. `clean_game_view` hides editor-only overlays without
|
||||
/// changing the active camera or play possession.
|
||||
#[derive(Resource, Debug, Clone, Copy, Default)]
|
||||
pub struct ViewportDisplayMode {
|
||||
pub clean_game_view: bool,
|
||||
}
|
||||
|
||||
/// Saved editor fly-camera poses keyed by scene path.
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct CameraBookmarks {
|
||||
pub poses: Vec<(String, Transform)>,
|
||||
}
|
||||
|
||||
pub struct ViewportPlugin;
|
||||
|
||||
impl Plugin for ViewportPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<ViewportSettings>()
|
||||
.init_resource::<ViewportDisplayMode>()
|
||||
.init_resource::<CameraBookmarks>()
|
||||
.add_plugins(EditorViewportModePlugin)
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
focus_selection_hotkey,
|
||||
toggle_viewport_hotkeys,
|
||||
camera_bookmark_hotkeys,
|
||||
draw_viewport_grid,
|
||||
)
|
||||
.run_if(scene_tools_active),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical pixel size of a dock panel rect (for render-to-texture targets).
|
||||
pub fn panel_physical_size(window: &Window, rect: egui::Rect) -> Option<UVec2> {
|
||||
if rect == egui::Rect::NOTHING || rect.width() <= 1.0 || rect.height() <= 1.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let scale = window.scale_factor();
|
||||
let size = rect.size() * scale;
|
||||
Some(UVec2::new(size.x.max(64.0) as u32, size.y.max(64.0) as u32))
|
||||
}
|
||||
|
||||
/// Builds a world-space ray from a viewport pointer position (render-to-texture camera).
|
||||
///
|
||||
/// Maps panel-local egui coordinates into the editor camera's [`Camera::logical_viewport_rect`]
|
||||
/// so picking matches the offscreen target rather than the primary window.
|
||||
pub fn scene_view_ray(
|
||||
camera: &Camera,
|
||||
transform: &GlobalTransform,
|
||||
pointer_pos: egui::Pos2,
|
||||
scene_rect: egui::Rect,
|
||||
) -> Option<Ray3d> {
|
||||
if !scene_rect.contains(pointer_pos) {
|
||||
return None;
|
||||
}
|
||||
let rel = pointer_pos - scene_rect.min;
|
||||
let panel_size = scene_rect.size();
|
||||
if panel_size.x <= f32::EPSILON || panel_size.y <= f32::EPSILON {
|
||||
return None;
|
||||
}
|
||||
let rel_uv = Vec2::new(rel.x / panel_size.x, rel.y / panel_size.y);
|
||||
|
||||
if let Some(viewport) = camera.logical_viewport_rect() {
|
||||
let logical_pos =
|
||||
viewport.min + Vec2::new(rel_uv.x * viewport.width(), rel_uv.y * viewport.height());
|
||||
return camera.viewport_to_world(transform, logical_pos).ok();
|
||||
}
|
||||
|
||||
// Before `camera_system` fills target_info, build a ray from panel UV via NDC.
|
||||
let mut ndc = rel_uv * 2.0 - Vec2::ONE;
|
||||
ndc.y = -ndc.y;
|
||||
let view_from_clip = camera.computed.clip_from_view.inverse();
|
||||
let world_from_view = transform.affine();
|
||||
let view_near = view_from_clip.project_point3a(ndc.extend(1.0).into());
|
||||
let view_far = view_from_clip.project_point3a(ndc.extend(f32::EPSILON).into());
|
||||
let view_dir = view_far - view_near;
|
||||
let origin = world_from_view.transform_point3a(view_near).into();
|
||||
let direction = world_from_view.transform_vector3a(view_dir).into();
|
||||
Dir3::new(direction)
|
||||
.ok()
|
||||
.map(|direction| Ray3d { origin, direction })
|
||||
}
|
||||
|
||||
/// Spawns placement position from editor camera center ray to ground plane.
|
||||
pub fn editor_spawn_ground_position(world: &mut World, scene_rect: egui::Rect) -> Vec3 {
|
||||
let center = scene_rect.center();
|
||||
viewport_ground_position(world, center, scene_rect).unwrap_or(Vec3::ZERO)
|
||||
}
|
||||
|
||||
/// Raycasts from a viewport pointer position to the ground plane (y = 0).
|
||||
pub fn viewport_ground_position(
|
||||
world: &mut World,
|
||||
pointer_pos: egui::Pos2,
|
||||
scene_rect: egui::Rect,
|
||||
) -> Option<Vec3> {
|
||||
let mut query = world.query_filtered::<(&Camera, &GlobalTransform), With<EditorCamera>>();
|
||||
for (camera, transform) in query.iter(world) {
|
||||
if !camera.is_active {
|
||||
continue;
|
||||
}
|
||||
let ray = scene_view_ray(camera, transform, pointer_pos, scene_rect)?;
|
||||
let direction = ray.direction.as_vec3();
|
||||
if direction.y.abs() < 0.0001 {
|
||||
return Some(ray.origin);
|
||||
}
|
||||
let t = -ray.origin.y / direction.y;
|
||||
return Some(ray.origin + direction * t.max(0.0));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Snaps a world position to the configured grid increment.
|
||||
pub fn snap_translation(position: Vec3, settings: &ViewportSettings) -> Vec3 {
|
||||
if !settings.snap_translate {
|
||||
return position;
|
||||
}
|
||||
let step = settings.snap_increment.max(0.01);
|
||||
Vec3::new(
|
||||
(position.x / step).round() * step,
|
||||
position.y,
|
||||
(position.z / step).round() * step,
|
||||
)
|
||||
}
|
||||
|
||||
fn focus_selection_hotkey(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
selected: Res<SelectedEntity>,
|
||||
mut editor_cameras: Query<&mut Transform, With<EditorCamera>>,
|
||||
targets: Query<&GlobalTransform>,
|
||||
) {
|
||||
if display.clean_game_view {
|
||||
return;
|
||||
}
|
||||
if !keys.just_pressed(KeyCode::KeyF) {
|
||||
return;
|
||||
}
|
||||
let Some(entity) = selected.0 else {
|
||||
return;
|
||||
};
|
||||
let Ok(target) = targets.get(entity) else {
|
||||
return;
|
||||
};
|
||||
let center = target.translation();
|
||||
for mut transform in &mut editor_cameras {
|
||||
let offset = transform.translation - center;
|
||||
let distance = offset.length().max(8.0);
|
||||
transform.translation = center - transform.forward().as_vec3() * distance;
|
||||
transform.look_at(center, Vec3::Y);
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_viewport_hotkeys(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
mut settings: ResMut<ViewportSettings>,
|
||||
mut display: ResMut<ViewportDisplayMode>,
|
||||
) {
|
||||
if keys.just_pressed(KeyCode::KeyG) {
|
||||
let ctrl = keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
|
||||
if ctrl {
|
||||
settings.show_grid = !settings.show_grid;
|
||||
} else {
|
||||
display.clean_game_view = !display.clean_game_view;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn camera_bookmark_hotkeys(
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
scene_io: Res<crate::scene_io::SceneIo>,
|
||||
mut bookmarks: ResMut<CameraBookmarks>,
|
||||
mut editor_cameras: Query<&mut Transform, With<EditorCamera>>,
|
||||
) {
|
||||
let shift = keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight);
|
||||
let ctrl = keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
|
||||
if !shift || !ctrl {
|
||||
return;
|
||||
}
|
||||
|
||||
let scene_key = scene_io
|
||||
.active_path
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|| "__unsaved__".into());
|
||||
|
||||
if keys.just_pressed(KeyCode::Digit1) {
|
||||
let Ok(transform) = editor_cameras.single() else {
|
||||
return;
|
||||
};
|
||||
save_camera_bookmark(&mut bookmarks, &scene_key, *transform);
|
||||
}
|
||||
|
||||
if keys.just_pressed(KeyCode::Digit2) {
|
||||
let Some(saved) = recall_camera_bookmark(&bookmarks, &scene_key) else {
|
||||
return;
|
||||
};
|
||||
for mut transform in &mut editor_cameras {
|
||||
*transform = saved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_viewport_grid(
|
||||
settings: Res<ViewportSettings>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
mut gizmos: Gizmos,
|
||||
) {
|
||||
if display.clean_game_view || !settings.show_grid {
|
||||
return;
|
||||
}
|
||||
|
||||
let step = settings.snap_increment.max(0.5);
|
||||
let extent = 32.0;
|
||||
let mut x = -extent;
|
||||
while x <= extent {
|
||||
gizmos.line(
|
||||
Vec3::new(x, 0.0, -extent),
|
||||
Vec3::new(x, 0.0, extent),
|
||||
Color::srgba(0.35, 0.38, 0.42, 0.35),
|
||||
);
|
||||
x += step;
|
||||
}
|
||||
let mut z = -extent;
|
||||
while z <= extent {
|
||||
gizmos.line(
|
||||
Vec3::new(-extent, 0.0, z),
|
||||
Vec3::new(extent, 0.0, z),
|
||||
Color::srgba(0.35, 0.38, 0.42, 0.35),
|
||||
);
|
||||
z += step;
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores the current editor camera as a bookmark named by scene path.
|
||||
pub fn save_camera_bookmark(
|
||||
bookmarks: &mut CameraBookmarks,
|
||||
scene_path: &str,
|
||||
transform: Transform,
|
||||
) {
|
||||
bookmarks.poses.retain(|(path, _)| path != scene_path);
|
||||
bookmarks.poses.push((scene_path.to_string(), transform));
|
||||
}
|
||||
|
||||
/// Recalls a bookmark for the given scene path, if any.
|
||||
pub fn recall_camera_bookmark(bookmarks: &CameraBookmarks, scene_path: &str) -> Option<Transform> {
|
||||
bookmarks
|
||||
.poses
|
||||
.iter()
|
||||
.find(|(path, _)| path == scene_path)
|
||||
.map(|(_, transform)| *transform)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! Exclusive ownership of the full project PBR stack (WYSIWYG, one active 3D view).
|
||||
//!
|
||||
//! Only [`sync_viewport_camera_stack`] mutates post-FX; scene/play systems set render targets only.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use bevy::anti_alias::taa::TemporalAntiAliasing;
|
||||
use bevy::core_pipeline::tonemapping::Tonemapping;
|
||||
use bevy::pbr::{Atmosphere, ScatteringMedium, ScreenSpaceAmbientOcclusion};
|
||||
use bevy::post_process::auto_exposure::AutoExposure;
|
||||
use bevy::post_process::bloom::Bloom;
|
||||
use bevy::prelude::*;
|
||||
use bevy::render::view::Hdr;
|
||||
use game::rendering::{
|
||||
clear_viewport_camera_stack, has_local_shadow_lights, resolve_viewport_camera_owner,
|
||||
sync_viewport_camera_stack, SolariRaytracingSceneStats, ViewportCameraOwner,
|
||||
ViewportFxSnapshot, ViewportStackApply,
|
||||
};
|
||||
use settings::{
|
||||
ActiveCameraRenderProfile, EffectiveRenderStack, GiPath, ProjectRenderCamera, ProjectSettings,
|
||||
RenderingCapabilities,
|
||||
};
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::render_target::ViewportRenderTarget;
|
||||
use crate::state::{EditorMode, PlayPossession};
|
||||
use sim::PlayerCamera;
|
||||
|
||||
/// Updated before [`sync_project_render_view`] so the render-view system stays within Bevy's param limit.
|
||||
#[derive(Resource, Default, Clone, Copy)]
|
||||
pub struct ViewportLocalShadowLights(pub bool);
|
||||
|
||||
pub struct RenderViewPlugin;
|
||||
|
||||
impl Plugin for RenderViewPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<ViewportLocalShadowLights>()
|
||||
.add_systems(
|
||||
PostUpdate,
|
||||
(sync_viewport_local_shadow_lights, sync_project_render_view)
|
||||
.chain()
|
||||
.after(crate::scene_view::sync_editor_camera_viewport_target)
|
||||
.after(crate::play::sync_play_camera_target)
|
||||
.after(game_hot::resolve_active_camera_render_profile_system),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_viewport_local_shadow_lights(
|
||||
points: Query<&PointLight>,
|
||||
spots: Query<&SpotLight>,
|
||||
mut flag: ResMut<ViewportLocalShadowLights>,
|
||||
) {
|
||||
flag.0 = has_local_shadow_lights(&points, &spots);
|
||||
}
|
||||
|
||||
fn owner_from_state(mode: EditorMode, possession: PlayPossession) -> ViewportCameraOwner {
|
||||
let editing = matches!(mode, EditorMode::Editing);
|
||||
let playing_possessed = mode == EditorMode::Playing && possession == PlayPossession::Possessed;
|
||||
resolve_viewport_camera_owner(editing, playing_possessed)
|
||||
}
|
||||
|
||||
type CameraFxState = (bool, bool, bool, bool, bool, bool, bool, bool);
|
||||
|
||||
fn fx_snapshot(state: CameraFxState) -> ViewportFxSnapshot {
|
||||
ViewportFxSnapshot {
|
||||
has_stack: state.0,
|
||||
has_atmosphere: state.1,
|
||||
has_tonemapping: state.2,
|
||||
has_bloom: state.3,
|
||||
has_ssao: state.4,
|
||||
has_taa: state.5,
|
||||
has_hdr: state.6,
|
||||
has_auto_exposure: state.7,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RenderViewCache {
|
||||
key: Option<(EditorMode, PlayPossession)>,
|
||||
target: Option<AssetId<Image>>,
|
||||
profile: Option<ActiveCameraRenderProfile>,
|
||||
effective_gi: Option<GiPath>,
|
||||
stack: Option<EffectiveRenderStack>,
|
||||
}
|
||||
|
||||
/// Ensures exactly one camera has the full project rendering stack for the current mode.
|
||||
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||
fn sync_project_render_view(
|
||||
mode: Res<State<EditorMode>>,
|
||||
possession: Res<PlayPossession>,
|
||||
settings: Res<ProjectSettings>,
|
||||
profile: Res<ActiveCameraRenderProfile>,
|
||||
mut caps: ResMut<RenderingCapabilities>,
|
||||
solari_stats: Res<SolariRaytracingSceneStats>,
|
||||
viewport_target: Res<ViewportRenderTarget>,
|
||||
local_shadow_lights: Res<ViewportLocalShadowLights>,
|
||||
mut commands: Commands,
|
||||
mut mediums: ResMut<Assets<ScatteringMedium>>,
|
||||
editor_cameras: Query<Entity, With<EditorCamera>>,
|
||||
player_cameras: Query<Entity, With<PlayerCamera>>,
|
||||
stacked: Query<Entity, With<ProjectRenderCamera>>,
|
||||
camera_fx: Query<(
|
||||
Has<ProjectRenderCamera>,
|
||||
Has<Atmosphere>,
|
||||
Has<Tonemapping>,
|
||||
Has<Bloom>,
|
||||
Has<ScreenSpaceAmbientOcclusion>,
|
||||
Has<TemporalAntiAliasing>,
|
||||
Has<Hdr>,
|
||||
Has<AutoExposure>,
|
||||
)>,
|
||||
mut cache: Local<RenderViewCache>,
|
||||
) {
|
||||
let mode = *mode.get();
|
||||
let possession = *possession;
|
||||
let owner = owner_from_state(mode, possession);
|
||||
let key = (mode, possession);
|
||||
let owner_changed = cache.key != Some(key);
|
||||
let settings_changed = settings.is_changed();
|
||||
let profile_changed = profile.is_changed() || cache.profile != Some(profile.clone());
|
||||
cache.profile = Some(profile.clone());
|
||||
let stack = game::rendering::effective_viewport_render_stack(
|
||||
profile.gi_path,
|
||||
&caps,
|
||||
Some(&solari_stats),
|
||||
local_shadow_lights.0,
|
||||
);
|
||||
if cache.stack != Some(stack) {
|
||||
info!(
|
||||
"Rendering stack: requested={:?} effective={:?} fallback={:?} rt_supported={} solari_ready={} local_shadow_lights={} tagged_meshes={} render_instances={} render_directional_lights={} bind_group_ready={} emissive_meshes={}",
|
||||
stack.requested_gi_path,
|
||||
stack.effective_gi_path,
|
||||
stack.fallback_reason,
|
||||
caps.rt_supported,
|
||||
stack.solari_ready,
|
||||
stack.local_shadow_lights,
|
||||
solari_stats.tagged_meshes,
|
||||
solari_stats.render_instances,
|
||||
solari_stats.render_directional_lights,
|
||||
solari_stats.render_bind_group_ready,
|
||||
solari_stats.emissive_meshes,
|
||||
);
|
||||
cache.stack = Some(stack);
|
||||
}
|
||||
let effective_gi = stack.effective_gi_path;
|
||||
let solari_readiness_changed = cache.effective_gi != Some(effective_gi);
|
||||
cache.effective_gi = Some(effective_gi);
|
||||
|
||||
let active_target = viewport_target.0.as_ref().map(|t| t.image.id());
|
||||
let target_changed = cache.target != active_target;
|
||||
cache.target = active_target;
|
||||
|
||||
if !owner_changed
|
||||
&& !settings_changed
|
||||
&& !target_changed
|
||||
&& !profile_changed
|
||||
&& !solari_readiness_changed
|
||||
{
|
||||
return;
|
||||
}
|
||||
cache.key = Some(key);
|
||||
|
||||
let Some(_) = active_target else {
|
||||
return;
|
||||
};
|
||||
|
||||
let active: HashSet<Entity> = match owner {
|
||||
ViewportCameraOwner::EditorFly => editor_cameras.iter().collect(),
|
||||
ViewportCameraOwner::Player => player_cameras.iter().collect(),
|
||||
};
|
||||
|
||||
if owner_changed {
|
||||
for entity in stacked.iter() {
|
||||
if !active.contains(&entity) {
|
||||
clear_viewport_camera_stack(&mut commands, entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if owner_changed
|
||||
|| settings_changed
|
||||
|| target_changed
|
||||
|| profile_changed
|
||||
|| solari_readiness_changed
|
||||
{
|
||||
for entity in &active {
|
||||
let apply = if owner_changed {
|
||||
ViewportStackApply::Full
|
||||
} else if let Ok(state) = camera_fx.get(*entity) {
|
||||
let snap = fx_snapshot(state);
|
||||
if snap.has_stack {
|
||||
ViewportStackApply::Incremental(snap)
|
||||
} else {
|
||||
ViewportStackApply::Full
|
||||
}
|
||||
} else {
|
||||
ViewportStackApply::Full
|
||||
};
|
||||
sync_viewport_camera_stack(
|
||||
&mut commands,
|
||||
*entity,
|
||||
&profile,
|
||||
&mut caps,
|
||||
Some(&solari_stats),
|
||||
local_shadow_lights.0,
|
||||
&mut mediums,
|
||||
apply,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
//! Window → Rendering: active camera, project defaults, and volume list.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use game::rendering::{
|
||||
camera_auto_exposure_active, effective_viewport_render_stack, hdr_enabled_profile,
|
||||
SolariRaytracingSceneStats,
|
||||
};
|
||||
use settings::{
|
||||
ActiveCameraRenderProfile, ActiveVolumeContribution, ExposureMode, GiPath, ProjectSettings,
|
||||
RenderFallbackReason, RenderingCapabilities,
|
||||
};
|
||||
use shared::{
|
||||
ActorKind, AuthoringLightKind, LevelObject, LightDesc, PostProcessVolumeDesc, ProjectSun,
|
||||
};
|
||||
|
||||
use crate::history::{spawn_with_history, EditorEntitySnapshot};
|
||||
use crate::project::settings_ui::{open_project_settings_panel, ProjectSettingsPanel};
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::ui::helpers::focus_editor_camera_on_selection;
|
||||
use crate::viewport::EditorViewportMode;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct RenderingDiagnosticsPanel {
|
||||
pub open: bool,
|
||||
tab: RenderingPanelTab,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
enum RenderingPanelTab {
|
||||
#[default]
|
||||
Active,
|
||||
Project,
|
||||
Volumes,
|
||||
}
|
||||
|
||||
pub fn rendering_diagnostics_window(world: &mut World, ctx: &egui::Context, open: &mut bool) {
|
||||
if !*open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Rendering")
|
||||
.open(open)
|
||||
.default_width(440.0)
|
||||
.show(ctx, |ui| {
|
||||
rendering_diagnostics_ui(world, ui);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn rendering_diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
|
||||
let mut tab = world.resource::<RenderingDiagnosticsPanel>().tab;
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.selectable_value(&mut tab, RenderingPanelTab::Active, "Active Camera");
|
||||
ui.selectable_value(&mut tab, RenderingPanelTab::Project, "Project");
|
||||
ui.selectable_value(&mut tab, RenderingPanelTab::Volumes, "Volumes");
|
||||
});
|
||||
world.resource_mut::<RenderingDiagnosticsPanel>().tab = tab;
|
||||
ui.separator();
|
||||
|
||||
match tab {
|
||||
RenderingPanelTab::Active => active_camera_tab(world, ui),
|
||||
RenderingPanelTab::Project => project_tab(world, ui),
|
||||
RenderingPanelTab::Volumes => volumes_tab(world, ui),
|
||||
}
|
||||
}
|
||||
|
||||
fn active_camera_tab(world: &mut World, ui: &mut egui::Ui) {
|
||||
let profile = world.resource::<ActiveCameraRenderProfile>().clone();
|
||||
let caps = world.resource::<RenderingCapabilities>().clone();
|
||||
let contributions = world.resource::<ActiveVolumeContribution>().clone();
|
||||
let solari_stats = world.get_resource::<SolariRaytracingSceneStats>().copied();
|
||||
let local_shadow_lights = game::rendering::world_has_local_shadow_lights(world);
|
||||
let stack = effective_viewport_render_stack(
|
||||
profile.gi_path,
|
||||
&caps,
|
||||
solari_stats.as_ref(),
|
||||
local_shadow_lights,
|
||||
);
|
||||
|
||||
let gi_label = match (
|
||||
stack.requested_gi_path,
|
||||
stack.effective_gi_path,
|
||||
stack.fallback_reason,
|
||||
) {
|
||||
(GiPath::Forward, _, _) => "Forward PBR",
|
||||
(GiPath::SolariDeferred, GiPath::SolariDeferred, _) => "Solari deferred",
|
||||
(GiPath::SolariDeferred, _, Some(RenderFallbackReason::LocalShadowLights)) => {
|
||||
"Solari requested, Forward (local shadow lights)"
|
||||
}
|
||||
(GiPath::SolariDeferred, _, Some(RenderFallbackReason::RtUnsupported)) => {
|
||||
"Solari requested, Forward (RT unsupported)"
|
||||
}
|
||||
(GiPath::SolariDeferred, _, None) => "Solari requested",
|
||||
};
|
||||
ui.label(format!("GI path: {gi_label}"));
|
||||
ui.label(format!(
|
||||
"Stack: requested={:?}, effective={:?}, fallback={:?}",
|
||||
stack.requested_gi_path, stack.effective_gi_path, stack.fallback_reason
|
||||
));
|
||||
if stack.requested_gi_path == GiPath::SolariDeferred
|
||||
&& stack.effective_gi_path == GiPath::SolariDeferred
|
||||
{
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Solari deferred: directional lights and emissive meshes affect lighting; point/spot lights are Forward-only in Bevy 0.18.",
|
||||
);
|
||||
} else if stack.fallback_reason == Some(RenderFallbackReason::LocalShadowLights) {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Point/spot lights with shadows require Forward PBR; GI auto-falls back while they are in the scene.",
|
||||
);
|
||||
} else if stack.fallback_reason == Some(RenderFallbackReason::RtUnsupported)
|
||||
|| (!caps.rt_supported && profile.gi_path == GiPath::Forward)
|
||||
{
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Forward fallback — Solari RT features unavailable on this GPU.",
|
||||
);
|
||||
}
|
||||
if stack.requested_gi_path == GiPath::SolariDeferred && !stack.solari_ready {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Solari is active/requested but still warming up or missing scene readiness; see Solari raytracing scene below.",
|
||||
);
|
||||
}
|
||||
|
||||
runtime_lighting_summary(world, ui);
|
||||
solari_geometry_summary(world, ui);
|
||||
|
||||
ui.separator();
|
||||
let auto_active = camera_auto_exposure_active(&profile, &caps);
|
||||
match profile.exposure_mode {
|
||||
ExposureMode::Auto if auto_active => {
|
||||
ui.label(format!(
|
||||
"Exposure: Auto (brighten {:.1} / darken {:.1} f-stops/s)",
|
||||
profile.auto_exposure_speed_brighten, profile.auto_exposure_speed_darken
|
||||
));
|
||||
}
|
||||
ExposureMode::Auto => {
|
||||
ui.label(format!(
|
||||
"Exposure: Auto requested — using manual {:.2} EV100",
|
||||
profile.exposure_ev100
|
||||
));
|
||||
if !profile.hdr {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Fallback: HDR is disabled in project settings.",
|
||||
);
|
||||
} else if !hdr_enabled_profile(&profile) {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Fallback: HDR pass off (check BEVY_FPS_HDR or project HDR).",
|
||||
);
|
||||
} else if !caps.auto_exposure_supported {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Fallback: GPU compute shaders unavailable.",
|
||||
);
|
||||
}
|
||||
}
|
||||
ExposureMode::Manual => {
|
||||
ui.label(format!(
|
||||
"Exposure: Manual ({:.2} EV100)",
|
||||
profile.exposure_ev100
|
||||
));
|
||||
let project = world.resource::<ProjectSettings>();
|
||||
if project.rendering.exposure_mode == ExposureMode::Auto {
|
||||
ui.small("Post-process volume overrides exposure EV100 (manual for this view).");
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.label(format!(
|
||||
"Fog: rgb({:.2},{:.2},{:.2}) density {:.4}",
|
||||
profile.fog_color[0], profile.fog_color[1], profile.fog_color[2], profile.fog_density
|
||||
));
|
||||
ui.label(format!(
|
||||
"Post-FX: hdr={} target_hdr={} bloom={} taa={} ssao={} atmosphere={} tonemap={}",
|
||||
profile.hdr,
|
||||
hdr_enabled_profile(&profile) || stack.effective_gi_path == GiPath::SolariDeferred,
|
||||
profile.bloom,
|
||||
profile.taa,
|
||||
profile.ssao,
|
||||
profile.atmosphere,
|
||||
profile.tonemapping_aces
|
||||
));
|
||||
if let Some(effect) = &profile.fullscreen_effect {
|
||||
ui.label(format!("Fullscreen effect: {effect}"));
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
ui.heading("Contributing volumes");
|
||||
if contributions.entries.is_empty() {
|
||||
ui.label("No volumes at camera position — using project defaults.");
|
||||
} else {
|
||||
for entry in &contributions.entries {
|
||||
ui.label(format!(
|
||||
"{} — {:.0}% weight, {} overrides",
|
||||
entry.label,
|
||||
entry.weight * 100.0,
|
||||
entry.override_count
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if ui.button("Select overlapping volumes at camera").clicked() {
|
||||
select_volumes_at_camera(world);
|
||||
}
|
||||
|
||||
if let Some(mode) = world.get_resource::<EditorViewportMode>() {
|
||||
ui.separator();
|
||||
let mode_label = match *mode {
|
||||
EditorViewportMode::Lit => "Lit",
|
||||
EditorViewportMode::Unlit => "Unlit",
|
||||
EditorViewportMode::Collider => "Collider",
|
||||
};
|
||||
ui.label(format!("Viewport mode: {mode_label}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn runtime_lighting_summary(world: &mut World, ui: &mut egui::Ui) {
|
||||
ui.separator();
|
||||
ui.heading("Runtime lights");
|
||||
|
||||
let directional = world.query::<&DirectionalLight>().iter(world).count();
|
||||
let point = world.query::<&PointLight>().iter(world).count();
|
||||
let spot = world.query::<&SpotLight>().iter(world).count();
|
||||
let shadowed_directional = world
|
||||
.query::<&DirectionalLight>()
|
||||
.iter(world)
|
||||
.filter(|light| light.shadows_enabled)
|
||||
.count();
|
||||
let shadowed_point = world
|
||||
.query::<&PointLight>()
|
||||
.iter(world)
|
||||
.filter(|light| light.shadows_enabled)
|
||||
.count();
|
||||
let shadowed_spot = world
|
||||
.query::<&SpotLight>()
|
||||
.iter(world)
|
||||
.filter(|light| light.shadows_enabled)
|
||||
.count();
|
||||
ui.label(format!(
|
||||
"Counts: {directional} directional, {point} point, {spot} spot"
|
||||
));
|
||||
ui.label(format!(
|
||||
"Shadow casters: {shadowed_directional} directional, {shadowed_point} point, {shadowed_spot} spot"
|
||||
));
|
||||
|
||||
let scene_directionals: Vec<(f32, bool)> = world
|
||||
.query_filtered::<&LightDesc, With<LevelObject>>()
|
||||
.iter(world)
|
||||
.filter_map(|light| {
|
||||
matches!(light.kind, AuthoringLightKind::Directional)
|
||||
.then_some((light.intensity, light.shadows))
|
||||
})
|
||||
.collect();
|
||||
|
||||
if scene_directionals.is_empty() {
|
||||
ui.label("Scene sun: none (project sun drives outdoor lighting)");
|
||||
} else {
|
||||
let (lux, shadows) = scene_directionals[0];
|
||||
ui.label(format!(
|
||||
"Scene sun override: {lux:.0} lux, shadows={shadows} ({} directional LightDesc in level)",
|
||||
scene_directionals.len()
|
||||
));
|
||||
}
|
||||
|
||||
let project_sun_active = world
|
||||
.query_filtered::<&Visibility, With<ProjectSun>>()
|
||||
.iter(world)
|
||||
.any(|visibility| *visibility != Visibility::Hidden);
|
||||
|
||||
if project_sun_active {
|
||||
ui.label("Project sun: active");
|
||||
} else if !scene_directionals.is_empty() {
|
||||
ui.label("Project sun: hidden (scene directional override)");
|
||||
} else {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 140, 140),
|
||||
"Project sun: hidden and no scene directional — level may appear black.",
|
||||
);
|
||||
}
|
||||
|
||||
if directional + point + spot == 0 {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 140, 140),
|
||||
"Zero runtime lights in the world.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn solari_geometry_summary(world: &World, ui: &mut egui::Ui) {
|
||||
let Some(stats) = world.get_resource::<SolariRaytracingSceneStats>() else {
|
||||
return;
|
||||
};
|
||||
ui.separator();
|
||||
ui.heading("Solari raytracing scene");
|
||||
ui.label(format!(
|
||||
"Project meshes: {} tagged, {} eligible, {} Solari-compatible assets, {} unsupported, {} excluded helpers, {} outside level roots",
|
||||
stats.tagged_meshes,
|
||||
stats.project_meshes,
|
||||
stats.compatible_mesh_assets,
|
||||
stats.unsupported_meshes,
|
||||
stats.excluded_meshes,
|
||||
stats.missing_level_root_meshes
|
||||
));
|
||||
if stats.incompatible_mesh_assets > 0 {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
format!(
|
||||
"Incompatible mesh assets: {} ({} missing tangents, {} missing U32 indices)",
|
||||
stats.incompatible_mesh_assets,
|
||||
stats.mesh_assets_missing_tangents,
|
||||
stats.mesh_assets_missing_u32_indices
|
||||
),
|
||||
);
|
||||
}
|
||||
ui.label(format!(
|
||||
"Render scene: {} instances, {} directional lights, bind group ready={}",
|
||||
stats.render_instances, stats.render_directional_lights, stats.render_bind_group_ready
|
||||
));
|
||||
ui.label(format!(
|
||||
"Solari-compatible lights: {} directional/emissive",
|
||||
stats.compatible_light_count()
|
||||
));
|
||||
if stats.solari_ready() {
|
||||
ui.label("Readiness: Solari active");
|
||||
} else {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
format!("Readiness: {}", solari_readiness_reason(stats)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn solari_readiness_reason(stats: &SolariRaytracingSceneStats) -> &'static str {
|
||||
if stats.tagged_meshes == 0 {
|
||||
"no project meshes are tagged for raytracing"
|
||||
} else if stats.compatible_mesh_assets == 0 {
|
||||
"tagged meshes are not Solari-compatible mesh assets"
|
||||
} else if stats.render_instances == 0 {
|
||||
"raytracing meshes have not reached the render world"
|
||||
} else if !stats.render_bind_group_ready {
|
||||
"Bevy has not built the raytracing scene bind group"
|
||||
} else if stats.compatible_light_count() == 0 {
|
||||
"no extracted directional or emissive Solari light source"
|
||||
} else {
|
||||
"waiting for Solari readiness"
|
||||
}
|
||||
}
|
||||
|
||||
fn project_tab(world: &mut World, ui: &mut egui::Ui) {
|
||||
let rendering = world.resource::<ProjectSettings>().rendering.clone();
|
||||
ui.label(format!("GiMode: {:?}", rendering.gi_mode));
|
||||
ui.label(format!("HDR: {}", rendering.hdr));
|
||||
if rendering.exposure_mode == ExposureMode::Auto {
|
||||
ui.label(format!(
|
||||
"Exposure: Auto (brighten {:.1} / darken {:.1} f-stops/s)",
|
||||
rendering.auto_exposure_speed_brighten, rendering.auto_exposure_speed_darken
|
||||
));
|
||||
} else {
|
||||
ui.label(format!(
|
||||
"Exposure: Manual ({:.2} EV100)",
|
||||
rendering.exposure_ev100
|
||||
));
|
||||
}
|
||||
ui.label(format!(
|
||||
"Ambient brightness: {:.1}",
|
||||
rendering.ambient_brightness
|
||||
));
|
||||
ui.label(format!(
|
||||
"Sun illuminance: {:.0} lux",
|
||||
rendering.sun_illuminance
|
||||
));
|
||||
ui.label(format!(
|
||||
"Post-FX: bloom={} taa={} ssao={} atmosphere={}",
|
||||
rendering.bloom, rendering.taa, rendering.ssao, rendering.atmosphere
|
||||
));
|
||||
if ui.button("Open Project Settings → Rendering").clicked() {
|
||||
let mut panel = world.resource_mut::<ProjectSettingsPanel>();
|
||||
open_project_settings_panel(&mut panel);
|
||||
}
|
||||
if ui.button("Scene → Lighting → Use project sun").clicked() {
|
||||
crate::ui::helpers::use_project_sun(world);
|
||||
}
|
||||
if ui.button("Reset scene lighting to project").clicked() {
|
||||
crate::ui::helpers::reset_scene_lighting_to_project_defaults(world);
|
||||
}
|
||||
}
|
||||
|
||||
fn volumes_tab(world: &mut World, ui: &mut egui::Ui) {
|
||||
let mut volumes: Vec<(Entity, PostProcessVolumeDesc, String)> = world
|
||||
.query_filtered::<(Entity, &PostProcessVolumeDesc, Option<&Name>), With<LevelObject>>()
|
||||
.iter(world)
|
||||
.map(|(entity, desc, name)| {
|
||||
let label = desc
|
||||
.label
|
||||
.clone()
|
||||
.or_else(|| name.map(|n| n.to_string()))
|
||||
.unwrap_or_else(|| format!("Volume {entity:?}"));
|
||||
(entity, desc.clone(), label)
|
||||
})
|
||||
.collect();
|
||||
volumes.sort_by(|a, b| b.1.priority.cmp(&a.1.priority).then_with(|| a.0.cmp(&b.0)));
|
||||
|
||||
if volumes.is_empty() {
|
||||
ui.label("No post-process volumes in this level.");
|
||||
return;
|
||||
}
|
||||
|
||||
for (entity, desc, label) in volumes {
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(&label).clicked() {
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(entity);
|
||||
}
|
||||
ui.label(format!("priority {}", desc.priority));
|
||||
if ui.small_button("Focus").clicked() {
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(entity);
|
||||
focus_editor_camera_on_selection(world);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select_volumes_at_camera(world: &mut World) {
|
||||
use game_hot::sample_volumes_at;
|
||||
use settings::ProjectRenderCamera;
|
||||
|
||||
let camera_pos = world
|
||||
.query_filtered::<&GlobalTransform, With<ProjectRenderCamera>>()
|
||||
.iter(world)
|
||||
.next()
|
||||
.map(|t| t.translation())
|
||||
.unwrap_or(Vec3::ZERO);
|
||||
|
||||
let volume_list: Vec<_> = world
|
||||
.query_filtered::<(Entity, &PostProcessVolumeDesc, &GlobalTransform), With<LevelObject>>()
|
||||
.iter(world)
|
||||
.collect();
|
||||
let samples = sample_volumes_at(camera_pos, &volume_list);
|
||||
|
||||
if !samples.is_empty() {
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(samples[0]);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn_post_process_volume_at_camera(world: &mut World) {
|
||||
use shared::EditorVisibility;
|
||||
|
||||
let translation = world
|
||||
.query_filtered::<&GlobalTransform, With<crate::camera::EditorCamera>>()
|
||||
.iter(world)
|
||||
.next()
|
||||
.map(|t| t.translation())
|
||||
.unwrap_or(Vec3::new(0.0, 2.0, 0.0));
|
||||
|
||||
let snapshot = EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: ActorKind::PostProcessVolume,
|
||||
actor_name: None,
|
||||
name: Some("Post Process Volume".into()),
|
||||
transform: Transform::from_translation(translation),
|
||||
primitive: None,
|
||||
static_mesh_renderer: None,
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: None,
|
||||
collider: None,
|
||||
physics: None,
|
||||
light: None,
|
||||
player_spawn: false,
|
||||
model: None,
|
||||
prefab: None,
|
||||
prefab_instance: None,
|
||||
weapon_spawn: None,
|
||||
trigger_volume: None,
|
||||
post_process_volume: Some(PostProcessVolumeDesc::default()),
|
||||
team_spawn: None,
|
||||
objective: None,
|
||||
hierarchy_sibling_index: 0,
|
||||
editor_visibility: EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
};
|
||||
spawn_with_history(world, snapshot);
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
use bevy::picking::mesh_picking::ray_cast::{MeshRayCast, MeshRayCastSettings, RayCastVisibility};
|
||||
use bevy::picking::pointer::{PointerAction, PointerInput, PointerInteraction};
|
||||
use bevy::prelude::*;
|
||||
use shared::LevelObject;
|
||||
use transform_gizmo_bevy::prelude::GizmoTarget;
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::infra::EditorOnly;
|
||||
use crate::state::scene_tools_active;
|
||||
use crate::state::EditorMode;
|
||||
use crate::ui::helpers::ensure_player_spawn_for_edit;
|
||||
use crate::ui::hierarchy_ops::is_entity_locked;
|
||||
use crate::ui::hierarchy_state::HierarchyPanelState;
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::actor_icons::ActorIconProxy;
|
||||
use crate::viewport::ViewportDisplayMode;
|
||||
use crate::visualizers::EditorVisualizerProxy;
|
||||
use bevy_egui::egui;
|
||||
|
||||
use crate::viewport::scene_view_ray;
|
||||
|
||||
#[derive(Resource, Default, Debug, Clone, Copy)]
|
||||
pub struct SelectedEntity(pub Option<Entity>);
|
||||
|
||||
/// Primary click on the viewport panel (egui), consumed by [`handle_pick_events`].
|
||||
#[derive(Resource, Default, Debug, Clone, Copy)]
|
||||
pub struct ViewportClick(pub Option<egui::Pos2>);
|
||||
|
||||
/// Overlapping pick targets at the last viewport click; **Tab** cycles forward.
|
||||
#[derive(Resource, Default, Debug)]
|
||||
pub struct ViewportPickStack {
|
||||
pub entities: Vec<Entity>,
|
||||
pub index: usize,
|
||||
pub anchor: Option<egui::Pos2>,
|
||||
}
|
||||
|
||||
pub struct EditorSelectionPlugin;
|
||||
|
||||
impl Plugin for EditorSelectionPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<SelectedEntity>()
|
||||
.init_resource::<ViewportClick>()
|
||||
.init_resource::<ViewportPickStack>()
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
redirect_runtime_player_selection_to_spawn,
|
||||
sync_gizmo_targets,
|
||||
)
|
||||
.chain()
|
||||
.run_if(scene_tools_active),
|
||||
)
|
||||
// After transform-gizmo `update_gizmos` (Last) so clicks hit gizmos first.
|
||||
.add_systems(
|
||||
Last,
|
||||
(handle_pick_events, cycle_overlapping_viewport_pick)
|
||||
.chain()
|
||||
.run_if(scene_tools_active),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn redirect_runtime_player_selection_to_spawn(world: &mut World) {
|
||||
if *world.resource::<State<EditorMode>>().get() != EditorMode::Editing {
|
||||
return;
|
||||
}
|
||||
let Some(selected_entity) = world.resource::<SelectedEntity>().0 else {
|
||||
return;
|
||||
};
|
||||
if world.get::<sim::Player>(selected_entity).is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let spawn = ensure_player_spawn_for_edit(world);
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(spawn);
|
||||
if let Some(mut ui_state) = world.get_resource_mut::<UiState>() {
|
||||
ui_state.selected_entities.select_replace(spawn);
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn handle_pick_events(
|
||||
mut ui_state: ResMut<UiState>,
|
||||
mut selected: ResMut<SelectedEntity>,
|
||||
mut viewport_click: ResMut<ViewportClick>,
|
||||
mut pick_stack: ResMut<ViewportPickStack>,
|
||||
mut click_events: MessageReader<PointerInput>,
|
||||
pointers: Query<&PointerInteraction>,
|
||||
editor_cameras: Query<(&Camera, &GlobalTransform), With<EditorCamera>>,
|
||||
mut mesh_ray_cast: MeshRayCast,
|
||||
level_objects: Query<Entity, (With<LevelObject>, Without<EditorOnly>)>,
|
||||
proxies: Query<&EditorVisualizerProxy>,
|
||||
icon_proxies: Query<&ActorIconProxy>,
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
gizmo_targets: Query<&GizmoTarget>,
|
||||
hierarchy: Option<Res<HierarchyPanelState>>,
|
||||
) {
|
||||
if keys.just_pressed(KeyCode::Escape) {
|
||||
ui_state.selected_entities.clear();
|
||||
selected.0 = None;
|
||||
pick_stack.entities.clear();
|
||||
pick_stack.index = 0;
|
||||
pick_stack.anchor = None;
|
||||
return;
|
||||
}
|
||||
|
||||
if display.clean_game_view {
|
||||
viewport_click.0 = None;
|
||||
return;
|
||||
}
|
||||
|
||||
if gizmo_targets
|
||||
.iter()
|
||||
.any(|g| GizmoTarget::is_focused(g) || GizmoTarget::is_active(g))
|
||||
{
|
||||
viewport_click.0 = None;
|
||||
return;
|
||||
}
|
||||
|
||||
let additive = keys.any_pressed([KeyCode::ControlLeft, KeyCode::ShiftLeft]);
|
||||
|
||||
if let Some(pointer_pos) = viewport_click.0.take() {
|
||||
apply_viewport_pick(
|
||||
hierarchy.as_deref(),
|
||||
&mut ui_state,
|
||||
&mut selected,
|
||||
&mut pick_stack,
|
||||
&editor_cameras,
|
||||
&mut mesh_ray_cast,
|
||||
&level_objects,
|
||||
&proxies,
|
||||
&icon_proxies,
|
||||
pointer_pos,
|
||||
additive,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if !ui_state.pointer_in_viewport {
|
||||
return;
|
||||
}
|
||||
|
||||
for event in click_events.read() {
|
||||
if !matches!(event.action, PointerAction::Press(PointerButton::Primary)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut picked = None;
|
||||
for interaction in &pointers {
|
||||
if let Some(entity) = interaction.as_slice().iter().find_map(|(entity, _hit)| {
|
||||
pick_target_for_entity(*entity, &level_objects, &proxies, &icon_proxies)
|
||||
}) {
|
||||
picked = Some(entity);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if picked.is_none() {
|
||||
let Some(pointer_pos) = ui_state.viewport_pointer_pos else {
|
||||
continue;
|
||||
};
|
||||
let hits = collect_viewport_pick_hits(
|
||||
&editor_cameras,
|
||||
&mut mesh_ray_cast,
|
||||
&level_objects,
|
||||
&proxies,
|
||||
&icon_proxies,
|
||||
ui_state.viewport_rect,
|
||||
pointer_pos,
|
||||
);
|
||||
pick_stack.entities = hits;
|
||||
pick_stack.index = 0;
|
||||
pick_stack.anchor = Some(pointer_pos);
|
||||
picked = pick_stack.entities.first().copied();
|
||||
} else {
|
||||
pick_stack.entities.clear();
|
||||
pick_stack.index = 0;
|
||||
pick_stack.anchor = ui_state.viewport_pointer_pos;
|
||||
}
|
||||
|
||||
apply_pick_result(
|
||||
hierarchy.as_deref(),
|
||||
&mut ui_state,
|
||||
&mut selected,
|
||||
picked,
|
||||
additive,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn cycle_overlapping_viewport_pick(
|
||||
mut ui_state: ResMut<UiState>,
|
||||
mut selected: ResMut<SelectedEntity>,
|
||||
mut pick_stack: ResMut<ViewportPickStack>,
|
||||
keys: Res<ButtonInput<KeyCode>>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
) {
|
||||
if display.clean_game_view {
|
||||
return;
|
||||
}
|
||||
if !keys.just_pressed(KeyCode::Tab) || pick_stack.entities.len() < 2 {
|
||||
return;
|
||||
}
|
||||
if keys.any_pressed([KeyCode::ControlLeft, KeyCode::ShiftLeft]) {
|
||||
return;
|
||||
}
|
||||
if !ui_state.pointer_in_viewport {
|
||||
return;
|
||||
}
|
||||
|
||||
pick_stack.index = (pick_stack.index + 1) % pick_stack.entities.len();
|
||||
let entity = pick_stack.entities[pick_stack.index];
|
||||
ui_state.selected_entities.select_replace(entity);
|
||||
selected.0 = Some(entity);
|
||||
}
|
||||
|
||||
fn apply_viewport_pick(
|
||||
hierarchy: Option<&HierarchyPanelState>,
|
||||
ui_state: &mut UiState,
|
||||
selected: &mut SelectedEntity,
|
||||
pick_stack: &mut ViewportPickStack,
|
||||
editor_cameras: &Query<(&Camera, &GlobalTransform), With<EditorCamera>>,
|
||||
mesh_ray_cast: &mut MeshRayCast,
|
||||
level_objects: &Query<Entity, (With<LevelObject>, Without<EditorOnly>)>,
|
||||
proxies: &Query<&EditorVisualizerProxy>,
|
||||
icon_proxies: &Query<&ActorIconProxy>,
|
||||
pointer_pos: egui::Pos2,
|
||||
additive: bool,
|
||||
) {
|
||||
let hits = collect_viewport_pick_hits(
|
||||
editor_cameras,
|
||||
mesh_ray_cast,
|
||||
level_objects,
|
||||
proxies,
|
||||
icon_proxies,
|
||||
ui_state.viewport_rect,
|
||||
pointer_pos,
|
||||
);
|
||||
pick_stack.entities = hits;
|
||||
pick_stack.index = 0;
|
||||
pick_stack.anchor = Some(pointer_pos);
|
||||
let picked = pick_stack.entities.first().copied();
|
||||
apply_pick_result(hierarchy, ui_state, selected, picked, additive);
|
||||
}
|
||||
|
||||
fn apply_pick_result(
|
||||
hierarchy: Option<&HierarchyPanelState>,
|
||||
ui_state: &mut UiState,
|
||||
selected: &mut SelectedEntity,
|
||||
picked: Option<Entity>,
|
||||
additive: bool,
|
||||
) {
|
||||
if let Some(entity) = picked {
|
||||
if hierarchy.is_some_and(|state| is_entity_locked(&state.locked, entity)) {
|
||||
return;
|
||||
}
|
||||
ui_state
|
||||
.selected_entities
|
||||
.select_maybe_add(entity, additive);
|
||||
selected.0 = Some(entity);
|
||||
} else if !additive {
|
||||
ui_state.selected_entities.clear();
|
||||
selected.0 = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_viewport_pick_hits(
|
||||
editor_cameras: &Query<(&Camera, &GlobalTransform), With<EditorCamera>>,
|
||||
mesh_ray_cast: &mut MeshRayCast,
|
||||
level_objects: &Query<Entity, (With<LevelObject>, Without<EditorOnly>)>,
|
||||
proxies: &Query<&EditorVisualizerProxy>,
|
||||
icon_proxies: &Query<&ActorIconProxy>,
|
||||
scene_rect: egui::Rect,
|
||||
pointer_pos: egui::Pos2,
|
||||
) -> Vec<Entity> {
|
||||
if !scene_rect.contains(pointer_pos) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let (camera, transform) = match editor_cameras
|
||||
.iter()
|
||||
.find(|(camera, _)| camera.is_active)
|
||||
.or_else(|| editor_cameras.iter().next())
|
||||
{
|
||||
Some(pair) => pair,
|
||||
None => return Vec::new(),
|
||||
};
|
||||
let Some(ray) = scene_view_ray(camera, transform, pointer_pos, scene_rect) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let filter = |entity: Entity| {
|
||||
level_objects.contains(entity)
|
||||
|| proxies
|
||||
.get(entity)
|
||||
.is_ok_and(|proxy| level_objects.contains(proxy.target) || proxy.target != entity)
|
||||
|| icon_proxies
|
||||
.get(entity)
|
||||
.is_ok_and(|proxy| level_objects.contains(proxy.target))
|
||||
};
|
||||
let settings = MeshRayCastSettings::default()
|
||||
.with_visibility(RayCastVisibility::Any)
|
||||
.with_filter(&filter)
|
||||
.never_early_exit();
|
||||
let hits = mesh_ray_cast.cast_ray(ray, &settings);
|
||||
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut ordered = Vec::new();
|
||||
for (entity, _) in hits {
|
||||
let Some(target) = pick_target_for_entity(*entity, level_objects, proxies, icon_proxies)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if seen.insert(target) {
|
||||
ordered.push(target);
|
||||
}
|
||||
}
|
||||
ordered
|
||||
}
|
||||
|
||||
fn pick_target_for_entity(
|
||||
entity: Entity,
|
||||
level_objects: &Query<Entity, (With<LevelObject>, Without<EditorOnly>)>,
|
||||
proxies: &Query<&EditorVisualizerProxy>,
|
||||
icon_proxies: &Query<&ActorIconProxy>,
|
||||
) -> Option<Entity> {
|
||||
if let Ok(proxy) = icon_proxies.get(entity) {
|
||||
return level_objects.contains(proxy.target).then_some(proxy.target);
|
||||
}
|
||||
if let Ok(proxy) = proxies.get(entity) {
|
||||
return Some(proxy.target);
|
||||
}
|
||||
level_objects.contains(entity).then_some(entity)
|
||||
}
|
||||
|
||||
fn sync_gizmo_targets(
|
||||
mut ui_state: ResMut<UiState>,
|
||||
mut selected: ResMut<SelectedEntity>,
|
||||
mut commands: Commands,
|
||||
targets: Query<Entity, With<GizmoTarget>>,
|
||||
level_objects: Query<(), (With<LevelObject>, Without<EditorOnly>)>,
|
||||
editor_only: Query<(), With<EditorOnly>>,
|
||||
transforms: Query<(), With<Transform>>,
|
||||
hierarchy: Option<Res<HierarchyPanelState>>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
) {
|
||||
ui_state
|
||||
.selected_entities
|
||||
.retain(|entity| transforms.contains(entity) && !editor_only.contains(entity));
|
||||
selected.0 = ui_state.selected_entities.as_slice().first().copied();
|
||||
|
||||
if display.clean_game_view {
|
||||
for entity in &targets {
|
||||
commands.entity(entity).remove::<GizmoTarget>();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for entity in &targets {
|
||||
if !ui_state.selected_entities.contains(entity) {
|
||||
commands.entity(entity).remove::<GizmoTarget>();
|
||||
}
|
||||
}
|
||||
if let Some(entity) = ui_state.selected_entities.as_slice().first().copied() {
|
||||
if level_objects.contains(entity)
|
||||
&& transforms.contains(entity)
|
||||
&& !targets.contains(entity)
|
||||
&& !hierarchy
|
||||
.as_ref()
|
||||
.is_some_and(|state| is_entity_locked(&state.locked, entity))
|
||||
{
|
||||
commands.entity(entity).insert(GizmoTarget::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
//! Editor selection outline: cheap AABB shells, dual depth pass (rim + x-ray).
|
||||
|
||||
use avian3d::prelude::ColliderConstructor;
|
||||
use bevy::asset::{load_internal_asset, uuid_handle};
|
||||
use bevy::camera::visibility::RenderLayers;
|
||||
use bevy::pbr::{Material, MaterialPlugin};
|
||||
use bevy::prelude::*;
|
||||
use bevy::render::render_resource::{
|
||||
AsBindGroup, BlendState, CompareFunction, Face, RenderPipelineDescriptor, ShaderType,
|
||||
};
|
||||
use bevy::shader::ShaderRef;
|
||||
use shared::{
|
||||
ColliderDesc, ColliderShapeDesc, LevelObject, PhysicsBody, Primitive, RaytracingExcluded,
|
||||
};
|
||||
|
||||
use crate::infra::EditorOnly;
|
||||
use crate::state::scene_tools_active;
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::ViewportDisplayMode;
|
||||
|
||||
const SELECTION_OUTLINE_SHADER: Handle<Shader> =
|
||||
uuid_handle!("c4e8f1a2-9b3d-4e7c-a1f5-6d2b8e0c4a91");
|
||||
|
||||
/// Subtle amber rim on visible faces.
|
||||
const VISIBLE_COLOR: Color = Color::srgba(1.0, 0.82, 0.35, 0.22);
|
||||
/// Soft cyan through occluders.
|
||||
const OCCLUDED_COLOR: Color = Color::srgba(0.35, 0.7, 0.95, 0.15);
|
||||
const BOUNDS_PADDING: f32 = 1.06;
|
||||
|
||||
#[derive(Clone, Copy, ShaderType)]
|
||||
struct OutlineUniform {
|
||||
color: LinearRgba,
|
||||
rim_power: f32,
|
||||
rim_mix: f32,
|
||||
pass_kind: u32,
|
||||
}
|
||||
|
||||
#[derive(Asset, TypePath, AsBindGroup, Clone)]
|
||||
pub struct SelectionOutlineVisibleMaterial {
|
||||
#[uniform(0)]
|
||||
uniform: OutlineUniform,
|
||||
}
|
||||
|
||||
#[derive(Asset, TypePath, AsBindGroup, Clone)]
|
||||
pub struct SelectionOutlineOccludedMaterial {
|
||||
#[uniform(0)]
|
||||
uniform: OutlineUniform,
|
||||
}
|
||||
|
||||
fn outline_uniform(color: Color, pass_kind: u32) -> OutlineUniform {
|
||||
OutlineUniform {
|
||||
color: color.into(),
|
||||
rim_power: 10.5,
|
||||
rim_mix: 0.35,
|
||||
pass_kind,
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_outline_material {
|
||||
($t:ty, $depth:expr) => {
|
||||
impl Material for $t {
|
||||
fn fragment_shader() -> ShaderRef {
|
||||
SELECTION_OUTLINE_SHADER.into()
|
||||
}
|
||||
|
||||
fn alpha_mode(&self) -> AlphaMode {
|
||||
AlphaMode::Blend
|
||||
}
|
||||
|
||||
fn enable_prepass() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn enable_shadows() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn specialize(
|
||||
_pipeline: &bevy::pbr::MaterialPipeline,
|
||||
descriptor: &mut RenderPipelineDescriptor,
|
||||
_layout: &bevy::mesh::MeshVertexBufferLayoutRef,
|
||||
_key: bevy::pbr::MaterialPipelineKey<Self>,
|
||||
) -> Result<(), bevy::render::render_resource::SpecializedMeshPipelineError> {
|
||||
descriptor.primitive.cull_mode = Some(Face::Front);
|
||||
if let Some(depth) = &mut descriptor.depth_stencil {
|
||||
depth.depth_write_enabled = false;
|
||||
depth.depth_compare = $depth;
|
||||
}
|
||||
if let Some(fragment) = &mut descriptor.fragment {
|
||||
if let Some(target) = fragment.targets.first_mut().and_then(|t| t.as_mut()) {
|
||||
target.blend = Some(BlendState::ALPHA_BLENDING);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_outline_material!(SelectionOutlineVisibleMaterial, CompareFunction::LessEqual);
|
||||
impl_outline_material!(SelectionOutlineOccludedMaterial, CompareFunction::Greater);
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
enum SelectionOutlinePass {
|
||||
Visible,
|
||||
Occluded,
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
pub(crate) struct SelectionOutlineShell {
|
||||
root: Entity,
|
||||
pass: SelectionOutlinePass,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct SelectionOutlineMaterials {
|
||||
occluded: Handle<SelectionOutlineOccludedMaterial>,
|
||||
visible: Handle<SelectionOutlineVisibleMaterial>,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct SelectionOutlineUnitBox(Handle<Mesh>);
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct SelectionBounds {
|
||||
center: Vec3,
|
||||
half_extents: Vec3,
|
||||
}
|
||||
|
||||
pub struct SelectionOutlinePlugin;
|
||||
|
||||
impl Plugin for SelectionOutlinePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
load_internal_asset!(
|
||||
app,
|
||||
SELECTION_OUTLINE_SHADER,
|
||||
"../../assets/shaders/selection_outline.wgsl",
|
||||
Shader::from_wgsl
|
||||
);
|
||||
|
||||
app.add_plugins((
|
||||
MaterialPlugin::<SelectionOutlineVisibleMaterial>::default(),
|
||||
MaterialPlugin::<SelectionOutlineOccludedMaterial>::default(),
|
||||
))
|
||||
.add_systems(
|
||||
Startup,
|
||||
(
|
||||
init_selection_outline_assets,
|
||||
init_selection_outline_materials,
|
||||
)
|
||||
.chain(),
|
||||
)
|
||||
.add_systems(
|
||||
Update,
|
||||
sync_selection_outline_meshes.run_if(scene_tools_active),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn init_selection_outline_assets(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
|
||||
commands.insert_resource(SelectionOutlineUnitBox(
|
||||
meshes.add(Mesh::from(Cuboid::new(1.0, 1.0, 1.0))),
|
||||
));
|
||||
}
|
||||
|
||||
fn init_selection_outline_materials(
|
||||
mut visible: ResMut<Assets<SelectionOutlineVisibleMaterial>>,
|
||||
mut occluded: ResMut<Assets<SelectionOutlineOccludedMaterial>>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
commands.insert_resource(SelectionOutlineMaterials {
|
||||
visible: visible.add(SelectionOutlineVisibleMaterial {
|
||||
uniform: outline_uniform(VISIBLE_COLOR, 0),
|
||||
}),
|
||||
occluded: occluded.add(SelectionOutlineOccludedMaterial {
|
||||
uniform: outline_uniform(OCCLUDED_COLOR, 1),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sync_selection_outline_meshes(
|
||||
ui_state: Res<UiState>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
materials: Res<SelectionOutlineMaterials>,
|
||||
unit_box: Res<SelectionOutlineUnitBox>,
|
||||
mut commands: Commands,
|
||||
shells: Query<(Entity, &SelectionOutlineShell)>,
|
||||
children: Query<&Children>,
|
||||
mesh_entities: Query<(Entity, &Mesh3d), With<Mesh3d>>,
|
||||
globals: Query<&GlobalTransform>,
|
||||
mesh_assets: Res<Assets<Mesh>>,
|
||||
primitives: Query<&Primitive>,
|
||||
physics: Query<&PhysicsBody>,
|
||||
colliders: Query<&ColliderDesc>,
|
||||
level_objects: Query<(), (With<LevelObject>, Without<EditorOnly>)>,
|
||||
) {
|
||||
if !ui_state.is_changed() && !display.is_changed() {
|
||||
return;
|
||||
}
|
||||
|
||||
let selected: std::collections::HashSet<Entity> = ui_state.selected_entities.iter().collect();
|
||||
|
||||
let mut desired: std::collections::HashMap<(Entity, SelectionOutlinePass), SelectionBounds> =
|
||||
std::collections::HashMap::new();
|
||||
if !display.clean_game_view {
|
||||
for &root in &selected {
|
||||
if !level_objects.contains(root) {
|
||||
continue;
|
||||
}
|
||||
let Some(bounds) = selection_bounds(
|
||||
root,
|
||||
&children,
|
||||
&mesh_entities,
|
||||
&globals,
|
||||
&mesh_assets,
|
||||
&primitives,
|
||||
&physics,
|
||||
&colliders,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
if bounds.half_extents.max_element() <= f32::EPSILON {
|
||||
continue;
|
||||
}
|
||||
desired.insert((root, SelectionOutlinePass::Occluded), bounds);
|
||||
desired.insert((root, SelectionOutlinePass::Visible), bounds);
|
||||
}
|
||||
}
|
||||
|
||||
for (shell_entity, shell) in &shells {
|
||||
if !desired.contains_key(&(shell.root, shell.pass)) {
|
||||
commands.entity(shell_entity).despawn();
|
||||
}
|
||||
}
|
||||
|
||||
let existing: std::collections::HashSet<(Entity, SelectionOutlinePass)> = shells
|
||||
.iter()
|
||||
.map(|(_, shell)| (shell.root, shell.pass))
|
||||
.collect();
|
||||
|
||||
for ((root, pass), bounds) in desired {
|
||||
if existing.contains(&(root, pass)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut entity_commands = commands.spawn((
|
||||
EditorOnly,
|
||||
RaytracingExcluded,
|
||||
Name::new("Selection Outline"),
|
||||
SelectionOutlineShell { root, pass },
|
||||
Mesh3d(unit_box.0.clone()),
|
||||
Transform {
|
||||
translation: bounds.center,
|
||||
scale: bounds.half_extents * 2.0,
|
||||
..default()
|
||||
},
|
||||
RenderLayers::default(),
|
||||
ChildOf(root),
|
||||
));
|
||||
|
||||
match pass {
|
||||
SelectionOutlinePass::Occluded => {
|
||||
entity_commands.insert(MeshMaterial3d(materials.occluded.clone()));
|
||||
}
|
||||
SelectionOutlinePass::Visible => {
|
||||
entity_commands.insert(MeshMaterial3d(materials.visible.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn selection_bounds(
|
||||
root: Entity,
|
||||
children: &Query<&Children>,
|
||||
mesh_entities: &Query<(Entity, &Mesh3d), With<Mesh3d>>,
|
||||
globals: &Query<&GlobalTransform>,
|
||||
mesh_assets: &Assets<Mesh>,
|
||||
primitives: &Query<&Primitive>,
|
||||
physics: &Query<&PhysicsBody>,
|
||||
colliders: &Query<&ColliderDesc>,
|
||||
) -> Option<SelectionBounds> {
|
||||
if let Ok(primitive) = primitives.get(root) {
|
||||
return Some(SelectionBounds {
|
||||
center: Vec3::ZERO,
|
||||
half_extents: primitive.size * 0.5 * BOUNDS_PADDING,
|
||||
});
|
||||
}
|
||||
|
||||
if let Ok(body) = physics.get(root) {
|
||||
if let Some(bounds) = bounds_from_collider(&body.collider) {
|
||||
return Some(bounds);
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(collider) = colliders.get(root) {
|
||||
if let Some(bounds) = bounds_from_collider_desc(collider) {
|
||||
return Some(bounds);
|
||||
}
|
||||
}
|
||||
|
||||
union_mesh_bounds(root, children, mesh_entities, globals, mesh_assets)
|
||||
}
|
||||
|
||||
fn bounds_from_collider(collider: &ColliderConstructor) -> Option<SelectionBounds> {
|
||||
match collider {
|
||||
ColliderConstructor::Cuboid {
|
||||
x_length,
|
||||
y_length,
|
||||
z_length,
|
||||
} => Some(SelectionBounds {
|
||||
center: Vec3::ZERO,
|
||||
half_extents: Vec3::new(*x_length, *y_length, *z_length) * 0.5 * BOUNDS_PADDING,
|
||||
}),
|
||||
ColliderConstructor::Sphere { radius } => Some(SelectionBounds {
|
||||
center: Vec3::ZERO,
|
||||
half_extents: Vec3::splat(*radius) * BOUNDS_PADDING,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn bounds_from_collider_desc(collider: &ColliderDesc) -> Option<SelectionBounds> {
|
||||
if !collider.enabled {
|
||||
return None;
|
||||
}
|
||||
match &collider.shape {
|
||||
ColliderShapeDesc::Cuboid {
|
||||
x_length,
|
||||
y_length,
|
||||
z_length,
|
||||
} => Some(SelectionBounds {
|
||||
center: Vec3::ZERO,
|
||||
half_extents: Vec3::new(*x_length, *y_length, *z_length) * 0.5 * BOUNDS_PADDING,
|
||||
}),
|
||||
ColliderShapeDesc::Sphere { radius } => Some(SelectionBounds {
|
||||
center: Vec3::ZERO,
|
||||
half_extents: Vec3::splat(*radius) * BOUNDS_PADDING,
|
||||
}),
|
||||
ColliderShapeDesc::Capsule { radius, height } => Some(SelectionBounds {
|
||||
center: Vec3::ZERO,
|
||||
half_extents: Vec3::new(*radius, *height * 0.5, *radius) * BOUNDS_PADDING,
|
||||
}),
|
||||
ColliderShapeDesc::StaticMesh { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn union_mesh_bounds(
|
||||
root: Entity,
|
||||
children: &Query<&Children>,
|
||||
mesh_entities: &Query<(Entity, &Mesh3d), With<Mesh3d>>,
|
||||
globals: &Query<&GlobalTransform>,
|
||||
mesh_assets: &Assets<Mesh>,
|
||||
) -> Option<SelectionBounds> {
|
||||
let root_global = globals.get(root).ok()?;
|
||||
let root_to_world = root_global.affine();
|
||||
let world_to_root = root_to_world.inverse();
|
||||
|
||||
let mut min = Vec3::splat(f32::INFINITY);
|
||||
let mut max = Vec3::splat(f32::NEG_INFINITY);
|
||||
let mut any = false;
|
||||
|
||||
for entity in collect_mesh_entities(root, children, mesh_entities) {
|
||||
let Ok((_, mesh3d)) = mesh_entities.get(entity) else {
|
||||
continue;
|
||||
};
|
||||
let Some(mesh) = mesh_assets.get(&mesh3d.0) else {
|
||||
continue;
|
||||
};
|
||||
let Some(aabb) = mesh.final_aabb else {
|
||||
continue;
|
||||
};
|
||||
let entity_global = globals.get(entity).ok()?;
|
||||
let entity_to_world = entity_global.affine();
|
||||
|
||||
let mesh_min = Vec3::from(aabb.min);
|
||||
let mesh_max = Vec3::from(aabb.max);
|
||||
for corner in corner_iter(mesh_min, mesh_max) {
|
||||
let world = entity_to_world.transform_point3(corner);
|
||||
let local = world_to_root.transform_point3(world);
|
||||
min = min.min(local);
|
||||
max = max.max(local);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !any {
|
||||
return None;
|
||||
}
|
||||
|
||||
let center = (min + max) * 0.5;
|
||||
let half_extents = (max - min) * 0.5 * BOUNDS_PADDING;
|
||||
Some(SelectionBounds {
|
||||
center,
|
||||
half_extents,
|
||||
})
|
||||
}
|
||||
|
||||
fn corner_iter(min: Vec3, max: Vec3) -> impl Iterator<Item = Vec3> {
|
||||
[
|
||||
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),
|
||||
]
|
||||
.into_iter()
|
||||
}
|
||||
|
||||
fn collect_mesh_entities(
|
||||
root: Entity,
|
||||
children: &Query<&Children>,
|
||||
meshes: &Query<(Entity, &Mesh3d), With<Mesh3d>>,
|
||||
) -> Vec<Entity> {
|
||||
let mut found = Vec::new();
|
||||
if meshes.get(root).is_ok() {
|
||||
found.push(root);
|
||||
}
|
||||
collect_mesh_descendants(root, children, meshes, &mut found);
|
||||
found
|
||||
}
|
||||
|
||||
fn collect_mesh_descendants(
|
||||
entity: Entity,
|
||||
children: &Query<&Children>,
|
||||
meshes: &Query<(Entity, &Mesh3d), With<Mesh3d>>,
|
||||
found: &mut Vec<Entity>,
|
||||
) {
|
||||
let Ok(kids) = children.get(entity) else {
|
||||
return;
|
||||
};
|
||||
for child in kids.iter() {
|
||||
if meshes.get(child).is_ok() {
|
||||
found.push(child);
|
||||
}
|
||||
collect_mesh_descendants(child, children, meshes, found);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! Viewport shading modes: Lit, Unlit (base color), and Collider-only.
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::infra::EditorOnly;
|
||||
use crate::selection_outline::SelectionOutlineShell;
|
||||
use crate::state::scene_tools_active;
|
||||
use crate::visualizers::EditorVisualizerProxy;
|
||||
|
||||
/// Viewport display mode (editor-only; does not affect saved scenes or runtime rendering).
|
||||
#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum EditorViewportMode {
|
||||
#[default]
|
||||
Lit,
|
||||
/// Base-color albedo without lighting response (debug).
|
||||
Unlit,
|
||||
/// Hide scene meshes; emphasize collider gizmos.
|
||||
Collider,
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct ViewportMaterialOverride {
|
||||
original: Handle<StandardMaterial>,
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct ViewportMeshHiddenByMode;
|
||||
|
||||
pub struct EditorViewportModePlugin;
|
||||
|
||||
impl Plugin for EditorViewportModePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<EditorViewportMode>().add_systems(
|
||||
Update,
|
||||
(
|
||||
apply_viewport_mode_on_change,
|
||||
apply_viewport_mode_for_new_meshes,
|
||||
reconcile_lit_material_overrides,
|
||||
reconcile_lit_mode_hidden_meshes,
|
||||
)
|
||||
.chain()
|
||||
.run_if(scene_tools_active),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_viewport_mode_on_change(
|
||||
mode: Res<EditorViewportMode>,
|
||||
mut last: Local<Option<EditorViewportMode>>,
|
||||
mut commands: Commands,
|
||||
mut materials: ResMut<Assets<StandardMaterial>>,
|
||||
meshes: Query<
|
||||
Entity,
|
||||
(
|
||||
With<Mesh3d>,
|
||||
Without<EditorOnly>,
|
||||
Without<EditorVisualizerProxy>,
|
||||
Without<SelectionOutlineShell>,
|
||||
),
|
||||
>,
|
||||
mesh_materials: Query<(Entity, &MeshMaterial3d<StandardMaterial>)>,
|
||||
overrides: Query<(Entity, &ViewportMaterialOverride)>,
|
||||
hidden: Query<Entity, With<ViewportMeshHiddenByMode>>,
|
||||
mut visibility: Query<&mut Visibility>,
|
||||
) {
|
||||
let mode = *mode;
|
||||
if *last == Some(mode) {
|
||||
return;
|
||||
}
|
||||
*last = Some(mode);
|
||||
|
||||
restore_lit_state(&mut commands, &overrides, &hidden, &mut visibility);
|
||||
|
||||
match mode {
|
||||
EditorViewportMode::Lit => {}
|
||||
EditorViewportMode::Unlit => {
|
||||
for (entity, material) in &mesh_materials {
|
||||
apply_unlit_override(entity, material, &mut commands, &mut materials);
|
||||
}
|
||||
}
|
||||
EditorViewportMode::Collider => {
|
||||
for entity in meshes.iter() {
|
||||
hide_mesh_for_collider_mode(entity, &mut commands, &mut visibility);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_viewport_mode_for_new_meshes(
|
||||
mode: Res<EditorViewportMode>,
|
||||
mut commands: Commands,
|
||||
mut materials: ResMut<Assets<StandardMaterial>>,
|
||||
refreshed_materials: Query<
|
||||
(Entity, &MeshMaterial3d<StandardMaterial>),
|
||||
(
|
||||
Changed<MeshMaterial3d<StandardMaterial>>,
|
||||
With<ViewportMaterialOverride>,
|
||||
),
|
||||
>,
|
||||
added_meshes: Query<
|
||||
Entity,
|
||||
(
|
||||
Added<Mesh3d>,
|
||||
Without<EditorOnly>,
|
||||
Without<EditorVisualizerProxy>,
|
||||
Without<SelectionOutlineShell>,
|
||||
Without<ViewportMeshHiddenByMode>,
|
||||
),
|
||||
>,
|
||||
added_materials: Query<
|
||||
(Entity, &MeshMaterial3d<StandardMaterial>),
|
||||
(
|
||||
Or<(
|
||||
Added<MeshMaterial3d<StandardMaterial>>,
|
||||
Changed<MeshMaterial3d<StandardMaterial>>,
|
||||
)>,
|
||||
Without<ViewportMaterialOverride>,
|
||||
),
|
||||
>,
|
||||
mut visibility: Query<&mut Visibility>,
|
||||
) {
|
||||
match *mode {
|
||||
EditorViewportMode::Lit => {}
|
||||
EditorViewportMode::Unlit => {
|
||||
for (entity, material) in &refreshed_materials {
|
||||
commands.entity(entity).remove::<ViewportMaterialOverride>();
|
||||
apply_unlit_override(entity, material, &mut commands, &mut materials);
|
||||
}
|
||||
for (entity, material) in &added_materials {
|
||||
apply_unlit_override(entity, material, &mut commands, &mut materials);
|
||||
}
|
||||
}
|
||||
EditorViewportMode::Collider => {
|
||||
for entity in added_meshes.iter() {
|
||||
hide_mesh_for_collider_mode(entity, &mut commands, &mut visibility);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_lit_state(
|
||||
commands: &mut Commands,
|
||||
overrides: &Query<(Entity, &ViewportMaterialOverride)>,
|
||||
hidden: &Query<Entity, With<ViewportMeshHiddenByMode>>,
|
||||
visibility: &mut Query<&mut Visibility>,
|
||||
) {
|
||||
for (entity, backup) in overrides.iter() {
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(MeshMaterial3d(backup.original.clone()));
|
||||
commands.entity(entity).remove::<ViewportMaterialOverride>();
|
||||
}
|
||||
|
||||
for entity in hidden.iter() {
|
||||
if let Ok(mut vis) = visibility.get_mut(entity) {
|
||||
*vis = Visibility::Inherited;
|
||||
}
|
||||
commands.entity(entity).remove::<ViewportMeshHiddenByMode>();
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_unlit_override(
|
||||
entity: Entity,
|
||||
material: &MeshMaterial3d<StandardMaterial>,
|
||||
commands: &mut Commands,
|
||||
materials: &mut Assets<StandardMaterial>,
|
||||
) {
|
||||
let Some(source) = materials.get(&material.0) else {
|
||||
return;
|
||||
};
|
||||
let unlit = materials.add(StandardMaterial {
|
||||
base_color: source.base_color,
|
||||
base_color_texture: source.base_color_texture.clone(),
|
||||
unlit: true,
|
||||
metallic: 0.0,
|
||||
perceptual_roughness: 1.0,
|
||||
..default()
|
||||
});
|
||||
let original = material.0.clone();
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert((ViewportMaterialOverride { original }, MeshMaterial3d(unlit)));
|
||||
}
|
||||
|
||||
fn hide_mesh_for_collider_mode(
|
||||
entity: Entity,
|
||||
commands: &mut Commands,
|
||||
visibility: &mut Query<&mut Visibility>,
|
||||
) {
|
||||
if let Ok(mut vis) = visibility.get_mut(entity) {
|
||||
*vis = Visibility::Hidden;
|
||||
}
|
||||
commands.entity(entity).insert(ViewportMeshHiddenByMode);
|
||||
}
|
||||
|
||||
/// Drops stale unlit overrides after material re-hydration while Lit is active.
|
||||
fn reconcile_lit_material_overrides(
|
||||
mode: Res<EditorViewportMode>,
|
||||
mut commands: Commands,
|
||||
stale: Query<
|
||||
Entity,
|
||||
(
|
||||
With<ViewportMaterialOverride>,
|
||||
Changed<MeshMaterial3d<StandardMaterial>>,
|
||||
),
|
||||
>,
|
||||
) {
|
||||
if *mode != EditorViewportMode::Lit {
|
||||
return;
|
||||
}
|
||||
for entity in &stale {
|
||||
commands.entity(entity).remove::<ViewportMaterialOverride>();
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears stale Collider-mode hides while Lit is active (e.g. after hot reload).
|
||||
fn reconcile_lit_mode_hidden_meshes(
|
||||
mode: Res<EditorViewportMode>,
|
||||
mut commands: Commands,
|
||||
overrides: Query<(Entity, &ViewportMaterialOverride)>,
|
||||
hidden: Query<Entity, With<ViewportMeshHiddenByMode>>,
|
||||
mut visibility: Query<&mut Visibility>,
|
||||
) {
|
||||
if *mode != EditorViewportMode::Lit {
|
||||
return;
|
||||
}
|
||||
if overrides.is_empty() && hidden.is_empty() {
|
||||
return;
|
||||
}
|
||||
restore_lit_state(&mut commands, &overrides, &hidden, &mut visibility);
|
||||
}
|
||||
@@ -0,0 +1,800 @@
|
||||
//! Editor-side scene visualizers for authoring/runtime entities that have no mesh.
|
||||
|
||||
use avian3d::prelude::ColliderConstructor;
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
AuthoringLightKind, ColliderDesc, ColliderShapeDesc, LevelObject, LightDesc, ModelRef,
|
||||
ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc, PrefabRef, ProjectSun,
|
||||
RaytracingExcluded, TeamSpawn, TriggerVolume, WeaponSpawn,
|
||||
};
|
||||
use sim::tuning::{EYE_OFFSET_STAND, PLAYER_LENGTH, PLAYER_RADIUS};
|
||||
use sim::{Player, PlayerCamera};
|
||||
|
||||
use crate::infra::EditorOnly;
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::state::scene_tools_active;
|
||||
use crate::viewport::{EditorViewportMode, ViewportDisplayMode};
|
||||
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct EditorVisualizationSettings {
|
||||
pub enabled: bool,
|
||||
pub show_actor_icons: bool,
|
||||
pub show_actor_icon_actor: bool,
|
||||
pub show_actor_icon_mesh: bool,
|
||||
pub show_actor_icon_light: bool,
|
||||
pub show_actor_icon_physics: bool,
|
||||
pub show_actor_icon_gameplay: bool,
|
||||
pub show_actor_icon_volume: bool,
|
||||
pub show_actor_icon_prefab_model: bool,
|
||||
pub show_actor_icon_debug: bool,
|
||||
pub show_colliders: bool,
|
||||
pub show_lights: bool,
|
||||
pub show_spawns: bool,
|
||||
pub show_prefab_model_anchors: bool,
|
||||
pub show_runtime: bool,
|
||||
pub pickable_proxies: bool,
|
||||
}
|
||||
|
||||
impl Default for EditorVisualizationSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
show_actor_icons: true,
|
||||
show_actor_icon_actor: true,
|
||||
show_actor_icon_mesh: true,
|
||||
show_actor_icon_light: true,
|
||||
show_actor_icon_physics: true,
|
||||
show_actor_icon_gameplay: true,
|
||||
show_actor_icon_volume: true,
|
||||
show_actor_icon_prefab_model: true,
|
||||
show_actor_icon_debug: true,
|
||||
show_colliders: true,
|
||||
show_lights: true,
|
||||
show_spawns: true,
|
||||
show_prefab_model_anchors: true,
|
||||
show_runtime: true,
|
||||
pickable_proxies: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct EditorVisualizerProxy {
|
||||
pub target: Entity,
|
||||
pub kind: VisualizerKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum VisualizerKind {
|
||||
Collider,
|
||||
Light,
|
||||
PlayerSpawn,
|
||||
Prefab,
|
||||
Model,
|
||||
Player,
|
||||
Camera,
|
||||
ProjectSun,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct VisualizerProxyAssets {
|
||||
mesh: Handle<Mesh>,
|
||||
material: Handle<StandardMaterial>,
|
||||
}
|
||||
|
||||
pub struct EditorVisualizersPlugin;
|
||||
|
||||
impl Plugin for EditorVisualizersPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<EditorVisualizationSettings>()
|
||||
.add_systems(Startup, init_visualizer_proxy_assets)
|
||||
.add_systems(Update, sync_visualizer_proxies.run_if(scene_tools_active))
|
||||
.add_systems(
|
||||
Update,
|
||||
(
|
||||
draw_visualizers,
|
||||
draw_split_collider_visualizers,
|
||||
draw_post_process_volume_gizmos,
|
||||
)
|
||||
.chain()
|
||||
.run_if(scene_tools_active)
|
||||
.run_if(viewport_editor_overlays_visible),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn viewport_editor_overlays_visible(display: Res<ViewportDisplayMode>) -> bool {
|
||||
!display.clean_game_view
|
||||
}
|
||||
|
||||
fn init_visualizer_proxy_assets(
|
||||
mut commands: Commands,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
mut materials: ResMut<Assets<StandardMaterial>>,
|
||||
) {
|
||||
commands.insert_resource(VisualizerProxyAssets {
|
||||
mesh: meshes.add(Sphere::new(0.22).mesh().uv(16, 8)),
|
||||
material: materials.add(StandardMaterial {
|
||||
base_color: Color::srgba(0.2, 0.8, 1.0, 0.08),
|
||||
alpha_mode: AlphaMode::Blend,
|
||||
unlit: true,
|
||||
..default()
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sync_visualizer_proxies(
|
||||
viewport_mode: Res<EditorViewportMode>,
|
||||
display: Res<ViewportDisplayMode>,
|
||||
settings: Res<EditorVisualizationSettings>,
|
||||
assets: Res<VisualizerProxyAssets>,
|
||||
mut commands: Commands,
|
||||
mut proxies: Query<(Entity, &EditorVisualizerProxy, &mut Transform)>,
|
||||
transforms: Query<&GlobalTransform>,
|
||||
colliders: Query<
|
||||
Entity,
|
||||
(
|
||||
With<LevelObject>,
|
||||
Or<(With<PhysicsBody>, With<ColliderDesc>)>,
|
||||
),
|
||||
>,
|
||||
lights: Query<Entity, (With<LevelObject>, With<LightDesc>)>,
|
||||
spawns: Query<Entity, (With<LevelObject>, With<PlayerSpawn>)>,
|
||||
prefabs: Query<Entity, (With<LevelObject>, With<PrefabRef>)>,
|
||||
models: Query<Entity, (With<LevelObject>, With<ModelRef>)>,
|
||||
players: Query<Entity, With<Player>>,
|
||||
cameras: Query<Entity, With<PlayerCamera>>,
|
||||
project_suns: Query<Entity, With<ProjectSun>>,
|
||||
) {
|
||||
let mut desired = std::collections::HashSet::new();
|
||||
let collider_mode = *viewport_mode == EditorViewportMode::Collider;
|
||||
let proxies_active = !display.clean_game_view
|
||||
&& settings.enabled
|
||||
&& (settings.pickable_proxies || collider_mode);
|
||||
|
||||
if proxies_active {
|
||||
if settings.show_colliders || collider_mode {
|
||||
desired.extend(
|
||||
colliders
|
||||
.iter()
|
||||
.map(|target| (target, VisualizerKind::Collider)),
|
||||
);
|
||||
}
|
||||
if settings.show_lights && !collider_mode {
|
||||
desired.extend(lights.iter().map(|target| (target, VisualizerKind::Light)));
|
||||
}
|
||||
if settings.show_spawns && !collider_mode {
|
||||
desired.extend(
|
||||
spawns
|
||||
.iter()
|
||||
.map(|target| (target, VisualizerKind::PlayerSpawn)),
|
||||
);
|
||||
}
|
||||
if settings.show_prefab_model_anchors && !collider_mode {
|
||||
desired.extend(
|
||||
prefabs
|
||||
.iter()
|
||||
.map(|target| (target, VisualizerKind::Prefab)),
|
||||
);
|
||||
desired.extend(models.iter().map(|target| (target, VisualizerKind::Model)));
|
||||
}
|
||||
if settings.show_runtime && !collider_mode {
|
||||
desired.extend(
|
||||
players
|
||||
.iter()
|
||||
.map(|target| (target, VisualizerKind::Player)),
|
||||
);
|
||||
desired.extend(
|
||||
cameras
|
||||
.iter()
|
||||
.map(|target| (target, VisualizerKind::Camera)),
|
||||
);
|
||||
desired.extend(
|
||||
project_suns
|
||||
.iter()
|
||||
.map(|target| (target, VisualizerKind::ProjectSun)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let existing: std::collections::HashSet<(Entity, VisualizerKind)> = proxies
|
||||
.iter()
|
||||
.map(|(_, proxy, _)| (proxy.target, proxy.kind))
|
||||
.collect();
|
||||
|
||||
for (entity, proxy, mut transform) in &mut proxies {
|
||||
if !desired.contains(&(proxy.target, proxy.kind)) || transforms.get(proxy.target).is_err() {
|
||||
commands.entity(entity).despawn();
|
||||
} else if let Ok(global) = transforms.get(proxy.target) {
|
||||
transform.translation = global.translation();
|
||||
}
|
||||
}
|
||||
|
||||
for (target, kind) in desired {
|
||||
let Ok(global) = transforms.get(target) else {
|
||||
continue;
|
||||
};
|
||||
if existing.contains(&(target, kind)) {
|
||||
continue;
|
||||
}
|
||||
commands.spawn((
|
||||
EditorOnly,
|
||||
RaytracingExcluded,
|
||||
Name::new(format!("{kind:?} Visualizer Proxy")),
|
||||
EditorVisualizerProxy { target, kind },
|
||||
Mesh3d(assets.mesh.clone()),
|
||||
MeshMaterial3d(assets.material.clone()),
|
||||
Transform::from_translation(global.translation()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_visualizers(
|
||||
viewport_mode: Res<EditorViewportMode>,
|
||||
settings: Res<EditorVisualizationSettings>,
|
||||
selected: Res<SelectedEntity>,
|
||||
mut gizmos: Gizmos,
|
||||
colliders: Query<(Entity, &PhysicsBody, &GlobalTransform), With<LevelObject>>,
|
||||
lights: Query<(Entity, &LightDesc, &GlobalTransform), With<LevelObject>>,
|
||||
spawns: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<PlayerSpawn>)>,
|
||||
prefabs: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<PrefabRef>)>,
|
||||
models: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<ModelRef>)>,
|
||||
players: Query<(Entity, &GlobalTransform), With<Player>>,
|
||||
cameras: Query<(Entity, &GlobalTransform), With<PlayerCamera>>,
|
||||
project_suns: Query<(Entity, &GlobalTransform), With<ProjectSun>>,
|
||||
triggers: Query<(Entity, &TriggerVolume, &GlobalTransform), With<LevelObject>>,
|
||||
weapons: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<WeaponSpawn>)>,
|
||||
teams: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<TeamSpawn>)>,
|
||||
objectives: Query<(Entity, &GlobalTransform), (With<LevelObject>, With<ObjectiveMarker>)>,
|
||||
) {
|
||||
let collider_mode = *viewport_mode == EditorViewportMode::Collider;
|
||||
if !settings.enabled && !collider_mode {
|
||||
return;
|
||||
}
|
||||
|
||||
if settings.show_colliders || collider_mode {
|
||||
for (entity, body, global) in &colliders {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
if collider_mode {
|
||||
Color::srgba(0.65, 1.0, 0.55, 1.0)
|
||||
} else {
|
||||
Color::srgba(0.55, 1.0, 0.45, 0.95)
|
||||
}
|
||||
} else if collider_mode {
|
||||
Color::srgba(0.35, 1.0, 0.45, 0.9)
|
||||
} else {
|
||||
Color::srgba(0.25, 0.9, 0.35, 0.55)
|
||||
};
|
||||
draw_collider(&mut gizmos, global, &body.collider, color);
|
||||
}
|
||||
}
|
||||
|
||||
if settings.show_lights && !collider_mode {
|
||||
for (entity, light, global) in &lights {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
Color::srgba(1.0, 0.9, 0.35, 1.0)
|
||||
} else {
|
||||
Color::srgba(1.0, 0.78, 0.25, 0.75)
|
||||
};
|
||||
draw_light(&mut gizmos, global, light, color, true);
|
||||
}
|
||||
}
|
||||
|
||||
if settings.show_spawns {
|
||||
for (entity, global) in &spawns {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
Color::srgba(0.2, 1.0, 1.0, 1.0)
|
||||
} else {
|
||||
Color::srgba(0.15, 0.85, 1.0, 0.75)
|
||||
};
|
||||
draw_spawn(&mut gizmos, global, color);
|
||||
}
|
||||
}
|
||||
|
||||
if settings.show_prefab_model_anchors {
|
||||
for (entity, global) in &prefabs {
|
||||
draw_anchor(
|
||||
&mut gizmos,
|
||||
global,
|
||||
selected.0 == Some(entity),
|
||||
Color::srgb(0.75, 0.45, 1.0),
|
||||
);
|
||||
}
|
||||
for (entity, global) in &models {
|
||||
draw_anchor(
|
||||
&mut gizmos,
|
||||
global,
|
||||
selected.0 == Some(entity),
|
||||
Color::srgb(0.5, 0.6, 1.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if settings.show_runtime {
|
||||
for (entity, global) in &players {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
Color::srgba(0.25, 0.65, 1.0, 1.0)
|
||||
} else {
|
||||
Color::srgba(0.25, 0.65, 1.0, 0.7)
|
||||
};
|
||||
draw_player(&mut gizmos, global, color);
|
||||
}
|
||||
for (entity, global) in &cameras {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
Color::srgba(0.4, 0.85, 1.0, 1.0)
|
||||
} else {
|
||||
Color::srgba(0.4, 0.85, 1.0, 0.7)
|
||||
};
|
||||
draw_camera_frustum(&mut gizmos, global, color);
|
||||
}
|
||||
for (entity, global) in &project_suns {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
Color::srgba(1.0, 0.88, 0.32, 1.0)
|
||||
} else {
|
||||
Color::srgba(1.0, 0.78, 0.18, 0.75)
|
||||
};
|
||||
draw_project_sun(&mut gizmos, global, color, true);
|
||||
}
|
||||
}
|
||||
|
||||
for (entity, trigger, global) in &triggers {
|
||||
draw_oriented_box(
|
||||
&mut gizmos,
|
||||
global,
|
||||
trigger.half_extents,
|
||||
if selected.0 == Some(entity) {
|
||||
Color::srgba(0.95, 0.35, 0.95, 0.85)
|
||||
} else {
|
||||
Color::srgba(0.9, 0.3, 0.9, 0.45)
|
||||
},
|
||||
);
|
||||
}
|
||||
for (entity, global) in &weapons {
|
||||
draw_anchor(
|
||||
&mut gizmos,
|
||||
global,
|
||||
selected.0 == Some(entity),
|
||||
Color::srgb(1.0, 0.35, 0.2),
|
||||
);
|
||||
}
|
||||
for (entity, global) in &teams {
|
||||
draw_anchor(
|
||||
&mut gizmos,
|
||||
global,
|
||||
selected.0 == Some(entity),
|
||||
Color::srgb(0.2, 0.85, 0.35),
|
||||
);
|
||||
}
|
||||
for (entity, global) in &objectives {
|
||||
draw_anchor(
|
||||
&mut gizmos,
|
||||
global,
|
||||
selected.0 == Some(entity),
|
||||
Color::srgb(0.95, 0.85, 0.2),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_split_collider_visualizers(
|
||||
viewport_mode: Res<EditorViewportMode>,
|
||||
settings: Res<EditorVisualizationSettings>,
|
||||
selected: Res<SelectedEntity>,
|
||||
mut gizmos: Gizmos,
|
||||
colliders: Query<
|
||||
(Entity, &ColliderDesc, &GlobalTransform),
|
||||
(With<LevelObject>, Without<PhysicsBody>),
|
||||
>,
|
||||
) {
|
||||
let collider_mode = *viewport_mode == EditorViewportMode::Collider;
|
||||
if !settings.enabled && !collider_mode {
|
||||
return;
|
||||
}
|
||||
if !(settings.show_colliders || collider_mode) {
|
||||
return;
|
||||
}
|
||||
for (entity, collider, global) in &colliders {
|
||||
let color = if selected.0 == Some(entity) {
|
||||
Color::srgba(0.65, 1.0, 0.55, 1.0)
|
||||
} else if collider_mode {
|
||||
Color::srgba(0.35, 1.0, 0.45, 0.9)
|
||||
} else {
|
||||
Color::srgba(0.25, 0.9, 0.35, 0.55)
|
||||
};
|
||||
draw_collider_desc(&mut gizmos, global, collider, color);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_post_process_volume_gizmos(
|
||||
viewport_mode: Res<EditorViewportMode>,
|
||||
settings: Res<EditorVisualizationSettings>,
|
||||
selected: Res<SelectedEntity>,
|
||||
mut gizmos: Gizmos,
|
||||
volumes: Query<(Entity, &PostProcessVolumeDesc, &GlobalTransform), With<LevelObject>>,
|
||||
) {
|
||||
if *viewport_mode == EditorViewportMode::Collider || !settings.enabled {
|
||||
return;
|
||||
}
|
||||
for (entity, volume, global) in &volumes {
|
||||
let t = ((volume.priority + 10) as f32 / 110.0).clamp(0.0, 1.0);
|
||||
let border = Color::srgba(0.2 + 0.8 * t, 0.45 + 0.2 * (1.0 - t), 1.0 - 0.65 * t, 0.95);
|
||||
draw_oriented_box(
|
||||
&mut gizmos,
|
||||
global,
|
||||
volume.half_extents,
|
||||
if selected.0 == Some(entity) {
|
||||
border.with_alpha(1.0)
|
||||
} else {
|
||||
border.with_alpha(0.55)
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_collider(
|
||||
gizmos: &mut Gizmos,
|
||||
global: &GlobalTransform,
|
||||
collider: &ColliderConstructor,
|
||||
color: Color,
|
||||
) {
|
||||
match collider {
|
||||
ColliderConstructor::Cuboid {
|
||||
x_length,
|
||||
y_length,
|
||||
z_length,
|
||||
} => draw_box(
|
||||
gizmos,
|
||||
global.translation(),
|
||||
global.rotation(),
|
||||
Vec3::new(*x_length, *y_length, *z_length) * 0.5,
|
||||
color,
|
||||
),
|
||||
ColliderConstructor::Sphere { radius } => {
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(global.translation(), global.rotation()),
|
||||
*radius,
|
||||
color,
|
||||
)
|
||||
.resolution(24);
|
||||
}
|
||||
ColliderConstructor::Capsule { radius, height } => {
|
||||
draw_capsule(
|
||||
gizmos,
|
||||
global.translation(),
|
||||
global.rotation(),
|
||||
*radius,
|
||||
*height,
|
||||
color,
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(global.translation(), global.rotation()),
|
||||
0.5,
|
||||
color,
|
||||
)
|
||||
.resolution(16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_collider_desc(
|
||||
gizmos: &mut Gizmos,
|
||||
global: &GlobalTransform,
|
||||
collider: &ColliderDesc,
|
||||
color: Color,
|
||||
) {
|
||||
if !collider.enabled {
|
||||
return;
|
||||
}
|
||||
match &collider.shape {
|
||||
ColliderShapeDesc::Cuboid {
|
||||
x_length,
|
||||
y_length,
|
||||
z_length,
|
||||
} => draw_box(
|
||||
gizmos,
|
||||
global.translation(),
|
||||
global.rotation(),
|
||||
Vec3::new(*x_length, *y_length, *z_length) * 0.5,
|
||||
color,
|
||||
),
|
||||
ColliderShapeDesc::Sphere { radius } => {
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(global.translation(), global.rotation()),
|
||||
*radius,
|
||||
color,
|
||||
)
|
||||
.resolution(24);
|
||||
}
|
||||
ColliderShapeDesc::Capsule { radius, height } => {
|
||||
draw_capsule(
|
||||
gizmos,
|
||||
global.translation(),
|
||||
global.rotation(),
|
||||
*radius,
|
||||
*height,
|
||||
color,
|
||||
);
|
||||
}
|
||||
ColliderShapeDesc::StaticMesh { .. } => {
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(global.translation(), global.rotation()),
|
||||
0.35,
|
||||
color,
|
||||
)
|
||||
.resolution(16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_light(
|
||||
gizmos: &mut Gizmos,
|
||||
global: &GlobalTransform,
|
||||
light: &LightDesc,
|
||||
color: Color,
|
||||
emphasize: bool,
|
||||
) {
|
||||
let center = global.translation();
|
||||
let forward = global.forward().as_vec3();
|
||||
match light.kind {
|
||||
AuthoringLightKind::Point => {
|
||||
let radius = light.range.max(0.25);
|
||||
gizmos
|
||||
.sphere(Isometry3d::new(center, global.rotation()), radius, color)
|
||||
.resolution(32);
|
||||
if emphasize {
|
||||
gizmos
|
||||
.circle(
|
||||
Isometry3d::from_translation(center),
|
||||
radius,
|
||||
color.with_alpha(0.45),
|
||||
)
|
||||
.resolution(32);
|
||||
}
|
||||
}
|
||||
AuthoringLightKind::Spot => {
|
||||
let range = light.range.max(1.0);
|
||||
let end = center + forward * range;
|
||||
gizmos.arrow(center, end, color);
|
||||
let right = global.right().as_vec3();
|
||||
let up = global.up().as_vec3();
|
||||
let outer_deg = light.outer_angle_deg.max(light.inner_angle_deg);
|
||||
let radius = range * (outer_deg.to_radians() * 0.5).tan().max(0.15);
|
||||
for offset in [right, -right, up, -up] {
|
||||
gizmos.line(center, end + offset * radius, color);
|
||||
}
|
||||
gizmos
|
||||
.circle(Isometry3d::new(end, global.rotation()), radius, color)
|
||||
.resolution(24);
|
||||
if emphasize {
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(end, global.rotation()),
|
||||
radius * 0.12,
|
||||
color.with_alpha(0.5),
|
||||
)
|
||||
.resolution(12);
|
||||
}
|
||||
}
|
||||
AuthoringLightKind::Directional => {
|
||||
draw_directional_light_arrow(gizmos, global, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_directional_light_arrow(gizmos: &mut Gizmos, global: &GlobalTransform, color: Color) {
|
||||
let center = global.translation();
|
||||
let forward = global.forward().as_vec3();
|
||||
let arrow_len = 5.0;
|
||||
let tail = center - forward * arrow_len;
|
||||
gizmos.arrow(tail, center, color);
|
||||
gizmos
|
||||
.sphere(Isometry3d::new(center, global.rotation()), 0.4, color)
|
||||
.resolution(18);
|
||||
let right = global.right().as_vec3();
|
||||
let up = global.up().as_vec3();
|
||||
for offset in [right, -right, up, -up] {
|
||||
gizmos.line(center, center + offset * 0.75, color.with_alpha(0.65));
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_spawn(gizmos: &mut Gizmos, global: &GlobalTransform, color: Color) {
|
||||
let center = global.translation();
|
||||
draw_capsule(
|
||||
gizmos,
|
||||
center,
|
||||
global.rotation(),
|
||||
PLAYER_RADIUS,
|
||||
PLAYER_LENGTH,
|
||||
color,
|
||||
);
|
||||
gizmos.arrow(center, center + global.forward().as_vec3() * 1.25, color);
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(center + Vec3::Y * EYE_OFFSET_STAND, global.rotation()),
|
||||
0.08,
|
||||
color,
|
||||
)
|
||||
.resolution(10);
|
||||
}
|
||||
|
||||
fn draw_anchor(gizmos: &mut Gizmos, global: &GlobalTransform, selected: bool, base: Color) {
|
||||
let center = global.translation();
|
||||
let color = if selected {
|
||||
Color::srgba(1.0, 0.85, 1.0, 1.0)
|
||||
} else {
|
||||
base.with_alpha(0.75)
|
||||
};
|
||||
gizmos.axes(Isometry3d::new(center, global.rotation()), 0.8);
|
||||
draw_box(gizmos, center, global.rotation(), Vec3::splat(0.35), color);
|
||||
}
|
||||
|
||||
fn draw_player(gizmos: &mut Gizmos, global: &GlobalTransform, color: Color) {
|
||||
let center = global.translation();
|
||||
draw_capsule(
|
||||
gizmos,
|
||||
center,
|
||||
global.rotation(),
|
||||
PLAYER_RADIUS,
|
||||
PLAYER_LENGTH,
|
||||
color,
|
||||
);
|
||||
gizmos.arrow(center, center + global.forward().as_vec3() * 1.25, color);
|
||||
gizmos
|
||||
.sphere(
|
||||
Isometry3d::new(center + Vec3::Y * EYE_OFFSET_STAND, global.rotation()),
|
||||
0.08,
|
||||
color,
|
||||
)
|
||||
.resolution(10);
|
||||
}
|
||||
|
||||
fn draw_project_sun(gizmos: &mut Gizmos, global: &GlobalTransform, color: Color, emphasize: bool) {
|
||||
let center = global.translation();
|
||||
gizmos
|
||||
.sphere(Isometry3d::new(center, global.rotation()), 0.45, color)
|
||||
.resolution(20);
|
||||
draw_directional_light_arrow(gizmos, global, color);
|
||||
if emphasize {
|
||||
gizmos
|
||||
.circle(
|
||||
Isometry3d::new(center, global.rotation()),
|
||||
1.0,
|
||||
color.with_alpha(0.35),
|
||||
)
|
||||
.resolution(28);
|
||||
} else {
|
||||
gizmos
|
||||
.circle(Isometry3d::new(center, global.rotation()), 0.75, color)
|
||||
.resolution(24);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_camera_frustum(gizmos: &mut Gizmos, global: &GlobalTransform, color: Color) {
|
||||
let origin = global.translation();
|
||||
let forward = global.forward().as_vec3();
|
||||
let right = global.right().as_vec3();
|
||||
let up = global.up().as_vec3();
|
||||
let near = origin + forward * 0.8;
|
||||
let half_w = 0.45;
|
||||
let half_h = 0.28;
|
||||
let corners = [
|
||||
near + right * half_w + up * half_h,
|
||||
near - right * half_w + up * half_h,
|
||||
near - right * half_w - up * half_h,
|
||||
near + right * half_w - up * half_h,
|
||||
];
|
||||
for corner in corners {
|
||||
gizmos.line(origin, corner, color);
|
||||
}
|
||||
gizmos.lineloop(corners, color);
|
||||
}
|
||||
|
||||
fn draw_box(gizmos: &mut Gizmos, center: Vec3, rotation: Quat, half: Vec3, color: Color) {
|
||||
let corners = [
|
||||
Vec3::new(-half.x, -half.y, -half.z),
|
||||
Vec3::new(half.x, -half.y, -half.z),
|
||||
Vec3::new(half.x, -half.y, half.z),
|
||||
Vec3::new(-half.x, -half.y, half.z),
|
||||
Vec3::new(-half.x, half.y, -half.z),
|
||||
Vec3::new(half.x, half.y, -half.z),
|
||||
Vec3::new(half.x, half.y, half.z),
|
||||
Vec3::new(-half.x, half.y, half.z),
|
||||
]
|
||||
.map(|corner| center + rotation * corner);
|
||||
|
||||
for (a, b) in [
|
||||
(0, 1),
|
||||
(1, 2),
|
||||
(2, 3),
|
||||
(3, 0),
|
||||
(4, 5),
|
||||
(5, 6),
|
||||
(6, 7),
|
||||
(7, 4),
|
||||
(0, 4),
|
||||
(1, 5),
|
||||
(2, 6),
|
||||
(3, 7),
|
||||
] {
|
||||
gizmos.line(corners[a], corners[b], color);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_capsule(
|
||||
gizmos: &mut Gizmos,
|
||||
center: Vec3,
|
||||
rotation: Quat,
|
||||
radius: f32,
|
||||
length: f32,
|
||||
color: Color,
|
||||
) {
|
||||
let half = length * 0.5;
|
||||
let top = center + rotation * Vec3::Y * half;
|
||||
let bottom = center - rotation * Vec3::Y * half;
|
||||
|
||||
gizmos
|
||||
.sphere(Isometry3d::new(top, rotation), radius, color)
|
||||
.resolution(16);
|
||||
gizmos
|
||||
.sphere(Isometry3d::new(bottom, rotation), radius, color)
|
||||
.resolution(16);
|
||||
|
||||
for (x, z) in [(radius, 0.0), (-radius, 0.0), (0.0, radius), (0.0, -radius)] {
|
||||
let offset = rotation * Vec3::new(x, 0.0, z);
|
||||
gizmos.line(top + offset, bottom + offset, color);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_oriented_box(
|
||||
gizmos: &mut Gizmos,
|
||||
global: &GlobalTransform,
|
||||
half_extents: Vec3,
|
||||
color: Color,
|
||||
) {
|
||||
let rotation = global.rotation();
|
||||
let center = global.translation();
|
||||
let corners = box_corners(center, rotation, half_extents);
|
||||
for (a, b) in box_edges() {
|
||||
gizmos.line(corners[a], corners[b], color);
|
||||
}
|
||||
}
|
||||
|
||||
fn box_corners(center: Vec3, rotation: Quat, half_extents: Vec3) -> [Vec3; 8] {
|
||||
let hx = half_extents.x;
|
||||
let hy = half_extents.y;
|
||||
let hz = half_extents.z;
|
||||
[
|
||||
center + rotation * Vec3::new(-hx, -hy, -hz),
|
||||
center + rotation * Vec3::new(hx, -hy, -hz),
|
||||
center + rotation * Vec3::new(hx, -hy, hz),
|
||||
center + rotation * Vec3::new(-hx, -hy, hz),
|
||||
center + rotation * Vec3::new(-hx, hy, -hz),
|
||||
center + rotation * Vec3::new(hx, hy, -hz),
|
||||
center + rotation * Vec3::new(hx, hy, hz),
|
||||
center + rotation * Vec3::new(-hx, hy, hz),
|
||||
]
|
||||
}
|
||||
|
||||
fn box_edges() -> [(usize, usize); 12] {
|
||||
[
|
||||
(0, 1),
|
||||
(1, 2),
|
||||
(2, 3),
|
||||
(3, 0),
|
||||
(4, 5),
|
||||
(5, 6),
|
||||
(6, 7),
|
||||
(7, 4),
|
||||
(0, 4),
|
||||
(1, 5),
|
||||
(2, 6),
|
||||
(3, 7),
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user