Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/domain/or-maps/src/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
90 changes: 75 additions & 15 deletions crates/domain/or-world-gta5/src/authoring/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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};
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -236,16 +233,13 @@ pub fn map_file(
format: BinaryFormat,
) -> Result<Vec<u8>, 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.
Expand All @@ -257,15 +251,18 @@ pub fn types_file(types: &CMapTypes, format: BinaryFormat) -> Result<Vec<u8>, 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
}
Expand Down Expand Up @@ -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}"
);
}
}
7 changes: 4 additions & 3 deletions crates/domain/or-world-gta5/src/authoring/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down
116 changes: 89 additions & 27 deletions crates/domain/or-world-gta5/src/authoring/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,57 @@ pub fn check(map: &MapData<'_>) -> Vec<Problem> {
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<Problem> {
let local_parents: Vec<Option<usize>> = 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<Problem> {
Expand Down Expand Up @@ -194,12 +245,17 @@ fn check_occlude_models(map: &MapData<'_>) -> Vec<Problem> {
/// [`crate::group`]'s to check, and checking them here reports every shipped
/// map as broken.
fn check_hierarchy(map: &MapData<'_>) -> Vec<Problem> {
let entities: Vec<_> = map.entities().collect();
let len = entities.len();
let local_parents: Vec<Option<usize>> =
map.entities().map(|e| e.local_parent_index()).collect();
check_hierarchy_parents(&local_parents)
}

fn check_hierarchy_parents(local_parents: &[Option<usize>]) -> Vec<Problem> {
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 {
Expand All @@ -214,18 +270,15 @@ fn check_hierarchy(map: &MapData<'_>) -> Vec<Problem> {
}

// 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;
}
Expand Down Expand Up @@ -262,29 +315,38 @@ fn check_light_arrays(map: &MapData<'_>) -> Vec<Problem> {
let Some(soa) = field::struct_at(map.instance(), key) else {
continue;
};
let lengths: Vec<usize> = 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<Problem>) {
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<Problem> {
let mut problems = Vec::new();
Expand Down
Loading
Loading