Advance M0 scene and rendering foundations
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-06-06 03:50:03 -04:00
1 parent 2fa64106c8
commit 2054fa2558
21 files changed
+711 -159

No files matched your search

+376
View File
@@ -0,0 +1,376 @@
//! Schema-aware scene document seam over the current DynamicScene RON format.
//!
//! This module intentionally stays Bevy-free. The editor can keep loading and
//! saving DynamicScene RON while tools start depending on stable actor/component
//! document concepts instead of runtime ECS entity IDs.
use std::collections::BTreeMap;
use ron::ser::PrettyConfig;
use serde::{Deserialize, Serialize};
use crate::{
migrate_scene_text, read_schema_version, stamp_schema_version, strip_schema_version,
validate_scene_authoring_only,
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SceneDocument {
pub schema_version: u32,
pub entities: Vec<SceneEntity>,
normalized_ron: String,
}
impl SceneDocument {
pub fn from_ron_text(text: &str) -> Result<Self, String> {
let normalized = migrate_scene_text(text)?;
validate_scene_authoring_only(&normalized)?;
let body = strip_schema_version(&normalized)?;
let parsed: DynamicSceneBody = ron::from_str(&body)
.map_err(|err| format!("could not parse scene document body: {err}"))?;
let mut entities = Vec::with_capacity(parsed.entities.len());
for (index, (_source_key, entity)) in parsed.entities.into_iter().enumerate() {
let components = entity
.components
.into_iter()
.map(|(type_name, value)| SceneComponentBlob::from_value(type_name, value))
.collect::<Result<Vec<_>, _>>()?;
let actor_id = extract_actor_id(&components);
let name = extract_name(&components);
let document_id = actor_id
.as_ref()
.map(|id| SceneEntityId::ActorId(id.clone()))
.unwrap_or_else(|| SceneEntityId::Anonymous(format!("anonymous:{index}")));
entities.push(SceneEntity {
document_id,
actor_id,
name,
parent_actor_id: None,
components,
});
}
Ok(Self {
schema_version: read_schema_version(&normalized),
entities,
normalized_ron: normalized,
})
}
pub fn to_ron_text(&self) -> Result<String, String> {
stamp_schema_version(&self.normalized_ron)
}
pub fn normalized_ron(&self) -> &str {
&self.normalized_ron
}
pub fn find_entity(&self, id: &SceneEntityId) -> Option<&SceneEntity> {
self.entities
.iter()
.find(|entity| &entity.document_id == id)
}
pub fn apply_patch(&mut self, patch: ScenePatch) -> Result<(), String> {
match patch {
ScenePatch::SetComponent { target, component } => {
let entity = self
.find_entity_mut(&target)
.ok_or_else(|| format!("scene entity `{target}` not found"))?;
if let Some(existing) = entity
.components
.iter_mut()
.find(|existing| existing.type_name == component.type_name)
{
*existing = component;
} else {
entity.components.push(component);
}
}
ScenePatch::RemoveComponent {
target,
component_type,
} => {
let entity = self
.find_entity_mut(&target)
.ok_or_else(|| format!("scene entity `{target}` not found"))?;
entity
.components
.retain(|component| component.type_name != component_type);
}
ScenePatch::AddEntity { entity } => {
if self.find_entity(&entity.document_id).is_some() {
return Err(format!(
"scene entity `{}` already exists",
entity.document_id
));
}
self.entities.push(entity);
}
ScenePatch::DeleteEntity { target } => {
let before = self.entities.len();
self.entities.retain(|entity| entity.document_id != target);
if self.entities.len() == before {
return Err(format!("scene entity `{target}` not found"));
}
}
ScenePatch::Reparent {
target,
parent_actor_id,
} => {
let entity = self
.find_entity_mut(&target)
.ok_or_else(|| format!("scene entity `{target}` not found"))?;
entity.parent_actor_id = parent_actor_id;
}
ScenePatch::Rename { target, name } => {
let entity = self
.find_entity_mut(&target)
.ok_or_else(|| format!("scene entity `{target}` not found"))?;
entity.name = Some(name);
}
ScenePatch::SetTransform { target, transform } => {
let entity = self
.find_entity_mut(&target)
.ok_or_else(|| format!("scene entity `{target}` not found"))?;
let component =
SceneComponentBlob::from_serializable(TRANSFORM_COMPONENT, &transform)?;
if let Some(existing) = entity
.components
.iter_mut()
.find(|existing| existing.type_name == TRANSFORM_COMPONENT)
{
*existing = component;
} else {
entity.components.push(component);
}
}
}
Ok(())
}
fn find_entity_mut(&mut self, id: &SceneEntityId) -> Option<&mut SceneEntity> {
self.entities
.iter_mut()
.find(|entity| &entity.document_id == id)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum SceneEntityId {
ActorId(String),
Anonymous(String),
}
impl std::fmt::Display for SceneEntityId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ActorId(id) => write!(f, "actor:{id}"),
Self::Anonymous(id) => write!(f, "{id}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SceneEntity {
pub document_id: SceneEntityId,
pub actor_id: Option<String>,
pub name: Option<String>,
pub parent_actor_id: Option<String>,
pub components: Vec<SceneComponentBlob>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SceneComponentBlob {
pub type_name: String,
pub ron: String,
}
impl SceneComponentBlob {
pub fn from_serializable(
type_name: impl Into<String>,
value: &impl Serialize,
) -> Result<Self, String> {
let pretty = PrettyConfig::new();
let ron = ron::ser::to_string_pretty(value, pretty)
.map_err(|err| format!("could not serialize component blob: {err}"))?;
Ok(Self {
type_name: type_name.into(),
ron,
})
}
fn from_value(type_name: String, value: ron::Value) -> Result<Self, String> {
let pretty = PrettyConfig::new();
let ron = ron::ser::to_string_pretty(&value, pretty)
.map_err(|err| format!("could not serialize component value `{type_name}`: {err}"))?;
Ok(Self { type_name, ron })
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ScenePatch {
SetComponent {
target: SceneEntityId,
component: SceneComponentBlob,
},
RemoveComponent {
target: SceneEntityId,
component_type: String,
},
AddEntity {
entity: SceneEntity,
},
DeleteEntity {
target: SceneEntityId,
},
Reparent {
target: SceneEntityId,
parent_actor_id: Option<String>,
},
Rename {
target: SceneEntityId,
name: String,
},
SetTransform {
target: SceneEntityId,
transform: SceneTransform,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SceneTransform {
pub translation: [f32; 3],
pub rotation: [f32; 4],
pub scale: [f32; 3],
}
impl Default for SceneTransform {
fn default() -> Self {
Self {
translation: [0.0, 0.0, 0.0],
rotation: [0.0, 0.0, 0.0, 1.0],
scale: [1.0, 1.0, 1.0],
}
}
}
#[derive(Debug, Deserialize)]
struct DynamicSceneBody {
#[serde(default)]
entities: BTreeMap<u64, DynamicSceneEntity>,
}
#[derive(Debug, Deserialize)]
struct DynamicSceneEntity {
#[serde(default)]
components: BTreeMap<String, ron::Value>,
}
const ACTOR_ID_COMPONENT: &str = "shared::components::ActorId";
const NAME_COMPONENT: &str = "bevy_ecs::name::Name";
pub const TRANSFORM_COMPONENT: &str = "bevy_transform::components::transform::Transform";
fn extract_name(components: &[SceneComponentBlob]) -> Option<String> {
components
.iter()
.find(|component| component.type_name == NAME_COMPONENT)
.map(|component| component.ron.trim().trim_matches('"').to_string())
.filter(|name| !name.is_empty())
}
fn extract_actor_id(components: &[SceneComponentBlob]) -> Option<String> {
let component = components
.iter()
.find(|component| component.type_name == ACTOR_ID_COMPONENT)?;
ron::from_str::<String>(&component.ron)
.ok()
.or_else(|| {
ron::from_str::<Vec<String>>(&component.ron)
.ok()
.and_then(|values| values.into_iter().next())
})
.filter(|value| !value.trim().is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_scene_document_without_exposing_runtime_entity_ids() {
let text = r#"(schema_version: 2,
resources: {},
entities: {
4294967133: (
components: {
"bevy_ecs::name::Name": "Crate",
"shared::components::ActorId": ("crate-01"),
"shared::components::LevelObject": (),
},
),
},
)"#;
let document = SceneDocument::from_ron_text(text).unwrap();
assert_eq!(document.schema_version, crate::CURRENT_SCENE_SCHEMA_VERSION);
assert_eq!(document.entities.len(), 1);
assert_eq!(document.entities[0].actor_id.as_deref(), Some("crate-01"));
assert_eq!(document.entities[0].name.as_deref(), Some("Crate"));
assert_eq!(
document.entities[0].document_id,
SceneEntityId::ActorId("crate-01".into())
);
assert!(!format!("{:?}", document.entities[0].document_id).contains("4294967133"));
}
#[test]
fn round_trips_normalized_ron_text() {
let body = "(resources: {}, entities: {})";
let document = SceneDocument::from_ron_text(body).unwrap();
let text = document.to_ron_text().unwrap();
assert!(text.starts_with("(schema_version: 2,"));
assert!(text.contains("entities: {}"));
}
#[test]
fn patch_rename_and_transform_are_representable() {
let text = r#"(schema_version: 2,
resources: {},
entities: {
1: (
components: {
"shared::components::ActorId": ("actor-a"),
"shared::components::LevelObject": (),
},
),
},
)"#;
let mut document = SceneDocument::from_ron_text(text).unwrap();
let target = SceneEntityId::ActorId("actor-a".into());
document
.apply_patch(ScenePatch::Rename {
target: target.clone(),
name: "Renamed".into(),
})
.unwrap();
document
.apply_patch(ScenePatch::SetTransform {
target: target.clone(),
transform: SceneTransform {
translation: [1.0, 2.0, 3.0],
..Default::default()
},
})
.unwrap();
let entity = document.find_entity(&target).unwrap();
assert_eq!(entity.name.as_deref(), Some("Renamed"));
assert!(entity
.components
.iter()
.any(|component| component.type_name == TRANSFORM_COMPONENT));
}
}
+1
View File
@@ -3,6 +3,7 @@
//! Bevy dynamic scenes are stored as RON tuples. On save the editor stamps
//! `schema_version` as the first root field; loaders strip it before deserializing.
pub mod document;
mod migrate;
use std::path::Path;