From 94bb719f8235c06967d8796da329f3a187511c2b Mon Sep 17 00:00:00 2001 From: leonidarider <358984476+leonidarider@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:17:19 +0100 Subject: [PATCH] refactor: unify GTA V world meta writes onto snapshot-free layered schemas and typed CMapData (desloppify wave 5F) - Make or_world_gta5::write::synthesise snapshot-free by layering type_tables::of_layout(layout) with declared world_types schemas and any installed snapshot via type_tables::layered, so write::encode and WorkingSet::finish no longer require a staged schema snapshot. - Add typed ContentFlags::of_typed, extents::compute_typed, validate::check_typed, and write::{refuse_if_broken_typed, apply_flags_typed, apply_extents_typed} sharing the exact derivation logic with the MetaInstance path. - Update create::map_file to apply flags, extents, and validation directly on typed CMapData before a single map.to_bytes() call, eliminating the serialize-then-reparse MetaInstance round trip. - Add snapshot-free unit tests in write.rs and create.rs and remove stale snapshot-required skip guards in or-world-gta5 integration tests. --- crates/domain/or-maps/src/delete.rs | 2 +- .../or-world-gta5/src/authoring/create.rs | 90 +++++-- .../or-world-gta5/src/authoring/execute.rs | 7 +- .../or-world-gta5/src/authoring/validate.rs | 116 ++++++-- .../or-world-gta5/src/authoring/write.rs | 253 +++++++++++++++++- .../or-world-gta5/src/map/content_flags.rs | 66 ++++- .../domain/or-world-gta5/src/map/extents.rs | 191 ++++++++++--- .../domain/or-world-gta5/src/map/map_data.rs | 11 + .../tests/a_prefab_round_trips_every_map.rs | 8 - .../executing_a_plan_keeps_every_link.rs | 8 - crates/io/or-io/src/meta/typed/mod.rs | 8 + 11 files changed, 639 insertions(+), 121 deletions(-) diff --git a/crates/domain/or-maps/src/delete.rs b/crates/domain/or-maps/src/delete.rs index 6e9d09a21..02eb67f7d 100644 --- a/crates/domain/or-maps/src/delete.rs +++ b/crates/domain/or-maps/src/delete.rs @@ -8,7 +8,7 @@ //! [`crate::operation`], which [`apply`] does whole or not at all and whose inverses put every file back byte for byte. //! //! The typed roots save with no schema snapshot, so the deletion is written on any machine; the links are followed the way -//! `or_world_gta5::execute` follows them over value trees, which it writes only where a snapshot is staged. +//! `or_world_gta5::execute` follows them over value trees. //! //! ⚠ **A plan sees the sources of the pack and nothing else.** A map whose parent is one of these and that is not among the sources //! keeps the indexes it had, which then name other entities. What the sources themselves show of that is said as a [`Note`]: a link diff --git a/crates/domain/or-world-gta5/src/authoring/create.rs b/crates/domain/or-world-gta5/src/authoring/create.rs index d86888ab3..5cc4d0aaf 100644 --- a/crates/domain/or-world-gta5/src/authoring/create.rs +++ b/crates/domain/or-world-gta5/src/authoring/create.rs @@ -3,7 +3,7 @@ //! The records are the typed world family's (`or_io::meta::typed`), built with the members that family types and saved by its //! own save, which lays a root built here out from the classes `or-io` declares (`or_io::meta::typed::world_types`). What a //! person does not choose is derived by the code that derives it for a file that arrived: a guid by [`free_guid`], the content -//! flags by [`crate::write::apply_flags`], the extents by [`crate::write::apply_extents`]; an entity has no parent and no child. +//! flags by [`crate::write::apply_flags_typed`], the extents by [`crate::write::apply_extents_typed`]; an entity has no parent and no child. //! //! ⚠ **The file is a PSO, and RBM is refused.** An RBM class carries a `signature` word that nothing in this tree derives //! ([`CreateError::NoSignature`]), and the game's own world files are RBM, so whether the game loads a world file written as PSO @@ -14,12 +14,11 @@ use glam::{Quat, Vec3}; use or_io::decl::File; -use or_io::meta::binary::parse_meta_binary_full; use or_io::meta::instance::HashedString; use or_io::meta::typed::{ CBaseArchetypeDef, CBaseArchetypeDefAny, CEntityDef, CEntityDefAny, CMapData, CMapTypes, }; -use or_io::meta::{BinaryFormat, DecodeGaps}; +use or_io::meta::BinaryFormat; use crate::archetypes::ArchetypeIndex; use crate::generate::{Authoring, DrawableFacts}; @@ -49,8 +48,6 @@ pub enum CreateError { Save(#[from] or_io::Error), #[error(transparent)] Derive(#[from] WriteError), - #[error("the file made does not read back: {0}")] - ReadBack(#[source] or_io::meta::MetaError), } /// What a person chooses of a new entity: what it places, where it stands and how far it is drawn. @@ -236,16 +233,13 @@ pub fn map_file( format: BinaryFormat, ) -> Result, CreateError> { writable(format)?; - let saved = held_to(map.to_bytes()?, format)?; - let mut diagnostics = DecodeGaps::lenient(); - let (mut root, layout) = - parse_meta_binary_full(or_io::meta::default_library(), &saved, &mut diagnostics) - .map_err(CreateError::ReadBack)?; - write::apply_flags(&mut root)?; + let mut map = map.clone(); + write::refuse_if_broken_typed(&map)?; + write::apply_flags_typed(&mut map)?; // ⚠ Refused when `index` lacks an entity's archetype: extents that leave it out are too small, and the game does not stream a // map by extents its entities stand outside. - write::apply_extents(&mut root, index)?; - Ok(write::encode(&root, &layout)?) + write::apply_extents_typed(&mut map, index)?; + held_to(map.to_bytes()?, format) } /// The file `types` saves as. @@ -257,15 +251,18 @@ pub fn types_file(types: &CMapTypes, format: BinaryFormat) -> Result, Cr #[cfg(test)] mod tests { use super::*; + use crate::content_flags::content; use crate::generate::AssetKind; + use crate::map_data::MapData; use crate::map_types::MapTypes; - use or_io::meta::MetaInstance; + use or_io::meta::binary::parse_meta_binary_full; + use or_io::meta::{DecodeGaps, MetaInstance, SchemaLibrary}; const BENCH: &str = "prop_bench_01a"; fn tree(bytes: &[u8]) -> MetaInstance { let mut diagnostics = DecodeGaps::lenient(); - parse_meta_binary_full(or_io::meta::default_library(), bytes, &mut diagnostics) + parse_meta_binary_full(&SchemaLibrary::default(), bytes, &mut diagnostics) .expect("the file reads") .0 } @@ -390,4 +387,67 @@ mod tests { Err(CreateError::NotAWorldContainer("RBF")) )); } + + #[test] + fn map_file_derives_flags_and_extents_directly_on_typed_map_without_snapshot() { + let mut made = map("hills"); + made.content_flags = content::CRITICAL; + place(&mut made, &bench_at(Vec3::new(10.0, 20.0, 30.0))).expect("placed first"); + place( + &mut made, + &Placed { + rotation: Quat::from_rotation_z(std::f32::consts::FRAC_PI_4), + scale_xy: 2.0, + scale_z: 1.5, + ..bench_at(Vec3::new(-40.0, 50.0, 5.0)) + }, + ) + .expect("placed second"); + + let index = index_of(&bench_types()); + let saved = map_file(&made, &index, BinaryFormat::Pso).expect("saves typed directly"); + let back = CMapData::from_bytes(&saved).expect("reopens typed"); + + // Additive bit-OR preserves authoring bits (CRITICAL) alongside implied bits (HD). + assert_eq!(back.content_flags, content::CRITICAL | content::HD); + assert_eq!(back.flags, 0); + + let raw = tree(&saved); + let expected = crate::extents::compute(&MapData::new(&raw).expect("a CMapData"), &index); + assert_eq!(vec3(back.entities_extents_min), expected.entities.min); + assert_eq!(vec3(back.entities_extents_max), expected.entities.max); + assert_eq!(vec3(back.streaming_extents_min), expected.streaming.min); + assert_eq!(vec3(back.streaming_extents_max), expected.streaming.max); + + // Missing archetypes refuse with IncompleteExtents. + let incomplete = map_file(&made, &ArchetypeIndex::new(), BinaryFormat::Pso) + .expect_err("unresolved archetypes are refused"); + assert!( + matches!( + incomplete, + CreateError::Derive(WriteError::IncompleteExtents(2)) + ), + "{incomplete}" + ); + + // Structural problems (out-of-range parent and parent cycle) are refused before encoding. + let mut out_of_range = made.clone(); + out_of_range.entities[0].parent_index = 99; + let refused = map_file(&out_of_range, &index, BinaryFormat::Pso) + .expect_err("out-of-range parent is refused"); + assert!( + matches!(refused, CreateError::Derive(WriteError::Structural(1, _))), + "{refused}" + ); + + let mut cycle = made.clone(); + cycle.entities[0].parent_index = 1; + cycle.entities[1].parent_index = 0; + let refused = + map_file(&cycle, &index, BinaryFormat::Pso).expect_err("parent cycle is refused"); + assert!( + matches!(refused, CreateError::Derive(WriteError::Structural(1, _))), + "{refused}" + ); + } } diff --git a/crates/domain/or-world-gta5/src/authoring/execute.rs b/crates/domain/or-world-gta5/src/authoring/execute.rs index 7400cacc6..528ec8bda 100644 --- a/crates/domain/or-world-gta5/src/authoring/execute.rs +++ b/crates/domain/or-world-gta5/src/authoring/execute.rs @@ -14,9 +14,10 @@ //! link names the same entity it named before, by identity. //! //! ⚠ **A grown or shrunk array reaches the file through synthesis**, which -//! is [`crate::write::encode`]'s fallback, and synthesis needs the schema -//! snapshot. With none staged, [`WorkingSet::finish`] refuses with the -//! writer's own reason and writes nothing. +//! is [`crate::write::encode`]'s fallback, laying out from the document's own +//! type table layered with `or-io`'s declared world types (and any staged +//! schema snapshot for classes neither states), so [`WorkingSet::finish`] +//! writes with no schema snapshot staged. use std::collections::{BTreeMap, BTreeSet}; diff --git a/crates/domain/or-world-gta5/src/authoring/validate.rs b/crates/domain/or-world-gta5/src/authoring/validate.rs index fc25cf241..65fb10b3a 100644 --- a/crates/domain/or-world-gta5/src/authoring/validate.rs +++ b/crates/domain/or-world-gta5/src/authoring/validate.rs @@ -163,6 +163,57 @@ pub fn check(map: &MapData<'_>) -> Vec { problems } +/// Check a typed [`or_io::meta::typed::CMapData`]'s LOD hierarchy, its light arrays and its occlude models. +pub fn check_typed(map: &or_io::meta::typed::CMapData) -> Vec { + let local_parents: Vec> = map + .entities + .iter() + .map(|entity| { + (entity.flags & (1 << 3) == 0) + .then(|| usize::try_from(entity.parent_index).ok()) + .flatten() + }) + .collect(); + let mut problems = check_hierarchy_parents(&local_parents); + let lights = &map.lod_lights_soa; + check_light_family( + &[ + ("direction", lights.direction.len()), + ("falloff", lights.falloff.len()), + ("falloffExponent", lights.falloff_exponent.len()), + ("timeAndStateFlags", lights.time_and_state_flags.len()), + ("hash", lights.hash.len()), + ("coneInnerAngle", lights.cone_inner_angle.len()), + ( + "coneOuterAngleOrCapExt", + lights.cone_outer_angle_or_cap_ext.len(), + ), + ("coronaIntensity", lights.corona_intensity.len()), + ], + &mut problems, + ); + let distant = &map.distant_lod_lights_soa; + check_light_family( + &[ + ("position", distant.position.len()), + ("RGBI", distant.rgbi.len()), + ], + &mut problems, + ); + for (model, record) in map.occlude_models.iter().enumerate() { + let stated = record.data_size; + let held = record.verts.len(); + if stated as usize != held { + problems.push(Problem::OccludeModelSizeDiffers { + model, + stated, + held, + }); + } + } + problems +} + /// ⚠ `dataSize` counts the bytes behind `verts`, and the engine reads that many: a save of the typed map refuses a model /// whose two differ. fn check_occlude_models(map: &MapData<'_>) -> Vec { @@ -194,12 +245,17 @@ fn check_occlude_models(map: &MapData<'_>) -> Vec { /// [`crate::group`]'s to check, and checking them here reports every shipped /// map as broken. fn check_hierarchy(map: &MapData<'_>) -> Vec { - let entities: Vec<_> = map.entities().collect(); - let len = entities.len(); + let local_parents: Vec> = + map.entities().map(|e| e.local_parent_index()).collect(); + check_hierarchy_parents(&local_parents) +} + +fn check_hierarchy_parents(local_parents: &[Option]) -> Vec { + let len = local_parents.len(); let mut problems = Vec::new(); - for (i, entity) in entities.iter().enumerate() { - let Some(parent) = entity.local_parent_index() else { + for (i, &parent) in local_parents.iter().enumerate() { + let Some(parent) = parent else { continue; }; if parent >= len { @@ -214,18 +270,15 @@ fn check_hierarchy(map: &MapData<'_>) -> Vec { } // A chain longer than the array has to revisit a node. - for (i, _) in entities.iter().enumerate() { + for i in 0..len { let mut at = i; for _ in 0..len { - match entities[at].local_parent_index() { + match local_parents[at] { Some(p) if p < len && p != at => at = p, _ => break, } } - if entities[at] - .local_parent_index() - .is_some_and(|p| p < len && p != at) - { + if local_parents[at].is_some_and(|p| p < len && p != at) { problems.push(Problem::ParentCycle { entity: i }); break; } @@ -262,29 +315,38 @@ fn check_light_arrays(map: &MapData<'_>) -> Vec { let Some(soa) = field::struct_at(map.instance(), key) else { continue; }; - let lengths: Vec = fields + let pairs: Vec<(&'static str, usize)> = fields .iter() - .map(|name| field::array_at(soa, literal_string_hash(name.as_bytes())).len()) + .map(|&name| { + ( + name, + field::array_at(soa, literal_string_hash(name.as_bytes())).len(), + ) + }) .collect(); - let Some(&expected) = lengths.iter().max() else { - continue; - }; - if expected == 0 { - continue; - } - for (name, len) in fields.iter().zip(&lengths) { - if *len != expected { - problems.push(Problem::LightArraysDiffer { - field: name, - len: *len, - expected, - }); - } - } + check_light_family(&pairs, &mut problems); } problems } +fn check_light_family(fields: &[(&'static str, usize)], problems: &mut Vec) { + let Some(expected) = fields.iter().map(|(_, len)| *len).max() else { + return; + }; + if expected == 0 { + return; + } + for &(name, len) in fields { + if len != expected { + problems.push(Problem::LightArraysDiffer { + field: name, + len, + expected, + }); + } + } +} + /// Check an interior's rooms, portals and entity sets against each other. pub fn check_interior(interior: &crate::map_types::Interior<'_>) -> Vec { let mut problems = Vec::new(); diff --git a/crates/domain/or-world-gta5/src/authoring/write.rs b/crates/domain/or-world-gta5/src/authoring/write.rs index fa45b367d..63d0b80ae 100644 --- a/crates/domain/or-world-gta5/src/authoring/write.rs +++ b/crates/domain/or-world-gta5/src/authoring/write.rs @@ -11,7 +11,8 @@ //! so no round trip catches it. use or_io::meta::binary::synth::{pso_layout_for_instance, rbm_layout_for_instance}; -use or_io::meta::binary::{write_meta_binary, ContainerLayout, MetaLayout}; +use or_io::meta::binary::{type_tables, write_meta_binary, ContainerLayout, MetaLayout}; +use or_io::meta::typed::{world_types, CMapData}; use or_io::meta::{MetaInstance, SchemaLibrary, Value}; use crate::archetypes::ArchetypeIndex; @@ -57,6 +58,16 @@ pub fn refuse_if_broken(root: &MetaInstance) -> Result<(), WriteError> { } } +/// Refuse a typed map the game would misread. +pub fn refuse_if_broken_typed(map: &CMapData) -> Result<(), WriteError> { + let problems = validate::check_typed(map); + if problems.is_empty() { + Ok(()) + } else { + Err(WriteError::Structural(problems.len(), problems)) + } +} + /// Encode a world document, refusing one the game would misread. /// /// The layout is the one the document was read with, so an untouched @@ -96,6 +107,11 @@ pub fn encode_with( /// A layout for a tree that no longer fits the one it arrived with. /// +/// The document's own type table comes first (preserving every member of the +/// build it came from), then the world classes declared in `or-io` for any +/// class a PSO table did not state, then `library` for anything neither holds +/// nor names — so synthesis works with no schema snapshot staged. +/// /// ⚠ The donor supplies a class's `signature` word and nothing else: no tool /// here or in CodeWalker derives one, so it is taken from the document rather /// than left at zero. Every offset, ordering and padding byte comes from the @@ -105,13 +121,20 @@ fn synthesise( root: &MetaInstance, layout: &MetaLayout, ) -> Result { + let mut tables = type_tables::of_layout(layout); + if matches!(&layout.container, ContainerLayout::Pso(pso) if !pso.is_gta_vi()) { + type_tables::fill(&mut tables, world_types::declared()); + } + let snapshot = (!library.structs.is_empty() || !library.enums.is_empty()).then_some(library); + let empty = SchemaLibrary::default(); + let typed = type_tables::layered(&empty, &tables, snapshot); let container = match &layout.container { ContainerLayout::Rbm(donor) => ContainerLayout::Rbm(Box::new(rbm_layout_for_instance( - library, + &typed, root, Some(&donor.model), )?)), - ContainerLayout::Pso(_) => ContainerLayout::Pso(pso_layout_for_instance(library, root)?), + ContainerLayout::Pso(_) => ContainerLayout::Pso(pso_layout_for_instance(&typed, root)?), // RBF needs no layout at all, so it has no allocation to outgrow. ContainerLayout::Rbf(rbf) => ContainerLayout::Rbf(rbf.clone()), }; @@ -145,6 +168,20 @@ pub fn apply_flags(root: &mut MetaInstance) -> Result { Ok(changed) } +/// Add the flag bits a typed map's contents imply, leaving the rest alone. +/// +/// Shares [`ContentFlags::of_typed`] with [`apply_flags`]: additive bit-OR +/// preserves authoring bits such as `contentFlags` bit 9 (`_critical_`). +pub fn apply_flags_typed(map: &mut CMapData) -> Result { + let implied = ContentFlags::of_typed(map); + let new_flags = map.flags | implied.flags; + let new_content = map.content_flags | implied.content; + let changed = new_flags != map.flags || new_content != map.content_flags; + map.flags = new_flags; + map.content_flags = new_content; + Ok(changed) +} + /// Recompute a map's four extents and write them into the tree. /// /// ⚠ Refuses when any entity's archetype is unresolved: extents computed @@ -156,23 +193,60 @@ pub fn apply_extents(root: &mut MetaInstance, index: &ArchetypeIndex) -> Result< let map = MapData::new(root).ok_or(WriteError::NotAMap)?; extents::compute(&map, index) }; + let Some((entities, streaming)) = validated_extents(&computed)? else { + return Ok(false); + }; + + let mut changed = set_vec3(root, keys::ENTITIES_EXTENTS_MIN, entities.min); + changed |= set_vec3(root, keys::ENTITIES_EXTENTS_MAX, entities.max); + changed |= set_vec3(root, keys::STREAMING_EXTENTS_MIN, streaming.min); + changed |= set_vec3(root, keys::STREAMING_EXTENTS_MAX, streaming.max); + Ok(changed) +} + +/// Recompute a typed map's four extents and write them into `map`. +/// +/// Refuses on unresolved archetypes or empty/non-finite streaming extents, +/// matching [`apply_extents`]. +pub fn apply_extents_typed(map: &mut CMapData, index: &ArchetypeIndex) -> Result { + let computed = extents::compute_typed(map, index); + let Some((entities, streaming)) = validated_extents(&computed)? else { + return Ok(false); + }; + + let mut changed = set_decl_vec3(&mut map.entities_extents_min, entities.min); + changed |= set_decl_vec3(&mut map.entities_extents_max, entities.max); + changed |= set_decl_vec3(&mut map.streaming_extents_min, streaming.min); + changed |= set_decl_vec3(&mut map.streaming_extents_max, streaming.max); + Ok(changed) +} + +fn validated_extents( + computed: &extents::Extents, +) -> Result, WriteError> { if !computed.is_complete() { return Err(WriteError::IncompleteExtents(computed.unresolved)); } if computed.entities.is_empty() { - return Ok(false); + return Ok(None); } // ⚠ A scale of nought or below leaves an entity out of the streaming box with no word, and a box that holds nothing streams nothing. let streaming = computed.streaming; if streaming.is_empty() || !(streaming.min.is_finite() && streaming.max.is_finite()) { return Err(WriteError::NoStreamingExtents); } + Ok(Some((computed.entities, streaming))) +} - let mut changed = set_vec3(root, keys::ENTITIES_EXTENTS_MIN, computed.entities.min); - changed |= set_vec3(root, keys::ENTITIES_EXTENTS_MAX, computed.entities.max); - changed |= set_vec3(root, keys::STREAMING_EXTENTS_MIN, computed.streaming.min); - changed |= set_vec3(root, keys::STREAMING_EXTENTS_MAX, computed.streaming.max); - Ok(changed) +fn set_decl_vec3(slot: &mut or_io::decl::Vec3, value: glam::Vec3) -> bool { + let new = or_io::decl::Vec3 { + x: value.x, + y: value.y, + z: value.z, + }; + let changed = *slot != new; + *slot = new; + changed } /// ⚠ Writes through the field's existing slot and never adds one: a name the @@ -217,7 +291,11 @@ fn set_vec3(root: &mut MetaInstance, key: u32, value: glam::Vec3) -> bool { #[cfg(test)] mod tests { use super::*; + use glam::Vec3; + use or_io::decl::File; + use or_io::meta::binary::parse_meta_binary_full; use or_io::meta::instance::value::HashedString; + use or_io::meta::{canonical, BinaryFormat, DecodeGaps}; fn map() -> MetaInstance { let mut ent = MetaInstance::new("CEntityDef"); @@ -262,4 +340,161 @@ mod tests { assert!(matches!(err, WriteError::Structural(1, _)), "{err}"); assert!(err.to_string().contains("entity 0"), "{err}"); } + + #[test] + fn growing_and_shrinking_a_map_synthesises_without_a_schema_snapshot() { + let empty = SchemaLibrary::default(); + let mut typed = crate::create::map("hills"); + crate::create::place( + &mut typed, + &crate::create::Placed::at(HashedString::new("prop_x"), Vec3::ZERO, 60.0), + ) + .expect("places entity"); + let pso_bytes = typed.to_bytes().expect("saves as PSO without snapshot"); + let (pso_doc, _) = + parse_meta_binary_full(&empty, &pso_bytes, &mut DecodeGaps::lenient()).expect("reads"); + let rbm_layout = + canonical::layout_for(world_types::declared(), &pso_doc, BinaryFormat::Rbm, None) + .expect("rbm layout"); + let rbm_bytes = + write_meta_binary(BinaryFormat::Rbm, Some(&rbm_layout), &pso_doc).expect("rbm bytes"); + + for (label, bytes) in [ + ("hills_pso.ymap", &pso_bytes), + ("hills_rbm.ymap", &rbm_bytes), + ] { + let (mut doc, layout) = + parse_meta_binary_full(&empty, bytes, &mut DecodeGaps::lenient()) + .expect("parses without snapshot"); + let first_entity = MapData::new(&doc) + .expect("a CMapData") + .entities() + .next() + .expect("one entity") + .instance() + .clone(); + + // Grow the entities array so the arrival layout is outgrown and synthesis must run. + if let Some(Value::Array(items)) = field::get_mut(&mut doc, keys::ENTITIES) { + items.push(Value::Pointer(Some(Box::new(first_entity.clone())))); + } + let outgrew = write_meta_binary(layout.format, Some(&layout), &doc) + .expect_err("arrival layout must refuse a grown array"); + assert!(outgrew.outgrew_its_layout(), "{label}: {outgrew}"); + + let grown_bytes = encode_with(&empty, &doc, &layout) + .unwrap_or_else(|e| panic!("{label}: synthesis with empty schema failed: {e}")); + let (mut grown_doc, grown_layout) = + parse_meta_binary_full(&empty, &grown_bytes, &mut DecodeGaps::lenient()) + .expect("grown map reads back"); + assert_eq!( + MapData::new(&grown_doc).expect("a CMapData").entity_count(), + 2, + "{label}" + ); + + // Shrink the entities array back to one and encode again with an empty schema library. + if let Some(Value::Array(items)) = field::get_mut(&mut grown_doc, keys::ENTITIES) { + items.pop(); + } + let shrunk_bytes = encode_with(&empty, &grown_doc, &grown_layout) + .unwrap_or_else(|e| panic!("{label}: shrunk encode failed: {e}")); + let (shrunk_doc, _) = + parse_meta_binary_full(&empty, &shrunk_bytes, &mut DecodeGaps::lenient()) + .expect("shrunk map reads back"); + assert_eq!( + MapData::new(&shrunk_doc) + .expect("a CMapData") + .entity_count(), + 1, + "{label}" + ); + + // Verify WorkingSet::finish succeeds end-to-end on both grow and shrink. + let (ws_doc, ws_layout) = + parse_meta_binary_full(&empty, bytes, &mut DecodeGaps::lenient()).expect("reads"); + let map_hash = or_io::string_hash(b"hills"); + let mut ws = crate::execute::WorkingSet::new(); + ws.add(label, ws_doc, ws_layout); + ws.add_entities(map_hash, vec![first_entity]) + .expect("adds entity"); + let finished = ws + .finish() + .unwrap_or_else(|e| panic!("{label}: WorkingSet::finish (grow) failed: {e}")); + assert_eq!(finished.len(), 1); + let (back_doc, back_layout) = + parse_meta_binary_full(&empty, &finished[0].1, &mut DecodeGaps::lenient()) + .expect("WorkingSet grown output reads back"); + assert_eq!( + MapData::new(&back_doc).expect("a CMapData").entity_count(), + 2, + "{label}" + ); + + let mut ws_shrink = crate::execute::WorkingSet::new(); + ws_shrink.add(label, back_doc, back_layout); + ws_shrink + .delete_entity(map_hash, 1) + .expect("deletes entity"); + let finished_shrink = ws_shrink + .finish() + .unwrap_or_else(|e| panic!("{label}: WorkingSet::finish (shrink) failed: {e}")); + assert_eq!(finished_shrink.len(), 1); + let (back_shrunk, _) = + parse_meta_binary_full(&empty, &finished_shrink[0].1, &mut DecodeGaps::lenient()) + .expect("WorkingSet shrunk output reads back"); + assert_eq!( + MapData::new(&back_shrunk) + .expect("a CMapData") + .entity_count(), + 1, + "{label}" + ); + } + + // Growing an empty PSO map (whose own type table does not yet state CEntityDef) falls back + // to the world classes declared in `or-io` without needing a schema snapshot. + let empty_pso = crate::create::map("empty_hills") + .to_bytes() + .expect("empty PSO map saves"); + let (mut empty_doc, empty_layout) = + parse_meta_binary_full(&empty, &empty_pso, &mut DecodeGaps::lenient()).expect("reads"); + let sample_entity = MapData::new(&pso_doc) + .expect("a CMapData") + .entities() + .next() + .expect("one entity") + .instance() + .clone(); + if let Some(Value::Array(items)) = field::get_mut(&mut empty_doc, keys::ENTITIES) { + items.push(Value::Pointer(Some(Box::new(sample_entity)))); + } + let first_entity_bytes = encode_with(&empty, &empty_doc, &empty_layout) + .expect("empty PSO map takes its first entity via declared world types"); + let (back, _) = + parse_meta_binary_full(&empty, &first_entity_bytes, &mut DecodeGaps::lenient()) + .expect("reads back"); + assert_eq!(MapData::new(&back).expect("a CMapData").entity_count(), 1); + } + + #[test] + fn typed_flags_are_additive_and_broken_typed_maps_are_refused() { + let mut typed = crate::create::map("hills"); + crate::create::place( + &mut typed, + &crate::create::Placed::at(HashedString::new("prop_x"), Vec3::ZERO, 60.0), + ) + .expect("placed"); + typed.content_flags = crate::content_flags::content::CRITICAL; + assert!(apply_flags_typed(&mut typed).expect("applies flags")); + assert_eq!( + typed.content_flags, + crate::content_flags::content::CRITICAL | crate::content_flags::content::HD + ); + assert!(!apply_flags_typed(&mut typed).expect("idempotent")); + + typed.entities[0].parent_index = 0; + let err = refuse_if_broken_typed(&typed).unwrap_err(); + assert!(matches!(err, WriteError::Structural(1, _)), "{err}"); + } } diff --git a/crates/domain/or-world-gta5/src/map/content_flags.rs b/crates/domain/or-world-gta5/src/map/content_flags.rs index 2e77aaadc..7abfd02c2 100644 --- a/crates/domain/or-world-gta5/src/map/content_flags.rs +++ b/crates/domain/or-world-gta5/src/map/content_flags.rs @@ -7,7 +7,10 @@ //! carry its neighbour's claim — so [`Divergence`] matters in the other //! direction: a bit the contents imply and the file does not set. -use crate::map_data::MapData; +use or_io::meta::typed::CMapData; +use or_io::meta::Value; + +use crate::map_data::{self, MapData}; /// Bit positions in `contentFlags`, named for what sets them. pub mod content { @@ -43,15 +46,60 @@ pub struct ContentFlags { pub content: u32, } +struct ContentSummary { + has_physics: bool, + has_grass: bool, + has_lod_lights: bool, + has_distant_lod_lights: bool, + has_occlusion: bool, +} + impl ContentFlags { /// What this map's contents imply. pub fn of(map: &MapData<'_>) -> Self { + Self::from_parts( + map.entities() + .map(|entity| (entity.lod_level(), entity.is_interior_instance())), + ContentSummary { + has_physics: map.physics_dictionary_count() > 0, + has_grass: map.grass_batches().next().is_some(), + has_lod_lights: map.has_lod_lights(), + has_distant_lod_lights: map.has_distant_lod_lights(), + has_occlusion: map.box_occluder_count() > 0 || map.occlude_model_count() > 0, + }, + ) + } + + /// What a typed [`CMapData`]'s contents imply, using the same rules as [`Self::of`]. + pub fn of_typed(map: &CMapData) -> Self { + Self::from_parts( + map.entities.iter().map(|entity| { + let lod = match entity.carried("lodLevel") { + Some(Value::Enum { variant, .. }) => Some(variant.as_str()), + _ => None, + }; + (lod, entity.as_mlo_instance().is_some()) + }), + ContentSummary { + has_physics: !map.physics_dictionaries.is_empty(), + has_grass: map_data::grass_batches_of_typed(map).next().is_some(), + has_lod_lights: !map.lod_lights_soa.is_empty(), + has_distant_lod_lights: !map.distant_lod_lights_soa.is_empty(), + has_occlusion: !map.box_occluders.is_empty() || !map.occlude_models.is_empty(), + }, + ) + } + + fn from_parts<'a>( + entities: impl Iterator, bool)>, + summary: ContentSummary, + ) -> Self { let mut flags = 0u32; let mut content = 0u32; - for entity in map.entities() { + for (lod_level, is_interior_instance) in entities { // ⚠ An entity whose class states no `lodLevel` is read at the enum's zero, which is HD, as a variant with no name is. - match entity.lod_level().map_or(LodDepth::Hd, lod_depth) { + match lod_level.map_or(LodDepth::Hd, lod_depth) { LodDepth::Hd => content |= content::HD, LodDepth::Lod => { content |= content::LOD; @@ -66,25 +114,25 @@ impl ContentFlags { flags |= map::SCRIPTED_OR_LOD; } } - if entity.is_interior_instance() { + if is_interior_instance { content |= content::INTERIOR; } } - if map.physics_dictionary_count() > 0 { + if summary.has_physics { content |= content::PHYSICS; } - if map.grass_batches().next().is_some() { + if summary.has_grass { content |= content::GRASS; } - if map.has_lod_lights() { + if summary.has_lod_lights { content |= content::LOD_LIGHTS; } - if map.has_distant_lod_lights() { + if summary.has_distant_lod_lights { content |= content::DISTANT_LOD_LIGHTS; flags |= map::SCRIPTED_OR_LOD; } - if map.box_occluder_count() > 0 || map.occlude_model_count() > 0 { + if summary.has_occlusion { content |= content::OCCLUSION; } diff --git a/crates/domain/or-world-gta5/src/map/extents.rs b/crates/domain/or-world-gta5/src/map/extents.rs index 27b0875a6..93f191dea 100644 --- a/crates/domain/or-world-gta5/src/map/extents.rs +++ b/crates/domain/or-world-gta5/src/map/extents.rs @@ -12,11 +12,14 @@ //! offered as a proposal and [`agreement`] is how far it is from what the //! game shipped, not a claim to have reproduced it. +use glam::{Quat, Vec3}; +use or_io::meta::typed::CMapData; pub use or_world::aabb::agreement; -use or_world::Aabb; +use or_world::{transform, Aabb}; use crate::archetypes::ArchetypeIndex; -use crate::map_data::MapData; +use crate::map_data::{self, GrassBatch, MapData}; +use crate::transform::Placement; /// What a recomputation produced, and how much of it it could see. #[derive(Debug, Clone, Copy)] @@ -39,67 +42,173 @@ impl Extents { } } -/// Recompute both extents for a map, using `index` for archetype bounds. -pub fn compute(map: &MapData<'_>, index: &ArchetypeIndex) -> Extents { - let mut entities = Aabb::default(); - let mut streaming = Aabb::default(); - let mut unresolved = 0; - let mut resolved = 0; +struct ExtentAccumulator<'a> { + index: &'a ArchetypeIndex, + entities: Aabb, + streaming: Aabb, + unresolved: usize, + resolved: usize, +} - for entity in map.entities() { - let Some(bounds) = index.bounds_of(entity.archetype()) else { - unresolved += 1; - continue; +impl<'a> ExtentAccumulator<'a> { + fn new(index: &'a ArchetypeIndex) -> Self { + Self { + index, + entities: Aabb::default(), + streaming: Aabb::default(), + unresolved: 0, + resolved: 0, + } + } + + fn add_entity( + &mut self, + archetype: u32, + lod_dist: f32, + position: Vec3, + rotation: Quat, + scale: Vec3, + ) { + let Some(bounds) = self.index.bounds_of(archetype) else { + self.unresolved += 1; + return; }; - resolved += 1; + self.resolved += 1; - let mut lod_dist = entity.lod_dist(); + let mut lod_dist = lod_dist; if lod_dist <= 0.0 { - lod_dist = index.lod_dist_of(entity.archetype()).unwrap_or(0.0); + lod_dist = self.index.lod_dist_of(archetype).unwrap_or(0.0); } - for corner in entity.place(bounds.min, bounds.max) { - entities.add_point(corner); + for corner in + transform::placed_corners(bounds.min * scale, bounds.max * scale, rotation, position) + { + self.entities.add_point(corner); } // ⚠ By the size of the scale: an entity mirrored by a scale below nought is drawn as far as one that is not. - let spread = lod_dist / entity.scale().abs().max_element().max(f32::MIN_POSITIVE); - for corner in entity.place(bounds.min - spread, bounds.max + spread) { - streaming.add_point(corner); + let spread = lod_dist / scale.abs().max_element().max(f32::MIN_POSITIVE); + for corner in transform::placed_corners( + (bounds.min - spread) * scale, + (bounds.max + spread) * scale, + rotation, + position, + ) { + self.streaming.add_point(corner); } } - for batch in map.grass_batches() { + fn add_grass_batch(&mut self, batch: GrassBatch<'_>) { if let Some((min, max)) = batch.bounds() { - entities.add_box(min, max); + self.entities.add_box(min, max); let lod = batch.lod_dist(); - streaming.add_box(min - lod, max + lod); + self.streaming.add_box(min - lod, max + lod); } } - for generator in map.car_generators() { - let Some(position) = generator.position() else { - continue; - }; - let length = generator.perpendicular_length(); - entities.add_box(position - length, position + length); - streaming.add_box(position - length * 2.0, position + length * 2.0); + fn add_car_generator(&mut self, position: Vec3, length: f32) { + self.entities.add_box(position - length, position + length); + self.streaming + .add_box(position - length * 2.0, position + length * 2.0); } - for occluder in map.box_occluders() { - let half = occluder.size.length() * 0.5; - entities.add_box(occluder.centre - half, occluder.centre + half); - streaming.add_box(occluder.centre - half, occluder.centre + half); + fn add_box_occluder(&mut self, centre: Vec3, size: Vec3) { + let half = size.length() * 0.5; + self.entities.add_box(centre - half, centre + half); + self.streaming.add_box(centre - half, centre + half); + } + + fn add_occlude_model(&mut self, min: Vec3, max: Vec3) { + self.entities.add_box(min, max); + self.streaming.add_box(min, max); } + fn finish(self) -> Extents { + Extents { + entities: self.entities, + streaming: self.streaming, + unresolved: self.unresolved, + resolved: self.resolved, + } + } +} + +/// Recompute both extents for a map, using `index` for archetype bounds. +pub fn compute(map: &MapData<'_>, index: &ArchetypeIndex) -> Extents { + let mut acc = ExtentAccumulator::new(index); + + for entity in map.entities() { + acc.add_entity( + entity.archetype(), + entity.lod_dist(), + entity.position(), + entity.rotation(), + entity.scale(), + ); + } + for batch in map.grass_batches() { + acc.add_grass_batch(batch); + } + for generator in map.car_generators() { + if let Some(position) = generator.position() { + acc.add_car_generator(position, generator.perpendicular_length()); + } + } + for occluder in map.box_occluders() { + acc.add_box_occluder(occluder.centre, occluder.size); + } for (min, max) in map.occlude_model_bounds() { - entities.add_box(min, max); - streaming.add_box(min, max); + acc.add_occlude_model(min, max); } - Extents { - entities, - streaming, - unresolved, - resolved, + acc.finish() +} + +/// Recompute both extents for a typed [`CMapData`], using the same math as [`compute`]. +pub fn compute_typed(map: &CMapData, index: &ArchetypeIndex) -> Extents { + let vec3 = |v: or_io::decl::Vec3| Vec3::new(v.x, v.y, v.z); + let mut acc = ExtentAccumulator::new(index); + + for entity in &map.entities { + let placement = match entity.as_mlo_instance() { + Some(_) => Placement::InteriorInstance, + None => Placement::Entity, + }; + let rotation = placement.rotation_of([ + entity.rotation.x, + entity.rotation.y, + entity.rotation.z, + entity.rotation.w, + ]); + acc.add_entity( + entity.archetype_name.hash, + entity.lod_dist, + vec3(entity.position), + rotation, + transform::scale_of(entity.scale_xy, entity.scale_z), + ); + } + for batch in map_data::grass_batches_of_typed(map) { + acc.add_grass_batch(batch); } + for generator in &map.car_generators { + acc.add_car_generator(vec3(generator.position), generator.perpendicular_length); + } + for occluder in &map.box_occluders { + let centre = Vec3::new( + f32::from(occluder.i_center_x) * 0.25, + f32::from(occluder.i_center_y) * 0.25, + f32::from(occluder.i_center_z) * 0.25, + ); + let size = Vec3::new( + f32::from(occluder.i_length) * 0.25, + f32::from(occluder.i_width) * 0.25, + f32::from(occluder.i_height) * 0.25, + ); + acc.add_box_occluder(centre, size); + } + for model in &map.occlude_models { + acc.add_occlude_model(vec3(model.bmin), vec3(model.bmax)); + } + + acc.finish() } diff --git a/crates/domain/or-world-gta5/src/map/map_data.rs b/crates/domain/or-world-gta5/src/map/map_data.rs index 507b9254e..a7e506278 100644 --- a/crates/domain/or-world-gta5/src/map/map_data.rs +++ b/crates/domain/or-world-gta5/src/map/map_data.rs @@ -419,6 +419,17 @@ pub struct BoxOccluder { pub size: Vec3, } +/// The grass batches carried by a typed [`or_io::meta::typed::CMapData`]. +pub(crate) fn grass_batches_of_typed( + map: &or_io::meta::typed::CMapData, +) -> impl Iterator> + '_ { + map.carried("instancedData") + .and_then(field::as_struct) + .into_iter() + .flat_map(|inst| field::structs_at(inst, keys::GRASS_INSTANCE_LIST)) + .map(|inst| GrassBatch { inst }) +} + /// One grass batch, which carries its own bounds rather than deriving them. #[derive(Debug, Clone, Copy)] pub struct GrassBatch<'a> { diff --git a/crates/domain/or-world-gta5/tests/a_prefab_round_trips_every_map.rs b/crates/domain/or-world-gta5/tests/a_prefab_round_trips_every_map.rs index 95c8022fc..a3922be74 100644 --- a/crates/domain/or-world-gta5/tests/a_prefab_round_trips_every_map.rs +++ b/crates/domain/or-world-gta5/tests/a_prefab_round_trips_every_map.rs @@ -340,14 +340,6 @@ fn a_prefab_round_trips_every_map() { ); return; } - if support::schema().struct_("CMapData").is_none() { - skip_install( - WHAT, - "no schema snapshot is staged, and a placement grows an array, which reaches the \ - file only through synthesis; see crates/io/or-io/src/meta/README.md", - ); - return; - } let stride: usize = std::env::var("OPENRAGE_EXEC_STRIDE") .ok() .and_then(|s| s.parse().ok()) diff --git a/crates/domain/or-world-gta5/tests/executing_a_plan_keeps_every_link.rs b/crates/domain/or-world-gta5/tests/executing_a_plan_keeps_every_link.rs index 2c9aea292..e9fbc4c9f 100644 --- a/crates/domain/or-world-gta5/tests/executing_a_plan_keeps_every_link.rs +++ b/crates/domain/or-world-gta5/tests/executing_a_plan_keeps_every_link.rs @@ -555,14 +555,6 @@ fn executing_a_plan_keeps_every_link() { ); return; } - if support::schema().struct_("CMapData").is_none() { - skip_install( - WHAT, - "no schema snapshot is staged, and a grown or shrunk array reaches the file only \ - through synthesis, which lays out from the schema; see crates/io/or-io/src/meta/README.md", - ); - return; - } let stride: usize = std::env::var("OPENRAGE_EXEC_STRIDE") .ok() .and_then(|s| s.parse().ok()) diff --git a/crates/io/or-io/src/meta/typed/mod.rs b/crates/io/or-io/src/meta/typed/mod.rs index 6dcdcb777..dc2764a79 100644 --- a/crates/io/or-io/src/meta/typed/mod.rs +++ b/crates/io/or-io/src/meta/typed/mod.rs @@ -1757,6 +1757,14 @@ pub use map_records::{ }; pub use ped::*; +impl CEntityDef { + /// What the file it was read from states under `member`, a member no typed record names. + pub fn carried(&self, member: &str) -> Option<&Value> { + let key = name_hash(member); + (self.carry.carried().find(|(held, _)| *held == key)).map(|(_, value)| value) + } +} + impl CMapData { /// What the file it was read from states under `member`, a member no typed record names. pub fn carried(&self, member: &str) -> Option<&Value> {