Build renderer and material component foundations

Add dedicated skinned rendering, pose restoration, shared Material and Material Instance slots, registry-driven components, Surface/Solari integration, transactional schema upgrades, navigation authoring, documentation, and evaluation evidence.
This commit is contained in:
Rbanh committed 2026-07-12 00:24:06 -04:00
1 parent 0553a85220
commit 0798aa5d57
169 files changed
+27098 -3469

No files matched your search

+3
View File
@@ -10,5 +10,8 @@ blake3 = "1"
serde = { workspace = true }
ron = "0.8"
ron-edit = "=0.2.0"
nav_glam.workspace = true
polyanya.workspace = true
rerecast.workspace = true
shared.workspace = true
settings.workspace = true
+1 -1
View File
@@ -743,7 +743,7 @@ mod tests {
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.starts_with("(schema_version: 4,"));
assert!(SceneDocument::from_ron_text(&text)
.unwrap()
.entities
+14 -7
View File
@@ -6,15 +6,19 @@
mod composition;
pub mod document;
mod migrate;
pub mod navigation;
mod prefab;
mod project_validation;
mod upgrade;
use std::path::Path;
use serde::{Deserialize, Serialize};
pub use composition::{validate_composition_graph, validate_scene_composition};
pub use migrate::{migrate_v1_to_v2, DEFAULT_SUN_ILLUMINANCE_LUX};
pub use migrate::{
migrate_v1_to_v2, migrate_v2_to_v3, migrate_v3_to_v4, DEFAULT_SUN_ILLUMINANCE_LUX,
};
pub use prefab::{
prefab_graph_revision, validate_prefab_graph, validate_prefab_graph_text,
validate_prefab_references, validate_prefab_references_text,
@@ -23,8 +27,9 @@ pub use project_validation::{
validate_project, ProjectDependency, ProjectValidationFinding, ProjectValidationReport,
ValidationSeverity,
};
pub use upgrade::{upgrade_project, ProjectUpgradeChange, ProjectUpgradeReport};
pub const CURRENT_SCENE_SCHEMA_VERSION: u32 = 2;
pub const CURRENT_SCENE_SCHEMA_VERSION: u32 = 4;
/// Whether an asset-relative path names a tree excluded from runtime packages.
pub fn is_runtime_package_excluded_tree(relative: &Path) -> bool {
@@ -129,8 +134,10 @@ pub fn migrate_scene_text(text: &str) -> Result<String, String> {
};
let migrated_body = match version {
0 | 1 => migrate_v1_to_v2(&body),
2 => body,
0 | 1 => migrate_v3_to_v4(&migrate_v2_to_v3(&migrate_v1_to_v2(&body))),
2 => migrate_v3_to_v4(&migrate_v2_to_v3(&body)),
3 => migrate_v3_to_v4(&body),
4 => body,
_ => {
return Err(format!(
"scene schema version {version} is newer than supported version {CURRENT_SCENE_SCHEMA_VERSION}"
@@ -220,16 +227,16 @@ mod tests {
fn stamp_and_strip_round_trip() {
let body = "(resources: {}, entities: {})";
let stamped = stamp_schema_version(body).unwrap();
assert!(stamped.starts_with("(schema_version: 2,"));
assert!(stamped.starts_with("(schema_version: 4,"));
let stripped = strip_schema_version(&stamped).unwrap();
assert_eq!(stripped, body);
}
#[test]
fn legacy_scene_migrates_to_v2() {
fn legacy_scene_migrates_to_current_schema() {
let legacy = "(resources: {}, entities: {4294967133: ()})";
let migrated = migrate_scene_text(legacy).unwrap();
assert!(migrated.contains("schema_version: 2"));
assert!(migrated.contains("schema_version: 4"));
}
#[test]
+88
View File
@@ -12,6 +12,57 @@ pub fn migrate_v1_to_v2(body: &str) -> String {
out
}
/// Migrates v2 animated imported-model actors to the dedicated skinned renderer contract.
///
/// `ModelRef` and `SkinnedMeshRenderer` intentionally share the same serialized source fields, so
/// the migration can preserve stable asset IDs and cached paths without lossy reconstruction.
pub fn migrate_v2_to_v3(body: &str) -> String {
let mut result = String::with_capacity(body.len() + 256);
let mut rest = body;
while let Some(index) = rest.find("components: {") {
result.push_str(&rest[..index]);
let after = &rest[index..];
let Some(close) = find_components_close(after) else {
result.push_str(after);
return result;
};
let block = &after[..close];
if block.contains("\"shared::animation::AnimationControllerDesc\"")
&& block.contains("\"shared::components::ModelRef\"")
{
result.push_str(
&block
.replace(
"\"shared::components::ModelRef\"",
"\"shared::animation::SkinnedMeshRenderer\"",
)
.replace(
"\"shared::components::ActorKind\": ImportedModel",
"\"shared::components::ActorKind\": SkinnedMesh",
)
.replace(
"\"shared::components::ActorKind\":ImportedModel",
"\"shared::components::ActorKind\":SkinnedMesh",
),
);
} else {
result.push_str(block);
}
rest = &after[close..];
}
result.push_str(rest);
result
}
/// Migrates schema-v3 documents into the registry-driven renderer/component foundation.
///
/// The v4 authoring types deliberately use serde defaults for material-slot sets and component
/// enable state, so normal loading can remain read-only. The explicit project upgrader later
/// materializes shared Material assets and canonical slot IDs on disk.
pub fn migrate_v3_to_v4(body: &str) -> String {
body.to_string()
}
fn backfill_actor_kinds(text: &str) -> String {
let mut result = String::with_capacity(text.len() + 1024);
let mut rest = text;
@@ -89,6 +140,9 @@ fn infer_kind_from_block(block: &str) -> &'static str {
if block.contains("\"shared::components::LightDesc\"") {
return actor_kind_ron(ActorKind::Light);
}
if block.contains("\"shared::animation::SkinnedMeshRenderer\"") {
return actor_kind_ron(ActorKind::SkinnedMesh);
}
if block.contains("\"shared::components::ModelRef\"") {
return actor_kind_ron(ActorKind::ImportedModel);
}
@@ -111,6 +165,9 @@ fn infer_kind_from_block(block: &str) -> &'static str {
if block.contains("\"shared::components::AudioListenerDesc\"") {
return actor_kind_ron(ActorKind::AudioListener);
}
if block.contains("\"shared::navigation::Navigation") {
return actor_kind_ron(ActorKind::Navigation);
}
actor_kind_ron(ActorKind::Empty)
}
@@ -119,6 +176,7 @@ fn actor_kind_ron(kind: ActorKind) -> &'static str {
ActorKind::Empty => "Empty",
ActorKind::Brush => "Brush",
ActorKind::StaticMesh => "StaticMesh",
ActorKind::SkinnedMesh => "SkinnedMesh",
ActorKind::ImportedModel => "ImportedModel",
ActorKind::Light => "Light",
ActorKind::PrefabAnchor => "PrefabAnchor",
@@ -130,6 +188,7 @@ fn actor_kind_ron(kind: ActorKind) -> &'static str {
ActorKind::Objective => "Objective",
ActorKind::AudioSource => "AudioSource",
ActorKind::AudioListener => "AudioListener",
ActorKind::Navigation => "Navigation",
}
}
@@ -241,6 +300,35 @@ mod tests {
assert!(migrated.contains("Brush"));
}
#[test]
fn v2_animation_actor_moves_to_dedicated_skinned_renderer() {
let body = r#"(
resources: {},
entities: {
1: (components: {
"shared::components::LevelObject": (),
"shared::components::ActorKind": ImportedModel,
"shared::components::ModelRef": (asset_id: "hero", path: "models/hero.glb", scene_index: 0),
"shared::animation::AnimationControllerDesc": (skeleton: None, states: [], default_state: "", default_crossfade_seconds: 0.2),
}),
2: (components: {
"shared::components::ActorKind": ImportedModel,
"shared::components::ModelRef": (asset_id: "prop", path: "models/prop.glb", scene_index: 0),
}),
},
)"#;
let migrated = migrate_v2_to_v3(body);
assert!(migrated.contains("\"shared::animation::SkinnedMeshRenderer\""));
assert!(migrated.contains("\"shared::components::ActorKind\": SkinnedMesh"));
assert_eq!(
migrated.matches("\"shared::components::ModelRef\"").count(),
1,
"generic scene instance must remain a ModelRef"
);
}
#[test]
fn backfills_actor_kind_for_audio_source_entity() {
let body = r#"(
+899
View File
@@ -0,0 +1,899 @@
use std::fs;
use std::path::{Path, PathBuf};
use nav_glam::{UVec3, Vec2, Vec3, Vec3A};
use polyanya::{Mesh, RecastFullMesh};
use rerecast::{
Aabb3d, AreaType, ConfigBuilder, ConvexVolume, DetailNavmesh, HeightfieldBuilder, TriMesh,
};
use serde::{Deserialize, Serialize};
use shared::{
BrushDesc, BrushKind, NavigationAgentProfile, NavigationArea, NavigationBounds, NavigationLink,
NavigationObstacle, Primitive, PrimitiveShape, COMPONENT_BRUSH_DESC, COMPONENT_NAVIGATION_AREA,
COMPONENT_NAVIGATION_BOUNDS, COMPONENT_NAVIGATION_LINK, COMPONENT_NAVIGATION_OBSTACLE,
COMPONENT_PRIMITIVE,
};
use crate::document::{SceneDocument, SceneEntity};
pub const NAVIGATION_ARTIFACT_SCHEMA_VERSION: u32 = 1;
pub const NAVIGATION_GENERATOR_ID: &str = "rerecast-0.3/polyanya-0.16";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NavigationVolumeInput {
pub actor_id: String,
pub center: [f32; 3],
pub half_extents: [f32; 3],
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NavigationAreaInput {
pub actor_id: String,
pub id: String,
pub center: [f32; 3],
pub half_extents: [f32; 3],
pub cost: f32,
pub walkable: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NavigationLinkInput {
pub actor_id: String,
pub start: [f32; 3],
pub end: [f32; 3],
pub bidirectional: bool,
pub cost: f32,
pub enabled: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NavigationGeometryInput {
pub actor_id: String,
pub triangles: Vec<[[f32; 3]; 3]>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NavigationBakeInput {
pub source_scene: String,
pub bounds_actor_id: String,
pub center: [f32; 3],
pub half_extents: [f32; 3],
pub agent: NavigationAgentProfile,
#[serde(default)]
pub geometry: Vec<NavigationGeometryInput>,
#[serde(default)]
pub obstacles: Vec<NavigationVolumeInput>,
#[serde(default)]
pub areas: Vec<NavigationAreaInput>,
#[serde(default)]
pub links: Vec<NavigationLinkInput>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct NavigationBakeJob {
pub artifact_path: String,
pub input: NavigationBakeInput,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NavigationBakeArtifact {
pub schema_version: u32,
pub generator: String,
pub source_scene: String,
pub source_fingerprint: String,
pub bounds_actor_id: String,
pub center: [f32; 3],
pub half_extents: [f32; 3],
pub agent: NavigationAgentProfile,
pub mesh: Mesh,
pub links: Vec<NavigationLinkInput>,
pub areas: Vec<NavigationAreaInput>,
}
impl NavigationBakeArtifact {
pub fn runtime_mesh(&self) -> Mesh {
let mut mesh = self.mesh.clone();
mesh.bake();
mesh
}
pub fn is_stale_for(&self, input: &NavigationBakeInput) -> bool {
self.schema_version != NAVIGATION_ARTIFACT_SCHEMA_VERSION
|| self.generator != NAVIGATION_GENERATOR_ID
|| self.source_fingerprint != navigation_source_fingerprint(input)
}
}
pub fn navigation_source_fingerprint(input: &NavigationBakeInput) -> String {
let bytes = ron::ser::to_string(input)
.expect("navigation bake input contains only serializable authoring data");
blake3::hash(bytes.as_bytes()).to_hex().to_string()
}
pub fn bake_navigation(input: &NavigationBakeInput) -> Result<NavigationBakeArtifact, String> {
validate_navigation_input(input)?;
let center = vec3(input.center);
let half_extents = vec3(input.half_extents);
let min = center - half_extents;
let max = center + half_extents;
let mut trimesh = floor_trimesh(min, max, center.y);
append_geometry(&mut trimesh, &input.geometry);
let config = ConfigBuilder {
cell_size_fraction: input.agent.cell_size_fraction,
cell_height_fraction: input.agent.cell_height_fraction,
agent_height: input.agent.height,
agent_radius: input.agent.radius,
walkable_climb: input.agent.max_climb,
walkable_slope_angle: input.agent.max_slope_deg.to_radians(),
min_region_size: input.agent.min_region_size,
merge_region_size: input.agent.merge_region_size,
aabb: Aabb3d { min, max },
..Default::default()
}
.build();
trimesh.mark_walkable_triangles(config.walkable_slope_angle);
let mut heightfield = HeightfieldBuilder {
aabb: config.aabb,
cell_size: config.cell_size,
cell_height: config.cell_height,
}
.build()
.map_err(|error| format!("failed to allocate navigation heightfield: {error}"))?;
heightfield
.rasterize_triangles(&trimesh, config.walkable_climb)
.map_err(|error| format!("failed to rasterize navigation geometry: {error}"))?;
heightfield.filter_low_hanging_walkable_obstacles(config.walkable_climb);
heightfield.filter_ledge_spans(config.walkable_height, config.walkable_climb);
heightfield.filter_walkable_low_height_spans(config.walkable_height);
let mut compact = heightfield
.into_compact(config.walkable_height, config.walkable_climb)
.map_err(|error| format!("failed to compact navigation heightfield: {error}"))?;
compact.erode_walkable_area(config.walkable_radius);
for obstacle in &input.obstacles {
compact.mark_convex_poly_area(&unwalkable_volume(obstacle.center, obstacle.half_extents));
}
for area in input.areas.iter().filter(|area| !area.walkable) {
compact.mark_convex_poly_area(&unwalkable_volume(area.center, area.half_extents));
}
compact.build_distance_field();
compact
.build_regions(
config.border_size,
config.min_region_area,
config.merge_region_area,
)
.map_err(|error| format!("failed to partition navigation regions: {error}"))?;
let contours = compact.build_contours(
config.max_simplification_error,
config.max_edge_len,
config.contour_flags,
);
let polygon = contours
.into_polygon_mesh(config.max_vertices_per_polygon)
.map_err(|error| format!("failed to build navigation polygons: {error}"))?;
if polygon.polygon_count() == 0 {
return Err(
"navigation bake produced no walkable polygons; enlarge bounds or repair obstacles"
.into(),
);
}
let detail = DetailNavmesh::new(
&polygon,
&compact,
config.detail_sample_dist,
config.detail_sample_max_error,
)
.map_err(|error| format!("failed to build navigation detail mesh: {error}"))?;
let mut mesh: Mesh = RecastFullMesh::new(polygon, detail).into();
mesh.unbake();
Ok(NavigationBakeArtifact {
schema_version: NAVIGATION_ARTIFACT_SCHEMA_VERSION,
generator: NAVIGATION_GENERATOR_ID.into(),
source_scene: input.source_scene.clone(),
source_fingerprint: navigation_source_fingerprint(input),
bounds_actor_id: input.bounds_actor_id.clone(),
center: input.center,
half_extents: input.half_extents,
agent: input.agent.clone(),
mesh,
links: input.links.clone(),
areas: input.areas.clone(),
})
}
pub fn write_navigation_artifact(
path: &Path,
artifact: &NavigationBakeArtifact,
) -> Result<(), String> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|error| {
format!("failed to create navigation artifact directory {parent:?}: {error}")
})?;
}
let text = ron::ser::to_string_pretty(artifact, ron::ser::PrettyConfig::default())
.map_err(|error| format!("failed to serialize navigation artifact: {error}"))?;
let temporary = temporary_path(path);
fs::write(&temporary, text)
.map_err(|error| format!("failed to write navigation artifact {temporary:?}: {error}"))?;
fs::rename(&temporary, path)
.map_err(|error| format!("failed to replace navigation artifact {path:?}: {error}"))
}
pub fn read_navigation_artifact(path: &Path) -> Result<NavigationBakeArtifact, String> {
let text = fs::read_to_string(path)
.map_err(|error| format!("failed to read navigation artifact {path:?}: {error}"))?;
let artifact: NavigationBakeArtifact = ron::from_str(&text)
.map_err(|error| format!("failed to parse navigation artifact {path:?}: {error}"))?;
if artifact.schema_version != NAVIGATION_ARTIFACT_SCHEMA_VERSION {
return Err(format!(
"navigation artifact schema {} is unsupported; rebake with schema {}",
artifact.schema_version, NAVIGATION_ARTIFACT_SCHEMA_VERSION
));
}
Ok(artifact)
}
pub fn navigation_bake_jobs_from_document(
document: &SceneDocument,
source_scene: &str,
) -> Result<Vec<NavigationBakeJob>, String> {
if !document.entities.iter().any(|entity| {
entity
.components
.iter()
.any(|component| component.type_name == COMPONENT_NAVIGATION_BOUNDS)
}) {
return Ok(Vec::new());
}
let poses = document_world_poses(document)?;
let mut obstacles = Vec::new();
let mut areas = Vec::new();
let mut links = Vec::new();
let mut bounds = Vec::new();
let mut geometry = Vec::new();
for entity in &document.entities {
let bounds_value = component::<NavigationBounds>(entity, COMPONENT_NAVIGATION_BOUNDS)?;
let obstacle_value =
component::<NavigationObstacle>(entity, COMPONENT_NAVIGATION_OBSTACLE)?;
let area_value = component::<NavigationArea>(entity, COMPONENT_NAVIGATION_AREA)?;
let link_value = component::<NavigationLink>(entity, COMPONENT_NAVIGATION_LINK)?;
let primitive = component::<Primitive>(entity, COMPONENT_PRIMITIVE)?;
let brush = component::<BrushDesc>(entity, COMPONENT_BRUSH_DESC)?;
if bounds_value.is_none()
&& obstacle_value.is_none()
&& area_value.is_none()
&& link_value.is_none()
&& primitive.is_none()
&& brush.is_none()
{
continue;
}
let actor_id = entity
.actor_id
.clone()
.ok_or_else(|| format!("navigation entity {} requires ActorId", entity.document_id))?;
let pose = poses
.get(&actor_id)
.copied()
.unwrap_or_else(WorldPose::identity);
if let Some(value) = bounds_value {
bounds.push((actor_id.clone(), pose, value));
}
if let Some(value) = obstacle_value {
obstacles.push(NavigationVolumeInput {
actor_id: actor_id.clone(),
center: pose.translation.to_array(),
half_extents: rotated_aabb_half_extents(pose, value.half_extents.to_array()),
});
}
if let Some(value) = area_value {
areas.push(NavigationAreaInput {
actor_id: actor_id.clone(),
id: value.id,
center: pose.translation.to_array(),
half_extents: rotated_aabb_half_extents(pose, value.half_extents.to_array()),
cost: value.cost,
walkable: value.walkable,
});
}
if let Some(value) = link_value {
links.push(NavigationLinkInput {
actor_id: actor_id.clone(),
start: pose.transform_point(value.start.to_array()).to_array(),
end: pose.transform_point(value.end.to_array()).to_array(),
bidirectional: value.bidirectional,
cost: value.cost,
enabled: value.enabled,
});
}
if let Some(value) = navigation_geometry_from_parts(
actor_id,
pose.translation.to_array(),
pose.rotation.to_array(),
pose.scale.to_array(),
primitive.as_ref(),
brush.as_ref(),
) {
geometry.push(value);
}
}
obstacles.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
areas.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
links.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
geometry.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
bounds.sort_by(|a, b| a.0.cmp(&b.0));
Ok(bounds
.into_iter()
.map(|(actor_id, pose, bounds)| {
let center = pose.translation.to_array();
let half_extents = rotated_aabb_half_extents(pose, bounds.half_extents.to_array());
NavigationBakeJob {
artifact_path: bounds.artifact_path,
input: NavigationBakeInput {
source_scene: source_scene.to_string(),
bounds_actor_id: actor_id,
center,
half_extents,
agent: bounds.agent,
geometry: geometry
.iter()
.filter(|value| geometry_overlaps_bounds(value, center, half_extents))
.cloned()
.collect(),
obstacles: obstacles
.iter()
.filter(|value| {
aabb_overlaps(center, half_extents, value.center, value.half_extents)
})
.cloned()
.collect(),
areas: areas
.iter()
.filter(|value| {
aabb_overlaps(center, half_extents, value.center, value.half_extents)
})
.cloned()
.collect(),
links: links
.iter()
.filter(|value| {
point_in_aabb(value.start, center, half_extents)
|| point_in_aabb(value.end, center, half_extents)
})
.cloned()
.collect(),
},
}
})
.collect())
}
fn validate_navigation_input(input: &NavigationBakeInput) -> Result<(), String> {
input
.agent
.validate()
.map_err(|error| format!("invalid navigation agent profile: {error}"))?;
if input.source_scene.trim().is_empty() {
return Err("navigation bake requires a source scene path".into());
}
if input.bounds_actor_id.trim().is_empty() {
return Err("navigation bounds actor requires a stable ActorId".into());
}
validate_half_extents(input.half_extents, "navigation bounds")?;
for geometry in &input.geometry {
if geometry.actor_id.trim().is_empty() {
return Err("navigation geometry requires a stable actor ID".into());
}
for triangle in &geometry.triangles {
if !triangle.iter().copied().all(finite3) {
return Err(format!(
"navigation geometry {} contains a non-finite triangle",
geometry.actor_id
));
}
}
}
for obstacle in &input.obstacles {
validate_half_extents(obstacle.half_extents, "navigation obstacle")?;
}
for area in &input.areas {
validate_half_extents(area.half_extents, "navigation area")?;
if area.id.trim().is_empty() {
return Err(format!("navigation area {} has an empty ID", area.actor_id));
}
if !area.cost.is_finite() || area.cost <= 0.0 {
return Err(format!(
"navigation area {} cost must be finite and greater than zero",
area.actor_id
));
}
}
for link in &input.links {
if link.enabled && (!finite3(link.start) || !finite3(link.end)) {
return Err(format!(
"navigation link {} endpoints must be finite",
link.actor_id
));
}
if link.enabled && squared_distance(link.start, link.end) <= f32::EPSILON {
return Err(format!(
"navigation link {} endpoints must be distinct",
link.actor_id
));
}
if !link.cost.is_finite() || link.cost <= 0.0 {
return Err(format!(
"navigation link {} cost must be finite and greater than zero",
link.actor_id
));
}
}
Ok(())
}
fn floor_trimesh(min: Vec3, max: Vec3, y: f32) -> TriMesh {
TriMesh {
vertices: vec![
Vec3A::new(min.x, y, min.z),
Vec3A::new(max.x, y, min.z),
Vec3A::new(max.x, y, max.z),
Vec3A::new(min.x, y, max.z),
],
indices: vec![UVec3::new(0, 2, 1), UVec3::new(0, 3, 2)],
area_types: vec![AreaType::DEFAULT_WALKABLE; 2],
}
}
fn append_geometry(trimesh: &mut TriMesh, geometry: &[NavigationGeometryInput]) {
for source in geometry {
for triangle in &source.triangles {
let base = trimesh.vertices.len() as u32;
trimesh
.vertices
.extend(triangle.iter().map(|vertex| Vec3A::from_array(*vertex)));
trimesh.indices.push(UVec3::new(base, base + 1, base + 2));
trimesh.area_types.push(AreaType::DEFAULT_WALKABLE);
}
}
}
pub fn navigation_geometry_from_parts(
actor_id: String,
translation: [f32; 3],
rotation: [f32; 4],
scale: [f32; 3],
primitive: Option<&Primitive>,
brush: Option<&BrushDesc>,
) -> Option<NavigationGeometryInput> {
let pose = WorldPose {
translation: Vec3::from_array(translation),
rotation: nav_glam::Quat::from_array(rotation).normalize(),
scale: Vec3::from_array(scale),
};
let local_triangles =
if let Some(brush) = brush.filter(|brush| brush.kind == BrushKind::Additive) {
brush_triangles(brush)
} else if let Some(primitive) = primitive {
primitive_triangles(primitive)
} else {
Vec::new()
};
(!local_triangles.is_empty()).then(|| NavigationGeometryInput {
actor_id,
triangles: local_triangles
.into_iter()
.map(|triangle| triangle.map(|point| pose.transform_point(point).to_array()))
.collect(),
})
}
fn brush_triangles(brush: &BrushDesc) -> Vec<[[f32; 3]; 3]> {
let mut triangles = Vec::new();
for face in &brush.faces {
let Some(first) = face.vertices.first() else {
continue;
};
for edge in face.vertices[1..].windows(2) {
triangles.push([first.to_array(), edge[0].to_array(), edge[1].to_array()]);
}
}
triangles
}
fn primitive_triangles(primitive: &Primitive) -> Vec<[[f32; 3]; 3]> {
let half = primitive.size.abs() * 0.5;
let vertices = match primitive.shape {
PrimitiveShape::Box => vec![
[-half.x, -half.y, -half.z],
[half.x, -half.y, -half.z],
[half.x, half.y, -half.z],
[-half.x, half.y, -half.z],
[-half.x, -half.y, half.z],
[half.x, -half.y, half.z],
[half.x, half.y, half.z],
[-half.x, half.y, half.z],
],
PrimitiveShape::Ramp => vec![
[-half.x, -half.y, -half.z],
[half.x, -half.y, -half.z],
[half.x, half.y, -half.z],
[-half.x, half.y, -half.z],
[-half.x, -half.y, half.z],
[half.x, -half.y, half.z],
],
PrimitiveShape::Sphere => vec![
[0.0, half.y, 0.0],
[half.x, 0.0, 0.0],
[0.0, 0.0, half.z],
[-half.x, 0.0, 0.0],
[0.0, 0.0, -half.z],
[0.0, -half.y, 0.0],
],
};
let indices: &[[usize; 3]] = match primitive.shape {
PrimitiveShape::Box => &[
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[3, 7, 6],
[3, 6, 2],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
],
PrimitiveShape::Ramp => &[
[0, 2, 1],
[0, 3, 2],
[0, 1, 5],
[0, 5, 4],
[0, 4, 3],
[1, 2, 5],
[3, 4, 5],
[3, 5, 2],
],
PrimitiveShape::Sphere => &[
[0, 2, 1],
[0, 3, 2],
[0, 4, 3],
[0, 1, 4],
[5, 1, 2],
[5, 2, 3],
[5, 3, 4],
[5, 4, 1],
],
};
indices
.iter()
.map(|[a, b, c]| [vertices[*a], vertices[*b], vertices[*c]])
.collect()
}
pub fn aabb_overlaps(
a_center: [f32; 3],
a_half: [f32; 3],
b_center: [f32; 3],
b_half: [f32; 3],
) -> bool {
(0..3).all(|axis| (a_center[axis] - b_center[axis]).abs() <= a_half[axis] + b_half[axis])
}
pub fn point_in_aabb(point: [f32; 3], center: [f32; 3], half_extents: [f32; 3]) -> bool {
(0..3).all(|axis| (point[axis] - center[axis]).abs() <= half_extents[axis])
}
pub fn geometry_overlaps_bounds(
geometry: &NavigationGeometryInput,
center: [f32; 3],
half_extents: [f32; 3],
) -> bool {
geometry.triangles.iter().any(|triangle| {
let mut min = triangle[0];
let mut max = triangle[0];
for vertex in &triangle[1..] {
for axis in 0..3 {
min[axis] = min[axis].min(vertex[axis]);
max[axis] = max[axis].max(vertex[axis]);
}
}
let geometry_center = std::array::from_fn(|axis| (min[axis] + max[axis]) * 0.5);
let geometry_half = std::array::from_fn(|axis| (max[axis] - min[axis]) * 0.5);
aabb_overlaps(center, half_extents, geometry_center, geometry_half)
})
}
fn unwalkable_volume(center: [f32; 3], half_extents: [f32; 3]) -> ConvexVolume {
let center = vec3(center);
let half = vec3(half_extents);
ConvexVolume {
vertices: vec![
Vec2::new(center.x - half.x, center.z - half.z),
Vec2::new(center.x + half.x, center.z - half.z),
Vec2::new(center.x + half.x, center.z + half.z),
Vec2::new(center.x - half.x, center.z + half.z),
],
min_y: center.y - half.y,
max_y: center.y + half.y,
area: AreaType::NOT_WALKABLE,
}
}
fn vec3(value: [f32; 3]) -> Vec3 {
Vec3::from_array(value)
}
fn finite3(value: [f32; 3]) -> bool {
value.into_iter().all(f32::is_finite)
}
fn validate_half_extents(value: [f32; 3], label: &str) -> Result<(), String> {
if !finite3(value) || value.into_iter().any(|axis| axis <= 0.0) {
return Err(format!(
"{label} half extents must be finite and greater than zero"
));
}
Ok(())
}
fn squared_distance(a: [f32; 3], b: [f32; 3]) -> f32 {
a.into_iter().zip(b).map(|(a, b)| (a - b) * (a - b)).sum()
}
fn temporary_path(path: &Path) -> PathBuf {
let mut temporary = path.as_os_str().to_os_string();
temporary.push(".tmp");
PathBuf::from(temporary)
}
const TRANSFORM_COMPONENT: &str = "bevy_transform::components::transform::Transform";
#[derive(Debug, Clone, Copy, Deserialize)]
struct SerializedTransform {
translation: [f32; 3],
rotation: [f32; 4],
scale: [f32; 3],
}
impl Default for SerializedTransform {
fn default() -> Self {
Self {
translation: [0.0; 3],
rotation: [0.0, 0.0, 0.0, 1.0],
scale: [1.0; 3],
}
}
}
#[derive(Debug, Clone, Copy)]
struct WorldPose {
translation: Vec3,
rotation: nav_glam::Quat,
scale: Vec3,
}
impl WorldPose {
fn identity() -> Self {
Self {
translation: Vec3::ZERO,
rotation: nav_glam::Quat::IDENTITY,
scale: Vec3::ONE,
}
}
fn from_serialized(value: SerializedTransform) -> Self {
Self {
translation: Vec3::from_array(value.translation),
rotation: nav_glam::Quat::from_array(value.rotation).normalize(),
scale: Vec3::from_array(value.scale),
}
}
fn compose(self, local: Self) -> Self {
Self {
translation: self.translation + self.rotation * (self.scale * local.translation),
rotation: (self.rotation * local.rotation).normalize(),
scale: self.scale * local.scale,
}
}
fn transform_point(self, point: [f32; 3]) -> Vec3 {
self.translation + self.rotation * (self.scale * Vec3::from_array(point))
}
}
fn document_world_poses(
document: &SceneDocument,
) -> Result<std::collections::BTreeMap<String, WorldPose>, String> {
let entities: std::collections::BTreeMap<&str, &SceneEntity> = document
.entities
.iter()
.filter_map(|entity| Some((entity.actor_id.as_deref()?, entity)))
.collect();
let mut poses = std::collections::BTreeMap::new();
let mut visiting = std::collections::BTreeSet::new();
for actor_id in entities.keys().copied() {
resolve_document_pose(actor_id, &entities, &mut poses, &mut visiting)?;
}
Ok(poses)
}
fn resolve_document_pose(
actor_id: &str,
entities: &std::collections::BTreeMap<&str, &SceneEntity>,
poses: &mut std::collections::BTreeMap<String, WorldPose>,
visiting: &mut std::collections::BTreeSet<String>,
) -> Result<WorldPose, String> {
if let Some(pose) = poses.get(actor_id).copied() {
return Ok(pose);
}
if !visiting.insert(actor_id.to_string()) {
return Err(format!(
"navigation hierarchy contains a cycle at actor {actor_id}"
));
}
let entity = entities
.get(actor_id)
.ok_or_else(|| format!("navigation actor {actor_id} is missing from the scene document"))?;
let local = component::<SerializedTransform>(entity, TRANSFORM_COMPONENT)?
.map(WorldPose::from_serialized)
.unwrap_or_else(WorldPose::identity);
let world = match entity.parent_actor_id.as_deref() {
Some(parent) => resolve_document_pose(parent, entities, poses, visiting)?.compose(local),
None => local,
};
visiting.remove(actor_id);
poses.insert(actor_id.to_string(), world);
Ok(world)
}
fn component<T: for<'de> Deserialize<'de>>(
entity: &SceneEntity,
type_name: &str,
) -> Result<Option<T>, String> {
entity
.components
.iter()
.find(|component| component.type_name == type_name)
.map(|component| {
ron::from_str(&component.ron).map_err(|error| {
format!(
"actor {} has invalid {type_name}: {error}",
entity.document_id
)
})
})
.transpose()
}
fn rotated_aabb_half_extents(pose: WorldPose, local_half: [f32; 3]) -> [f32; 3] {
let half = pose.scale.abs() * Vec3::from_array(local_half);
let x = pose.rotation * Vec3::X;
let y = pose.rotation * Vec3::Y;
let z = pose.rotation * Vec3::Z;
(x.abs() * half.x + y.abs() * half.y + z.abs() * half.z).to_array()
}
#[cfg(test)]
mod tests {
use nav_glam::Vec2;
use super::*;
fn fixture() -> NavigationBakeInput {
NavigationBakeInput {
source_scene: "assets/levels/navigation_showcase.scn.ron".into(),
bounds_actor_id: "bounds".into(),
center: [0.0, 0.0, 0.0],
half_extents: [5.0, 2.0, 5.0],
agent: NavigationAgentProfile {
min_region_size: 1,
merge_region_size: 2,
..Default::default()
},
geometry: Vec::new(),
obstacles: vec![NavigationVolumeInput {
actor_id: "center-obstacle".into(),
center: [0.0, 0.5, 0.0],
half_extents: [0.75, 1.0, 0.75],
}],
areas: Vec::new(),
links: Vec::new(),
}
}
#[test]
fn deterministic_bake_routes_around_an_obstacle() {
let input = fixture();
let artifact = bake_navigation(&input).unwrap();
assert_eq!(
artifact.source_fingerprint,
navigation_source_fingerprint(&input)
);
let mesh = artifact.runtime_mesh();
let path = mesh.path(Vec2::new(-3.0, 0.0), Vec2::new(3.0, 0.0));
assert!(path.is_some());
assert!(path.unwrap().length > 6.0);
}
#[test]
fn artifact_round_trip_preserves_query_mesh() {
let artifact = bake_navigation(&fixture()).unwrap();
let text = ron::ser::to_string(&artifact).unwrap();
let restored: NavigationBakeArtifact = ron::from_str(&text).unwrap();
assert!(restored
.runtime_mesh()
.path(Vec2::new(-3.0, -3.0), Vec2::new(3.0, 3.0))
.is_some());
}
#[test]
fn agent_change_marks_artifact_stale() {
let input = fixture();
let artifact = bake_navigation(&input).unwrap();
let mut changed = input;
changed.agent.radius += 0.1;
assert!(artifact.is_stale_for(&changed));
}
#[test]
fn authored_geometry_change_marks_artifact_stale() {
let mut input = fixture();
input.geometry.push(NavigationGeometryInput {
actor_id: "walkable-floor".into(),
triangles: vec![[[-2.0, 0.0, -2.0], [2.0, 0.0, 2.0], [2.0, 0.0, -2.0]]],
});
let artifact = bake_navigation(&input).unwrap();
input.geometry[0].triangles[0][0][0] -= 0.25;
assert!(artifact.is_stale_for(&input));
}
#[test]
fn bounds_filter_excludes_distant_authoring() {
assert!(aabb_overlaps(
[0.0, 0.0, 0.0],
[2.0, 2.0, 2.0],
[3.0, 0.0, 0.0],
[1.0, 1.0, 1.0]
));
assert!(!aabb_overlaps(
[0.0, 0.0, 0.0],
[2.0, 2.0, 2.0],
[3.01, 0.0, 0.0],
[1.0, 1.0, 1.0]
));
}
#[test]
fn committed_navigation_fixture_matches_its_bake_artifact() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let scene_path = root.join("assets/levels/navigation_authoring_showcase.scn.ron");
let text = std::fs::read_to_string(scene_path).unwrap();
let document = SceneDocument::from_ron_text(&text).unwrap();
let job = navigation_bake_jobs_from_document(
&document,
"assets/levels/navigation_authoring_showcase.scn.ron",
)
.unwrap()
.pop()
.unwrap();
let committed = read_navigation_artifact(&root.join(&job.artifact_path)).unwrap();
assert!(!committed.is_stale_for(&job.input));
assert_eq!(committed.bounds_actor_id, "navigation-bounds-main");
assert_eq!(job.input.geometry.len(), 1);
assert_eq!(job.input.geometry[0].actor_id, "navigation-floor-geometry");
assert!(committed
.runtime_mesh()
.path(Vec2::new(-6.0, 0.0), Vec2::new(6.0, 0.0))
.is_some());
}
}
+639 -64
View File
@@ -11,10 +11,10 @@ use shared::{
brush_math::{validate_brush, BrushDiagnosticSeverity},
AnimationControllerDesc, AnimationDiagnosticSeverity, AnimationManifest, AudioListenerDesc,
AudioSourceDesc, BrushDesc, ColliderDesc, ColliderShapeDesc, EditorAssetRef, MaterialAsset,
MaterialDesc, MaterialOverride, ModelRef, PostProcessEffectAsset, PostProcessVolumeDesc,
PrefabInstance, PrefabRef, ShaderSchemaAsset, StaticMeshRenderer,
ANIMATION_MANIFEST_SCHEMA_VERSION, AUDIO_CLIP_SUB_ASSET_ID,
COMPONENT_ANIMATION_CONTROLLER_DESC,
MaterialDesc, MaterialInstanceAsset, MaterialOverride, ModelRef, PostProcessEffectAsset,
PostProcessVolumeDesc, PrefabInstance, PrefabRef, RendererMaterialSet, ShaderSchemaAsset,
SkinnedMeshRenderer, StaticMeshRenderer, ANIMATION_MANIFEST_SCHEMA_VERSION,
AUDIO_CLIP_SUB_ASSET_ID, COMPONENT_ANIMATION_CONTROLLER_DESC, COMPONENT_SKINNED_MESH_RENDERER,
};
use crate::document::{SceneComponentBlob, SceneDocument};
@@ -308,6 +308,8 @@ struct RegistryImportSettings {
static_mesh_manifest_path: Option<String>,
#[serde(default)]
animation_manifest_path: Option<String>,
#[serde(default)]
default_animation_clip_id: Option<String>,
}
#[derive(Deserialize)]
@@ -325,6 +327,7 @@ struct RegistryAssetRecord {
struct AnimationRegistryRecord {
source_path: String,
manifest_path: Option<String>,
default_animation_clip_id: Option<String>,
}
#[derive(Debug, Clone)]
@@ -438,6 +441,10 @@ fn validate_asset_registry(
.or_insert(AnimationRegistryRecord {
source_path: record.path.clone(),
manifest_path: record.import_settings.animation_manifest_path.clone(),
default_animation_clip_id: record
.import_settings
.default_animation_clip_id
.clone(),
});
}
if record.kind_tag == "Model"
@@ -499,21 +506,103 @@ fn validate_material_assets(project_root: &Path, report: &mut ProjectValidationR
report,
) {
let source = display_project_path(project_root, &path);
let Some(asset) = parse_document::<MaterialAsset>(&path, &source, "material", report)
else {
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
if let Some(shader) = asset.shader {
add_reference(
if let Ok(asset) = ron::from_str::<MaterialAsset>(&text) {
if asset.schema_version != shared::MATERIAL_ASSET_SCHEMA_VERSION {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "material.incompatible_schema".into(),
source_path: source.clone(),
owner_actor_id: None,
reference: Some(asset.schema_version.to_string()),
message: "material asset schema is not supported by this build".into(),
repair: "Run `cargo upgrade-project --apply` and review the upgrade report."
.into(),
});
}
if let Some(shader) = asset.shader {
add_reference(
project_root,
report,
&source,
None,
"shader_schema",
&shader,
);
}
if let Some(shader) = asset.shader_ref {
collect_asset_ref(
project_root,
report,
&source,
None,
"shader_schema",
&shader,
);
}
collect_material(project_root, report, &source, None, &asset.material);
continue;
}
if let Ok(instance) = ron::from_str::<MaterialInstanceAsset>(&text) {
if instance.schema_version != shared::MATERIAL_INSTANCE_SCHEMA_VERSION {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "material_instance.incompatible_schema".into(),
source_path: source.clone(),
owner_actor_id: None,
reference: Some(instance.schema_version.to_string()),
message: "material-instance schema is not supported by this build".into(),
repair: "Run `cargo upgrade-project --apply` and review the upgrade report."
.into(),
});
}
let nested_base = instance.base.0.sub_asset_id == "material:instance"
|| instance.base.0.source_path.as_deref().is_some_and(|path| {
let path = Path::new(path);
let path = if path.is_absolute() {
path.to_path_buf()
} else {
project_root.join(path)
};
MaterialInstanceAsset::load_from_path(&path.to_string_lossy()).is_ok()
});
if nested_base {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "material_instance.nested_base".into(),
source_path: source.clone(),
owner_actor_id: None,
reference: Some(instance.base.0.label.clone()),
message: "material instances must directly inherit a Material asset".into(),
repair: "Choose a Material asset as the instance base.".into(),
});
}
collect_asset_ref(
project_root,
report,
&source,
None,
"shader_schema",
&shader,
"material",
&instance.base.0,
);
for texture in instance.textures {
if let Some(reference) = texture.texture {
collect_asset_ref(project_root, report, &source, None, "texture", &reference);
}
}
continue;
}
collect_material(project_root, report, &source, None, &asset.material);
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "material.invalid".into(),
source_path: source,
owner_actor_id: None,
reference: None,
message: "could not parse file as a Material or Material Instance asset".into(),
repair: "Repair the document or restore it from the project-upgrade backup.".into(),
});
}
}
@@ -530,8 +619,53 @@ fn validate_shader_assets(project_root: &Path, report: &mut ProjectValidationRep
else {
continue;
};
if asset.schema_version != shared::SURFACE_SHADER_SCHEMA_VERSION {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "surface_shader.incompatible_schema".into(),
source_path: source.clone(),
owner_actor_id: None,
reference: Some(asset.schema_version.to_string()),
message: "surface shader schema is not supported by this build".into(),
repair: "Run `cargo upgrade-project --apply` and review the upgrade report.".into(),
});
}
if let Some(wgsl) = asset.wgsl_path {
add_reference(project_root, report, &source, None, "shader", &wgsl);
if let Ok(code) = std::fs::read_to_string(project_root.join(&wgsl)) {
if !code.contains("fn evaluate(")
|| [
"@group",
"@binding",
"@vertex",
"@fragment",
"@compute",
"var<",
"rayQuery",
"dpdx",
"dpdy",
"fwidth",
"discard",
"Barrier",
"subgroup",
"textureStore",
"atomic",
]
.iter()
.any(|forbidden| code.contains(forbidden))
{
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "surface_shader.invalid_contract".into(),
source_path: source.clone(),
owner_actor_id: None,
reference: Some(wgsl.clone()),
message: "WGSL does not satisfy the Surface ABI evaluator contract".into(),
repair: "Define only `fn evaluate(...) -> Surface` and remove resource bindings/entry points."
.into(),
});
}
}
}
for texture in asset.default_textures {
if let Some(reference) = texture.texture {
@@ -574,6 +708,8 @@ struct StaticMeshSourceView {
dependencies: Vec<String>,
}
const STATIC_MESH_MANIFEST_SCHEMA_VERSION: u32 = 3;
fn validate_static_mesh_manifests(project_root: &Path, report: &mut ProjectValidationReport) {
for path in ron_files(
project_root,
@@ -590,7 +726,9 @@ fn validate_static_mesh_manifests(project_root: &Path, report: &mut ProjectValid
) else {
continue;
};
if manifest.schema_version != 1 || manifest.asset_id.trim().is_empty() {
if manifest.schema_version != STATIC_MESH_MANIFEST_SCHEMA_VERSION
|| manifest.asset_id.trim().is_empty()
{
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "manifest.incompatible_schema".into(),
@@ -732,6 +870,17 @@ fn validate_animation_manifests(
repair: "Reimport the model so its UUID-keyed animation manifest matches the asset registry.".into(),
});
}
if manifest.default_animation_clip_id != record.default_animation_clip_id {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "animation.default_clip_manifest_mismatch".into(),
source_path: normalized.clone(),
owner_actor_id: None,
reference: record.default_animation_clip_id.clone(),
message: "model import settings and generated animation manifest disagree on the default clip".into(),
repair: "Reimport the model so its generated manifest records the current Default animation setting.".into(),
});
}
if manifest.source.path != record.source_path {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
@@ -1001,6 +1150,26 @@ fn validate_animation_manifest_contract(
}
}
if let Some(default_clip_id) = manifest.default_animation_clip_id.as_deref() {
if (default_clip_id.trim().is_empty() || !clip_ids.contains(default_clip_id))
&& !manifest
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == "animation.default_clip_missing")
{
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "animation.default_clip_missing".into(),
source_path: source_path.into(),
owner_actor_id: None,
reference: Some(default_clip_id.to_string()),
message: "animation manifest default clip does not resolve to an imported clip"
.into(),
repair: "Choose an existing Default animation in Model Import Settings, or select Imported rest pose, then reimport.".into(),
});
}
}
match source_format.as_str() {
"gltf" | "glb" if !manifest.runtime_supported => {
report.findings.push(ProjectValidationFinding {
@@ -1219,6 +1388,8 @@ fn validate_document(
return;
};
validate_navigation_document(project_root, &source_path, &document, report);
if let Some(composition) = &document.composition {
for subscene in &composition.subscenes {
add_reference(
@@ -1279,6 +1450,131 @@ fn validate_document(
}
}
fn validate_navigation_document(
project_root: &Path,
source_path: &str,
document: &SceneDocument,
report: &mut ProjectValidationReport,
) {
let jobs = match crate::navigation::navigation_bake_jobs_from_document(document, source_path) {
Ok(jobs) => jobs,
Err(error) => {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "navigation.authoring_invalid".into(),
source_path: source_path.to_string(),
owner_actor_id: None,
reference: None,
message: error,
repair: "Repair the named navigation actor and rebake the scene.".into(),
});
return;
}
};
for job in jobs {
report.dependencies.push(ProjectDependency {
owner_path: source_path.to_string(),
owner_actor_id: Some(job.input.bounds_actor_id.clone()),
kind: "navigation_artifact".into(),
reference: job.artifact_path.clone(),
});
let Some(path) = resolve_reference(project_root, &job.artifact_path) else {
push_navigation_finding(
report,
source_path,
&job.input.bounds_actor_id,
"navigation.artifact_unsafe_path",
&job.artifact_path,
"navigation artifact path escapes the project",
"Choose an artifact path under assets/navigation/generated/.",
);
continue;
};
if !path.is_file() {
push_navigation_finding(
report,
source_path,
&job.input.bounds_actor_id,
"navigation.artifact_missing",
&job.artifact_path,
"navigation bounds has no baked artifact",
"Select the bounds actor and run Scene > Navigation > Bake Selected Bounds.",
);
continue;
}
let artifact = match crate::navigation::read_navigation_artifact(&path) {
Ok(artifact) => artifact,
Err(error) => {
push_navigation_finding(
report,
source_path,
&job.input.bounds_actor_id,
"navigation.artifact_invalid",
&job.artifact_path,
&error,
"Delete the invalid generated artifact and rebake the bounds actor.",
);
continue;
}
};
if artifact.is_stale_for(&job.input) {
push_navigation_finding(
report,
source_path,
&job.input.bounds_actor_id,
"navigation.artifact_stale",
&job.artifact_path,
"navigation artifact fingerprint does not match authored navigation data",
"Rebake navigation after the authored geometry or agent-profile change.",
);
}
let mesh = artifact.runtime_mesh();
for link in artifact.links.iter().filter(|link| link.enabled) {
for (label, endpoint) in [("start", link.start), ("end", link.end)] {
let point = nav_glam::Vec2::new(endpoint[0], endpoint[2]);
let valid = mesh.get_closest_point(point).is_some_and(|closest| {
closest.position().distance(point) <= artifact.agent.radius * 2.0
});
if !valid {
push_navigation_finding(
report,
source_path,
&link.actor_id,
"navigation.link_unreachable",
&job.artifact_path,
&format!(
"navigation link {label} endpoint is farther than two agent radii from the baked mesh"
),
"Move the endpoint onto a visible navigation polygon and rebake.",
);
}
}
}
}
}
fn push_navigation_finding(
report: &mut ProjectValidationReport,
source_path: &str,
actor_id: &str,
code: &str,
reference: &str,
message: &str,
repair: &str,
) {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: code.into(),
source_path: source_path.into(),
owner_actor_id: Some(actor_id.into()),
reference: Some(reference.into()),
message: message.into(),
repair: repair.into(),
});
}
fn collect_component_references(
project_root: &Path,
report: &mut ProjectValidationReport,
@@ -1321,51 +1617,36 @@ fn collect_component_references(
}
MODEL_REF => {
let model = parse!(ModelRef);
if model.asset_id.trim().is_empty() {
add_reference(
project_root,
report,
source_path,
actor_id,
"model",
&model.path,
);
} else if let Some(record) = animation_catalog.registry_by_id.get(&model.asset_id) {
add_reference(
project_root,
report,
source_path,
actor_id,
"model",
&record.source_path,
);
if normalized_project_reference(&model.path)
!= normalized_project_reference(&record.source_path)
{
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Warning,
code: "model.cached_path_stale".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: Some(model.asset_id),
message: format!(
"ModelRef cached path `{}` differs from registered path `{}`",
model.path, record.source_path
),
repair: "Open and save the scene to refresh the cached path hint; runtime resolution already uses the stable asset ID.".into(),
});
}
} else {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "model.asset_unresolved".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: Some(model.asset_id),
message: "ModelRef asset ID is absent from the project registry".into(),
repair: "Restore/reimport the owning model or reassign the model reference in the editor.".into(),
});
}
collect_model_source_reference(
project_root,
report,
source_path,
actor_id,
&model.asset_id,
&model.path,
"ModelRef",
animation_catalog,
);
}
COMPONENT_SKINNED_MESH_RENDERER => {
let renderer = parse!(SkinnedMeshRenderer);
collect_model_source_reference(
project_root,
report,
source_path,
actor_id,
&renderer.asset_id,
&renderer.path,
"SkinnedMeshRenderer",
animation_catalog,
);
collect_renderer_material_references(
project_root,
report,
source_path,
actor_id,
&renderer.materials,
);
}
MATERIAL_DESC => collect_material(
project_root,
@@ -1390,7 +1671,33 @@ fn collect_component_references(
}
}
STATIC_MESH_RENDERER => {
for slot in parse!(StaticMeshRenderer).slots {
let renderer = parse!(StaticMeshRenderer);
collect_renderer_material_references(
project_root,
report,
source_path,
actor_id,
&renderer.materials,
);
if let Some(slot) = renderer.slots.iter().find(|slot| {
animation_asset_requires_skinned_renderer(&slot.mesh.asset_id, animation_catalog)
}) {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "static_mesh.hierarchy_bound_geometry".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: Some(format!(
"{}#{}",
slot.mesh.asset_id, slot.mesh.sub_asset_id
)),
message:
"StaticMeshRenderer references geometry from a skinned or animated model"
.into(),
repair: "Replace this actor by placing the source model through SkinnedMeshRenderer; static slots cannot retain its imported hierarchy.".into(),
});
}
for slot in renderer.slots {
collect_asset_ref(
project_root,
report,
@@ -1510,6 +1817,119 @@ fn collect_component_references(
}
}
fn collect_renderer_material_references(
project_root: &Path,
report: &mut ProjectValidationReport,
source_path: &str,
actor_id: Option<&str>,
materials: &RendererMaterialSet,
) {
for slot in &materials.slots {
for reference in [slot.source_material.as_ref(), slot.material.as_ref()]
.into_iter()
.flatten()
{
collect_asset_ref(
project_root,
report,
source_path,
actor_id,
"material",
&reference.0,
);
}
}
for orphan in &materials.orphaned_assignments {
collect_asset_ref(
project_root,
report,
source_path,
actor_id,
"material",
&orphan.material.0,
);
}
}
fn animation_asset_requires_skinned_renderer(
asset_id: &str,
catalog: &AnimationValidationCatalog,
) -> bool {
let Some(record) = catalog.registry_by_id.get(asset_id) else {
return false;
};
let Some(manifest_path) = record.manifest_path.as_deref() else {
return false;
};
matches!(
catalog
.manifests_by_path
.get(&normalized_project_reference(manifest_path)),
Some(AnimationManifestLoad::Valid(manifest))
if !manifest.skeletons.is_empty() || !manifest.clips.is_empty()
)
}
#[allow(clippy::too_many_arguments)]
fn collect_model_source_reference(
project_root: &Path,
report: &mut ProjectValidationReport,
source_path: &str,
actor_id: Option<&str>,
asset_id: &str,
cached_path: &str,
component_name: &str,
animation_catalog: &AnimationValidationCatalog,
) {
if asset_id.trim().is_empty() {
add_reference(
project_root,
report,
source_path,
actor_id,
"model",
cached_path,
);
} else if let Some(record) = animation_catalog.registry_by_id.get(asset_id) {
add_reference(
project_root,
report,
source_path,
actor_id,
"model",
&record.source_path,
);
if normalized_project_reference(cached_path)
!= normalized_project_reference(&record.source_path)
{
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Warning,
code: "model.cached_path_stale".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: Some(asset_id.to_string()),
message: format!(
"{component_name} cached path `{cached_path}` differs from registered path `{}`",
record.source_path
),
repair: "Open and save the scene to refresh the cached path hint; runtime resolution already uses the stable asset ID.".into(),
});
}
} else {
report.findings.push(ProjectValidationFinding {
severity: ValidationSeverity::Error,
code: "model.asset_unresolved".into(),
source_path: source_path.to_string(),
owner_actor_id: actor_id.map(str::to_string),
reference: Some(asset_id.to_string()),
message: format!("{component_name} asset ID is absent from the project registry"),
repair:
"Restore/reimport the owning model or reassign the model reference in the editor."
.into(),
});
}
}
fn validate_animation_controller(
project_root: &Path,
report: &mut ProjectValidationReport,
@@ -2396,6 +2816,31 @@ mod tests {
root
}
#[test]
fn static_mesh_manifest_schema_v3_is_current() {
let root = fixture_root();
let source_path = "assets/models/static.glb";
std::fs::create_dir_all(root.join("assets/models")).unwrap();
std::fs::write(root.join(source_path), b"model").unwrap();
let artifact_dir = root.join("assets/meshes/generated");
std::fs::create_dir_all(&artifact_dir).unwrap();
std::fs::write(
artifact_dir.join("static-id.static_mesh.ron"),
format!(
"(schema_version:{STATIC_MESH_MANIFEST_SCHEMA_VERSION},asset_id:\"static-id\",source:(path:\"{source_path}\",dependencies:[]),warnings:[])"
),
)
.unwrap();
let report = validate_project(&root);
assert!(!report.findings.iter().any(|finding| {
finding.code == "manifest.incompatible_schema"
&& finding.source_path.ends_with("static-id.static_mesh.ron")
}));
std::fs::remove_dir_all(root).unwrap();
}
fn write_manifest(root: &Path, version: u32) {
std::fs::write(
root.join("assets/project.ron"),
@@ -2423,6 +2868,7 @@ mod tests {
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: ANIMATION_ASSET_ID.into(),
label: "Hero".into(),
default_animation_clip_id: None,
source: AnimationManifestSource {
path: source_path.into(),
format: source_format.into(),
@@ -2497,6 +2943,23 @@ mod tests {
.unwrap();
}
fn write_animation_source_and_registry_default(
root: &Path,
source_path: &str,
default_clip_id: &str,
) {
let source = root.join(source_path);
std::fs::create_dir_all(source.parent().unwrap()).unwrap();
std::fs::write(source, b"model").unwrap();
std::fs::write(
root.join("assets/.index/registry.ron"),
format!(
"[(id:(\"{ANIMATION_ASSET_ID}\"),path:\"{source_path}\",kind_tag:\"Model\",import_settings:(static_mesh_manifest_path:None,animation_manifest_path:Some(\"{ANIMATION_MANIFEST_PATH}\"),default_animation_clip_id:Some(\"{default_clip_id}\")),dependencies:[])]"
),
)
.unwrap();
}
fn write_animation_manifest(root: &Path, manifest: &AnimationManifest) {
let path = root.join(ANIMATION_MANIFEST_PATH);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
@@ -2539,6 +3002,61 @@ mod tests {
std::fs::remove_dir_all(root).unwrap();
}
fn write_navigation_scene(root: &Path, radius: f32, write_artifact: bool) {
let mut bounds = shared::NavigationBounds::default();
bounds.agent.radius = radius;
bounds.agent.min_region_size = 1;
bounds.agent.merge_region_size = 2;
bounds.artifact_path = "assets/navigation/generated/main_humanoid.nav.ron".to_string();
let bounds_ron = ron::to_string(&bounds).unwrap();
let scene = format!(
"(schema_version:2,resources:{{}},entities:{{1:(components:{{\"shared::components::ActorId\":(\"nav-bounds\"),\"shared::navigation::NavigationBounds\":{bounds_ron},}})}})"
);
std::fs::write(root.join("assets/levels/main.scn.ron"), &scene).unwrap();
if write_artifact {
let document = SceneDocument::from_ron_text(&scene).unwrap();
let job = crate::navigation::navigation_bake_jobs_from_document(
&document,
"assets/levels/main.scn.ron",
)
.unwrap()
.pop()
.unwrap();
let artifact = crate::navigation::bake_navigation(&job.input).unwrap();
crate::navigation::write_navigation_artifact(&root.join(&job.artifact_path), &artifact)
.unwrap();
}
}
#[test]
fn missing_navigation_artifact_blocks_release_with_bounds_owner() {
let root = fixture_root();
write_navigation_scene(&root, 0.35, false);
let report = validate_project(&root);
let finding = report
.findings
.iter()
.find(|finding| finding.code == "navigation.artifact_missing")
.expect("missing artifact should be reported");
assert_eq!(finding.owner_actor_id.as_deref(), Some("nav-bounds"));
assert!(finding.repair.contains("Bake Selected Bounds"));
}
#[test]
fn navigation_agent_change_marks_bake_stale() {
let root = fixture_root();
write_navigation_scene(&root, 0.35, true);
assert!(validate_project(&root).is_release_ready());
write_navigation_scene(&root, 0.5, false);
let report = validate_project(&root);
assert!(report
.findings
.iter()
.any(|finding| finding.code == "navigation.artifact_stale"));
}
#[test]
fn valid_animation_controller_collects_stable_artifact_dependencies() {
let root = fixture_root();
@@ -2565,6 +3083,39 @@ mod tests {
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn static_renderer_cannot_reference_skinned_or_animated_model_geometry() {
let root = fixture_root();
let source_path = "assets/models/hero.glb";
let manifest = animation_fixture_manifest(source_path, "glb", "rig-signature", true);
write_animation_source_and_registry(&root, source_path, Some(ANIMATION_MANIFEST_PATH));
write_animation_manifest(&root, &manifest);
let renderer = StaticMeshRenderer::single(shared::StaticMeshRendererEntry {
mesh: EditorAssetRef::new(ANIMATION_ASSET_ID, "mesh:hero", "Hero"),
..Default::default()
});
let renderer = ron::to_string(&renderer).unwrap();
std::fs::write(
root.join("assets/levels/main.scn.ron"),
format!(
"(schema_version:3,resources:{{}},entities:{{1:(components:{{\"shared::components::ActorId\":(\"static-hero\"),\"shared::components::StaticMeshRenderer\":{renderer},}})}})"
),
)
.unwrap();
let report = validate_project(&root);
let finding = report
.findings
.iter()
.find(|finding| finding.code == "static_mesh.hierarchy_bound_geometry")
.expect("static use of hierarchy-bound geometry should be blocking");
assert_eq!(finding.owner_actor_id.as_deref(), Some("static-hero"));
assert_eq!(finding.severity, ValidationSeverity::Error);
assert!(finding.repair.contains("SkinnedMeshRenderer"));
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn same_size_animation_source_change_invalidates_manifest_content_hash() {
let root = fixture_root();
@@ -2669,13 +3220,37 @@ mod tests {
&& finding.owner_actor_id.as_deref() == Some("animated-actor")
})
.expect("missing clip must identify the owning actor state");
assert!(finding.reference.as_deref().is_some_and(
|reference| reference.contains("AnimationControllerDesc.states[idle].clip")
));
assert!(finding.reference.as_deref().is_some_and(|reference| {
reference.contains("AnimationControllerDesc.states[idle].clip")
}));
assert!(!finding.repair.trim().is_empty());
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn missing_import_default_clip_blocks_the_generated_manifest() {
let root = fixture_root();
let source_path = "assets/models/hero.glb";
let missing = animation_clip_sub_asset_id(9, "Removed");
let mut manifest = animation_fixture_manifest(source_path, "glb", "rig-signature", true);
manifest.default_animation_clip_id = Some(missing.clone());
write_animation_source_and_registry_default(&root, source_path, &missing);
write_animation_manifest(&root, &manifest);
let report = validate_project(&root);
let finding = report
.findings
.iter()
.find(|finding| finding.code == "animation.default_clip_missing")
.expect("a stale import default must be a blocking project diagnostic");
assert_eq!(finding.severity, ValidationSeverity::Error);
assert_eq!(finding.reference.as_deref(), Some(missing.as_str()));
assert!(finding.repair.contains("Default animation"));
assert!(!report.is_release_ready());
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn invalid_animation_state_contract_reports_each_actor_property() {
let root = fixture_root();
@@ -2757,9 +3332,9 @@ mod tests {
&& finding.owner_actor_id.as_deref() == Some("animated-actor")
})
.expect("signature mismatch must identify the owning actor state");
assert!(finding.reference.as_deref().is_some_and(
|reference| reference.contains("AnimationControllerDesc.states[idle].clip")
));
assert!(finding.reference.as_deref().is_some_and(|reference| {
reference.contains("AnimationControllerDesc.states[idle].clip")
}));
assert!(finding.repair.contains("does not retarget"));
assert!(!report.is_release_ready());
std::fs::remove_dir_all(root).unwrap();
+450
View File
@@ -0,0 +1,450 @@
//! Explicit, transactional project content upgrade support.
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::Serialize;
use shared::{
AuthoringComponentStates, ComponentInstanceId, InspectorOrder, MaterialAsset,
MaterialInstanceAsset, MaterialRef, RendererMaterialSlot, ShaderSchemaAsset,
StaticMeshRenderer, COMPONENT_STATIC_MESH_RENDERER,
};
use crate::document::{SceneComponentBlob, SceneDocument};
const INSPECTOR_ORDER_COMPONENT: &str = "shared::components::InspectorOrder";
const AUTHORING_COMPONENT_STATES_COMPONENT: &str = "shared::components::AuthoringComponentStates";
#[derive(Debug, Clone, Serialize)]
pub struct ProjectUpgradeChange {
pub path: String,
pub kind: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct ProjectUpgradeReport {
pub applied: bool,
pub backup_path: Option<String>,
pub changes: Vec<ProjectUpgradeChange>,
pub warnings: Vec<String>,
}
struct PendingWrite {
path: PathBuf,
contents: String,
kind: &'static str,
}
pub fn upgrade_project(root: &Path, apply: bool) -> Result<ProjectUpgradeReport, String> {
let assets = root.join("assets");
let mut files = Vec::new();
collect_files(&assets, &mut files)?;
files.sort();
let mut pending = Vec::new();
let mut warnings = Vec::new();
for path in files {
if path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with('.'))
{
continue;
}
let relative = path.strip_prefix(root).unwrap_or(&path);
let normalized = relative.to_string_lossy().replace('\\', "/");
let Some(original) = fs::read_to_string(&path).ok() else {
continue;
};
let upgraded = if normalized.ends_with(".scn.ron") || normalized.ends_with(".prefab.ron") {
match canonical_scene_document(&original) {
Ok(value) => Some((value, "scene-schema")),
Err(error) => {
warnings.push(format!("{normalized}: {error}"));
None
}
}
} else if normalized.contains("/materials/") && normalized.ends_with(".ron") {
canonical_material_document(&path, &original)
} else if normalized.contains("/shaders/") && normalized.ends_with(".shader.ron") {
canonical_shader_document(&original)
} else {
None
};
let Some((contents, kind)) = upgraded else {
continue;
};
if normalize_text(&contents) != normalize_text(&original) {
pending.push(PendingWrite {
path,
contents,
kind,
});
}
}
let changes = pending
.iter()
.map(|write| ProjectUpgradeChange {
path: write
.path
.strip_prefix(root)
.unwrap_or(&write.path)
.to_string_lossy()
.replace('\\', "/"),
kind: write.kind.to_string(),
})
.collect::<Vec<_>>();
if !apply || pending.is_empty() {
return Ok(ProjectUpgradeReport {
applied: false,
backup_path: None,
changes,
warnings,
});
}
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|error| error.to_string())?
.as_secs();
let backup_root = root
.join(".blacksite")
.join("backups")
.join(format!("material-component-v4-{timestamp}"));
for write in &pending {
let relative = write
.path
.strip_prefix(root)
.map_err(|error| error.to_string())?;
let backup = backup_root.join(relative);
if let Some(parent) = backup.parent() {
fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
fs::copy(&write.path, &backup).map_err(|error| {
format!(
"could not back up {} to {}: {error}",
write.path.display(),
backup.display()
)
})?;
}
let mut staged = Vec::new();
for (index, write) in pending.iter().enumerate() {
let temporary = write
.path
.with_extension(format!("blacksite-upgrade-{index}.tmp"));
fs::write(&temporary, &write.contents)
.map_err(|error| format!("could not stage {}: {error}", write.path.display()))?;
staged.push((temporary, write.path.clone()));
}
for (temporary, destination) in &staged {
if let Err(error) = fs::rename(temporary, destination) {
for change in &changes {
let backup = backup_root.join(&change.path);
let destination = root.join(&change.path);
let _ = fs::copy(backup, destination);
}
return Err(format!(
"project upgrade failed while replacing {} and was rolled back: {error}",
destination.display()
));
}
}
Ok(ProjectUpgradeReport {
applied: true,
backup_path: Some(
backup_root
.strip_prefix(root)
.unwrap_or(&backup_root)
.to_string_lossy()
.replace('\\', "/"),
),
changes,
warnings,
})
}
fn canonical_scene_document(text: &str) -> Result<String, String> {
let mut document = SceneDocument::from_ron_text(text)?;
for entity in &mut document.entities {
let present_types = entity
.components
.iter()
.filter(|component| shared::authoring_component_id(&component.type_name).is_some())
.map(|component| component.type_name.clone())
.collect::<Vec<_>>();
if let Some(component) = entity
.components
.iter_mut()
.find(|component| component.type_name == COMPONENT_STATIC_MESH_RENDERER)
{
let mut renderer: StaticMeshRenderer =
ron::from_str(&component.ron).map_err(|error| {
format!("could not upgrade StaticMeshRenderer component: {error}")
})?;
normalize_static_renderer(&mut renderer);
*component =
SceneComponentBlob::from_serializable(COMPONENT_STATIC_MESH_RENDERER, &renderer)?;
}
let states_index = entity
.components
.iter()
.position(|component| component.type_name == AUTHORING_COMPONENT_STATES_COMPONENT);
let mut states = states_index
.and_then(|index| {
ron::from_str::<AuthoringComponentStates>(&entity.components[index].ron).ok()
})
.unwrap_or_default();
normalize_component_states(&mut states);
let mut migrated_legacy_state = false;
if let Some(order_index) = entity
.components
.iter()
.position(|component| component.type_name == INSPECTOR_ORDER_COMPONENT)
{
let mut order: InspectorOrder = ron::from_str(&entity.components[order_index].ron)
.map_err(|error| format!("could not upgrade InspectorOrder component: {error}"))?;
for legacy in std::mem::take(&mut order.component_states) {
let key = if legacy.component_id.trim().is_empty() {
legacy.type_name
} else {
legacy.component_id
};
if !key.trim().is_empty() {
states.set_component_active(key, legacy.active);
migrated_legacy_state = true;
}
}
let present = present_types.iter().map(String::as_str).collect::<Vec<_>>();
order.ensure_component_order(&present);
entity.components[order_index] =
SceneComponentBlob::from_serializable(INSPECTOR_ORDER_COMPONENT, &order)?;
}
if states_index.is_some() || migrated_legacy_state {
let component = SceneComponentBlob::from_serializable(
AUTHORING_COMPONENT_STATES_COMPONENT,
&states,
)?;
if let Some(index) = states_index {
entity.components[index] = component;
} else {
entity.components.push(component);
}
}
}
document.to_ron_text()
}
fn normalize_static_renderer(renderer: &mut StaticMeshRenderer) {
for (index, part) in renderer.slots.iter_mut().enumerate() {
if part.id.is_empty() {
let id = if part.mesh.sub_asset_id.trim().is_empty() {
format!("draw:legacy:{index}")
} else {
part.mesh.sub_asset_id.clone()
};
part.id = ComponentInstanceId::new(id);
}
if part.material_slot_id.is_empty() {
part.material_slot_id = ComponentInstanceId::new(format!("slot:{}", part.id.0));
}
let legacy_material = part.material.take().map(MaterialRef::new);
if let Some(slot) = renderer.materials.slot_mut(&part.material_slot_id) {
if slot.source_material.is_none() {
slot.source_material = legacy_material;
}
if slot.name.trim().is_empty() {
slot.name = part.name.clone();
}
} else {
renderer.materials.slots.push(RendererMaterialSlot {
id: part.material_slot_id.clone(),
name: part.name.clone(),
source_material: legacy_material,
material: None,
});
}
}
}
fn normalize_component_states(states: &mut AuthoringComponentStates) {
let old = std::mem::take(&mut states.states);
for state in old {
let key = if state.component_id.trim().is_empty() {
state.type_name
} else {
state.component_id
};
if !key.trim().is_empty() {
states.set_component_active(key, state.active);
}
}
}
fn canonical_material_document(path: &Path, text: &str) -> Option<(String, &'static str)> {
if let Ok(asset) = ron::from_str::<MaterialAsset>(text) {
return ron::ser::to_string_pretty(&asset, ron::ser::PrettyConfig::default())
.ok()
.map(|text| (text, "material-schema"));
}
if let Ok(instance) = ron::from_str::<MaterialInstanceAsset>(text) {
return ron::ser::to_string_pretty(&instance, ron::ser::PrettyConfig::default())
.ok()
.map(|text| (text, "material-instance-schema"));
}
let _ = path;
None
}
fn canonical_shader_document(text: &str) -> Option<(String, &'static str)> {
let schema = ron::from_str::<ShaderSchemaAsset>(text).ok()?;
ron::ser::to_string_pretty(&schema, ron::ser::PrettyConfig::default())
.ok()
.map(|text| (text, "surface-shader-schema"))
}
fn collect_files(path: &Path, output: &mut Vec<PathBuf>) -> Result<(), String> {
if !path.exists() {
return Ok(());
}
for entry in fs::read_dir(path).map_err(|error| error.to_string())? {
let entry = entry.map_err(|error| error.to_string())?;
let path = entry.path();
if entry
.file_type()
.map_err(|error| error.to_string())?
.is_dir()
{
collect_files(&path, output)?;
} else {
output.push(path);
}
}
Ok(())
}
fn normalize_text(text: &str) -> String {
text.trim().replace("\r\n", "\n")
}
#[cfg(test)]
mod tests {
use super::*;
use shared::{
EditorAssetRef, InspectorComponentState, MeshRenderSlot,
AUTHORING_COMPONENT_STATIC_MESH_RENDERER,
};
#[test]
fn dry_run_does_not_write_and_apply_creates_backup() {
let root = std::env::temp_dir().join(format!(
"blacksite-upgrader-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let level = root.join("assets/levels/main.scn.ron");
fs::create_dir_all(level.parent().unwrap()).unwrap();
fs::write(&level, "(schema_version: 3, resources: {}, entities: {})").unwrap();
let dry_run = upgrade_project(&root, false).unwrap();
assert!(!dry_run.applied);
assert_eq!(dry_run.changes.len(), 1);
assert!(fs::read_to_string(&level)
.unwrap()
.contains("schema_version: 3"));
let applied = upgrade_project(&root, true).unwrap();
assert!(applied.applied);
assert!(fs::read_to_string(&level)
.unwrap()
.contains("schema_version: 4"));
assert!(root.join(applied.backup_path.unwrap()).exists());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn canonical_upgrade_materializes_slots_and_separates_active_state() {
let renderer = StaticMeshRenderer {
slots: vec![MeshRenderSlot {
id: ComponentInstanceId::new("draw:body"),
name: "Body".into(),
mesh: EditorAssetRef::new("model", "mesh:body", "Body"),
material: Some(EditorAssetRef::new(
"model",
"material:body",
"Body Material",
)),
..Default::default()
}],
..Default::default()
};
let order = InspectorOrder {
component_type_names: vec![COMPONENT_STATIC_MESH_RENDERER.into()],
component_states: vec![InspectorComponentState {
type_name: COMPONENT_STATIC_MESH_RENDERER.into(),
active: false,
..Default::default()
}],
..Default::default()
};
let text = format!(
"(schema_version: 3, resources: {{}}, entities: {{1: (components: {{\"{COMPONENT_STATIC_MESH_RENDERER}\": {}, \"{INSPECTOR_ORDER_COMPONENT}\": {}}})}})",
ron::to_string(&renderer).unwrap(),
ron::to_string(&order).unwrap(),
);
let upgraded = canonical_scene_document(&text).unwrap();
let document = SceneDocument::from_ron_text(&upgraded).unwrap();
let components = &document.entities[0].components;
let renderer: StaticMeshRenderer = ron::from_str(
&components
.iter()
.find(|component| component.type_name == COMPONENT_STATIC_MESH_RENDERER)
.unwrap()
.ron,
)
.unwrap();
assert!(renderer.slots[0].material.is_none());
assert_eq!(renderer.materials.slots.len(), 1);
assert_eq!(
renderer.materials.slots[0]
.source_material
.as_ref()
.unwrap()
.0
.sub_asset_id,
"material:body"
);
let order: InspectorOrder = ron::from_str(
&components
.iter()
.find(|component| component.type_name == INSPECTOR_ORDER_COMPONENT)
.unwrap()
.ron,
)
.unwrap();
assert!(order.component_states.is_empty());
assert_eq!(
order.component_ids,
vec![AUTHORING_COMPONENT_STATIC_MESH_RENDERER]
);
let states: AuthoringComponentStates = ron::from_str(
&components
.iter()
.find(|component| component.type_name == AUTHORING_COMPONENT_STATES_COMPONENT)
.unwrap()
.ron,
)
.unwrap();
assert!(!states.is_component_active(COMPONENT_STATIC_MESH_RENDERER));
}
}