This commit is contained in:
commit
f29712d158
259 files changed
+52069
No files matched your search
@@ -0,0 +1,195 @@
|
||||
//! Scene file schema versioning for `assets/levels/*.scn.ron`.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
mod migrate;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use migrate::{migrate_v1_to_v2, DEFAULT_SUN_ILLUMINANCE_LUX};
|
||||
|
||||
pub const CURRENT_SCENE_SCHEMA_VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SceneSchemaHeader {
|
||||
pub schema_version: u32,
|
||||
}
|
||||
|
||||
impl Default for SceneSchemaHeader {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
schema_version: CURRENT_SCENE_SCHEMA_VERSION,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_schema_version(text: &str) -> u32 {
|
||||
let trimmed = text.trim();
|
||||
if !trimmed.starts_with("(schema_version:") {
|
||||
return 1;
|
||||
}
|
||||
let inner = trimmed
|
||||
.strip_prefix('(')
|
||||
.and_then(|s| s.strip_prefix("schema_version:"))
|
||||
.unwrap_or("");
|
||||
let version_str = inner.trim().split(',').next().unwrap_or("1").trim();
|
||||
version_str.parse().unwrap_or(1)
|
||||
}
|
||||
|
||||
/// Inserts `schema_version` as the first field of a Bevy dynamic-scene RON root tuple.
|
||||
pub fn stamp_schema_version(text: &str) -> Result<String, String> {
|
||||
let trimmed = text.trim();
|
||||
if trimmed.starts_with("(schema_version:") {
|
||||
let version = read_schema_version(trimmed);
|
||||
if version == CURRENT_SCENE_SCHEMA_VERSION {
|
||||
return Ok(trimmed.to_string());
|
||||
}
|
||||
let body = strip_schema_version(trimmed)?;
|
||||
return stamp_schema_version(&body);
|
||||
}
|
||||
if !trimmed.starts_with('(') || !trimmed.ends_with(')') {
|
||||
return Err("expected scene RON root tuple".into());
|
||||
}
|
||||
Ok(format!(
|
||||
"(schema_version: {},{}",
|
||||
CURRENT_SCENE_SCHEMA_VERSION,
|
||||
&trimmed[1..]
|
||||
))
|
||||
}
|
||||
|
||||
/// Applies versioned migrations and stamps the current schema header.
|
||||
pub fn migrate_scene_text(text: &str) -> Result<String, String> {
|
||||
let trimmed = text.trim();
|
||||
let version = read_schema_version(trimmed);
|
||||
let body = if trimmed.starts_with("(schema_version:") {
|
||||
strip_schema_version(trimmed)?
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
};
|
||||
|
||||
let migrated_body = match version {
|
||||
0 | 1 => migrate_v1_to_v2(&body),
|
||||
2 => body,
|
||||
_ => body,
|
||||
};
|
||||
|
||||
stamp_schema_version(&migrated_body)
|
||||
}
|
||||
|
||||
/// Removes the schema header so Bevy can deserialize the dynamic scene body.
|
||||
pub fn strip_schema_version(text: &str) -> Result<String, String> {
|
||||
let trimmed = text.trim();
|
||||
if !trimmed.starts_with("(schema_version:") {
|
||||
return Ok(trimmed.to_string());
|
||||
}
|
||||
let inner = trimmed
|
||||
.strip_prefix('(')
|
||||
.ok_or_else(|| "invalid schema wrapper".to_string())?;
|
||||
let after_key = inner
|
||||
.strip_prefix("schema_version:")
|
||||
.ok_or_else(|| "invalid schema_version prefix".to_string())?;
|
||||
let comma = after_key
|
||||
.find(',')
|
||||
.ok_or_else(|| "schema_version tuple missing body".to_string())?;
|
||||
Ok(format!("({}", after_key[comma + 1..].trim_start()))
|
||||
}
|
||||
|
||||
/// Hydrated/runtime component type names that must not appear in saved `.scn.ron` files.
|
||||
pub const FORBIDDEN_SAVED_COMPONENT_MARKERS: &[&str] = &[
|
||||
"bevy_pbr::PointLight",
|
||||
"bevy_pbr::SpotLight",
|
||||
"bevy_pbr::DirectionalLight",
|
||||
"bevy_mesh::Mesh3d",
|
||||
"bevy_mesh::MeshMaterial3d",
|
||||
"avian3d::RigidBody",
|
||||
"avian3d::Collider",
|
||||
"bevy_scene::SceneRoot",
|
||||
"bevy_render::visibility::ComputedVisibility",
|
||||
];
|
||||
|
||||
/// Ensures serialized scene text does not contain hydrated ECS component entries.
|
||||
pub fn validate_scene_authoring_only(text: &str) -> Result<(), String> {
|
||||
for marker in FORBIDDEN_SAVED_COMPONENT_MARKERS {
|
||||
if text.contains(marker) {
|
||||
return Err(format!(
|
||||
"scene file contains hydrated component marker `{marker}` (save allowlist violation)"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_level_text(text: &str) -> Result<(), String> {
|
||||
if text.trim().is_empty() {
|
||||
return Err("empty scene file".into());
|
||||
}
|
||||
let migrated = migrate_scene_text(text)?;
|
||||
strip_schema_version(&migrated)?;
|
||||
validate_scene_authoring_only(&migrated)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_level_file(path: &Path) -> Result<(), String> {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
validate_level_text(&text)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stamp_and_strip_round_trip() {
|
||||
let body = "(resources: {}, entities: {})";
|
||||
let stamped = stamp_schema_version(body).unwrap();
|
||||
assert!(stamped.starts_with("(schema_version: 2,"));
|
||||
let stripped = strip_schema_version(&stamped).unwrap();
|
||||
assert_eq!(stripped, body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_scene_migrates_to_v2() {
|
||||
let legacy = "(resources: {}, entities: {4294967133: ()})";
|
||||
let migrated = migrate_scene_text(legacy).unwrap();
|
||||
assert!(migrated.contains("schema_version: 2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "run manually to rewrite assets/levels/editor_scene.scn.ron"]
|
||||
fn migrate_editor_scene_on_disk() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../assets/levels/editor_scene.scn.ron");
|
||||
let text = std::fs::read_to_string(&path).expect("read editor scene");
|
||||
let migrated = migrate_scene_text(&text).expect("migrate");
|
||||
std::fs::write(&path, migrated).expect("write migrated scene");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_editor_scene_has_no_hydrated_components() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../assets/levels/editor_scene.scn.ron");
|
||||
let text = std::fs::read_to_string(&path).expect("read editor scene");
|
||||
validate_scene_authoring_only(&text).expect("editor scene must be authoring-only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v1_scene_gains_actor_kind_on_migrate() {
|
||||
let v1 = "(schema_version: 1,(resources: {}, entities: {
|
||||
1: (
|
||||
components: {
|
||||
\"shared::components::LevelObject\": (),
|
||||
\"shared::components::Primitive\": (
|
||||
shape: Box,
|
||||
size: (1.0, 1.0, 1.0),
|
||||
),
|
||||
},
|
||||
),
|
||||
}))";
|
||||
let migrated = migrate_scene_text(&v1).unwrap();
|
||||
assert!(migrated.contains("ActorKind"));
|
||||
assert!(migrated.contains("StaticMesh"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Versioned scene text migrations.
|
||||
|
||||
use shared::ActorKind;
|
||||
|
||||
pub const DEFAULT_SUN_ILLUMINANCE_LUX: f32 = 100_000.0;
|
||||
|
||||
/// Migrates v1 scene text to schema v2 (ActorKind backfill + directional lux fix).
|
||||
pub fn migrate_v1_to_v2(body: &str) -> String {
|
||||
let mut out = body.to_string();
|
||||
out = migrate_directional_light_intensity(&out);
|
||||
out = backfill_actor_kinds(&out);
|
||||
out
|
||||
}
|
||||
|
||||
fn backfill_actor_kinds(text: &str) -> String {
|
||||
let mut result = String::with_capacity(text.len() + 1024);
|
||||
let mut rest = text;
|
||||
while let Some(idx) = rest.find("components: {") {
|
||||
result.push_str(&rest[..idx]);
|
||||
let after = &rest[idx..];
|
||||
let Some(close) = find_components_close(after) else {
|
||||
result.push_str(after);
|
||||
break;
|
||||
};
|
||||
let block = &after[..close];
|
||||
let tail = &after[close..];
|
||||
if block.contains("\"shared::components::ActorKind\"") {
|
||||
result.push_str(block);
|
||||
} else if block.contains("\"shared::components::LevelObject\"") {
|
||||
let kind = infer_kind_from_block(block);
|
||||
result.push_str(&inject_actor_kind(block, kind));
|
||||
} else {
|
||||
result.push_str(block);
|
||||
}
|
||||
rest = tail;
|
||||
}
|
||||
result.push_str(rest);
|
||||
result
|
||||
}
|
||||
|
||||
fn find_components_close(after: &str) -> Option<usize> {
|
||||
let mut depth = 0;
|
||||
let bytes = after.as_bytes();
|
||||
for (i, &b) in bytes.iter().enumerate() {
|
||||
match b {
|
||||
b'{' => depth += 1,
|
||||
b'}' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Some(i + 1);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn inject_actor_kind(block: &str, kind: &str) -> String {
|
||||
let Some(close) = block.rfind('}') else {
|
||||
return block.to_string();
|
||||
};
|
||||
format!(
|
||||
"{block_prefix}\"shared::components::ActorKind\": {kind},\n {close_brace}",
|
||||
block_prefix = &block[..close],
|
||||
close_brace = &block[close..]
|
||||
)
|
||||
}
|
||||
|
||||
fn infer_kind_from_block(block: &str) -> &'static str {
|
||||
if block.contains("\"shared::components::PlayerSpawn\"") {
|
||||
return actor_kind_ron(ActorKind::PlayerSpawn);
|
||||
}
|
||||
if block.contains("\"shared::components::WeaponSpawn\"") {
|
||||
return actor_kind_ron(ActorKind::WeaponSpawn);
|
||||
}
|
||||
if block.contains("\"shared::components::TriggerVolume\"") {
|
||||
return actor_kind_ron(ActorKind::TriggerVolume);
|
||||
}
|
||||
if block.contains("\"shared::components::PostProcessVolumeDesc\"") {
|
||||
return actor_kind_ron(ActorKind::PostProcessVolume);
|
||||
}
|
||||
if block.contains("\"shared::components::TeamSpawn\"") {
|
||||
return actor_kind_ron(ActorKind::TeamSpawn);
|
||||
}
|
||||
if block.contains("\"shared::components::ObjectiveMarker\"") {
|
||||
return actor_kind_ron(ActorKind::Objective);
|
||||
}
|
||||
if block.contains("\"shared::components::LightDesc\"") {
|
||||
return actor_kind_ron(ActorKind::Light);
|
||||
}
|
||||
if block.contains("\"shared::components::ModelRef\"") {
|
||||
return actor_kind_ron(ActorKind::ImportedModel);
|
||||
}
|
||||
if block.contains("\"shared::components::Primitive\"")
|
||||
|| block.contains("\"shared::components::StaticMeshRenderer\"")
|
||||
{
|
||||
return actor_kind_ron(ActorKind::StaticMesh);
|
||||
}
|
||||
if block.contains("\"shared::components::PrefabRef\"")
|
||||
|| block.contains("\"shared::components::PrefabInstance\"")
|
||||
{
|
||||
return actor_kind_ron(ActorKind::PrefabAnchor);
|
||||
}
|
||||
actor_kind_ron(ActorKind::Empty)
|
||||
}
|
||||
|
||||
fn actor_kind_ron(kind: ActorKind) -> &'static str {
|
||||
match kind {
|
||||
ActorKind::Empty => "Empty",
|
||||
ActorKind::StaticMesh => "StaticMesh",
|
||||
ActorKind::ImportedModel => "ImportedModel",
|
||||
ActorKind::Light => "Light",
|
||||
ActorKind::PrefabAnchor => "PrefabAnchor",
|
||||
ActorKind::PlayerSpawn => "PlayerSpawn",
|
||||
ActorKind::WeaponSpawn => "WeaponSpawn",
|
||||
ActorKind::TriggerVolume => "TriggerVolume",
|
||||
ActorKind::PostProcessVolume => "PostProcessVolume",
|
||||
ActorKind::TeamSpawn => "TeamSpawn",
|
||||
ActorKind::Objective => "Objective",
|
||||
}
|
||||
}
|
||||
|
||||
fn migrate_directional_light_intensity(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find("\"shared::components::LightDesc\"") {
|
||||
out.push_str(&rest[..start]);
|
||||
let block_start = start;
|
||||
let Some(rel_end) = find_light_desc_block_end(&rest[block_start..]) else {
|
||||
out.push_str(&rest[block_start..]);
|
||||
return out;
|
||||
};
|
||||
let end = block_start + rel_end;
|
||||
let block = &rest[block_start..end];
|
||||
let migrated = if block.contains("kind: Directional") {
|
||||
fix_directional_intensity(block)
|
||||
} else {
|
||||
block.to_string()
|
||||
};
|
||||
out.push_str(&migrated);
|
||||
rest = &rest[end..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
fn find_light_desc_block_end(text: &str) -> Option<usize> {
|
||||
let open = text.find('(')?;
|
||||
let mut depth = 0;
|
||||
for (i, ch) in text[open..].char_indices() {
|
||||
match ch {
|
||||
'(' => depth += 1,
|
||||
')' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Some(open + i + 1);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn fix_directional_intensity(block: &str) -> String {
|
||||
let Some(intensity_idx) = block.find("intensity:") else {
|
||||
return block.to_string();
|
||||
};
|
||||
let after = &block[intensity_idx + "intensity:".len()..];
|
||||
let trimmed = after.trim_start();
|
||||
let end = trimmed
|
||||
.find(|c: char| c == ',' || c == ')')
|
||||
.unwrap_or(trimmed.len());
|
||||
let value_str = trimmed[..end].trim();
|
||||
let Ok(value) = value_str.parse::<f32>() else {
|
||||
return block.to_string();
|
||||
};
|
||||
if value >= 1000.0 {
|
||||
return block.to_string();
|
||||
}
|
||||
let replacement = format!("intensity: {}", DEFAULT_SUN_ILLUMINANCE_LUX);
|
||||
block.replace(&format!("intensity: {value_str}"), &replacement)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn backfills_actor_kind_for_primitive_entity() {
|
||||
let body = r#"(
|
||||
resources: {},
|
||||
entities: {
|
||||
1: (
|
||||
components: {
|
||||
"shared::components::LevelObject": (),
|
||||
"shared::components::Primitive": (
|
||||
shape: Box,
|
||||
size: (1.0, 1.0, 1.0),
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
)"#;
|
||||
let migrated = migrate_v1_to_v2(body);
|
||||
assert!(migrated.contains("ActorKind"));
|
||||
assert!(migrated.contains("StaticMesh"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixes_low_directional_lux() {
|
||||
let body = r#"(
|
||||
resources: {},
|
||||
entities: {
|
||||
1: (
|
||||
components: {
|
||||
"shared::components::LightDesc": (
|
||||
kind: Directional,
|
||||
color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0),
|
||||
intensity: 10.0,
|
||||
range: 0.0,
|
||||
shadows: true,
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
)"#;
|
||||
let migrated = migrate_v1_to_v2(body);
|
||||
assert!(migrated.contains("intensity: 100000"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user