Merge pull request #919 from ludovic111/feat/structure-rule-tests
🤖 Agent: reviewed; verify passes. Parity: all 269 game-side harnesses on modpacks-8's integration commit (main 573f3a64 + the six game-side PRs), vanilla structure-start oracle 35/35. Merged in order #919 → #920 → #922 → #923 → #924, then the stack #926 → #929 → #930 → #932.
This commit is contained in:
@@ -79,15 +79,18 @@ impl BlockProperty {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BoundBlockProperty {
|
||||
states: Arc<[u8]>,
|
||||
property: BlockProperty,
|
||||
mask: u8,
|
||||
}
|
||||
impl BoundBlockProperty {
|
||||
pub fn contains(&self, id: BlockStateId) -> bool {
|
||||
self.states
|
||||
.get(id.0 as usize)
|
||||
.is_some_and(|flags| flags & self.property.mask() != 0)
|
||||
.is_some_and(|flags| flags & self.mask != 0)
|
||||
}
|
||||
}
|
||||
/// The per-state flag of the block definition's `canOcclude`, past the
|
||||
/// [`BlockProperty`] bits.
|
||||
const CAN_OCCLUDE: u8 = 16;
|
||||
|
||||
/// Immutable FULL face-occlusion results, independent of support/collision.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -195,7 +198,12 @@ impl<'r> BlockPropertiesRegistry<'r> {
|
||||
.ok_or_else(|| invalid("missing block occlusion shape"))?,
|
||||
)
|
||||
.map_err(|error| invalid(error.to_string()))?,
|
||||
) << 3),
|
||||
) << 3)
|
||||
| if properties.can_occlude {
|
||||
CAN_OCCLUDE
|
||||
} else {
|
||||
0
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
@@ -225,7 +233,14 @@ impl<'r> BlockPropertiesRegistry<'r> {
|
||||
pub fn bind(&self, property: BlockProperty) -> BoundBlockProperty {
|
||||
BoundBlockProperty {
|
||||
states: Arc::clone(&self.states),
|
||||
property,
|
||||
mask: property.mask(),
|
||||
}
|
||||
}
|
||||
/// The states whose block definition can occlude (BlockState.canOcclude).
|
||||
pub fn bind_can_occlude(&self) -> BoundBlockProperty {
|
||||
BoundBlockProperty {
|
||||
states: Arc::clone(&self.states),
|
||||
mask: CAN_OCCLUDE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ pub struct FeatureBlockBindings<'r> {
|
||||
)>,
|
||||
physical_properties: Option<[BoundBlockProperty; 4]>,
|
||||
pub(crate) occlusion_faces: Option<crate::block_properties::BoundOcclusionFaces>,
|
||||
pub(crate) can_occlude: Option<BoundBlockProperty>,
|
||||
biomes: Option<Arc<super::biome_predicate::BiomePredicateBindings>>,
|
||||
pub(crate) fluids: super::fluid_predicate::FluidPredicateBindings,
|
||||
pub(crate) codec: BlockStateJsonCodec<'r>,
|
||||
@@ -88,6 +89,7 @@ impl<'r> FeatureBlockBindings<'r> {
|
||||
properties.bind(BlockProperty::SolidRender),
|
||||
]);
|
||||
self.occlusion_faces = Some(properties.bind_occlusion_faces());
|
||||
self.can_occlude = Some(properties.bind_can_occlude());
|
||||
Ok(self)
|
||||
}
|
||||
pub fn with_biomes(
|
||||
@@ -156,6 +158,7 @@ impl<'r> FeatureBlockBindings<'r> {
|
||||
biomes: None,
|
||||
physical_properties: None,
|
||||
occlusion_faces: None,
|
||||
can_occlude: None,
|
||||
fluids: super::fluid_predicate::FluidPredicateBindings::new(registry)?,
|
||||
blocks: blocks
|
||||
.into_iter()
|
||||
|
||||
@@ -45,6 +45,9 @@ impl FluidPredicateBindings {
|
||||
self.tags = resolved;
|
||||
Ok(self)
|
||||
}
|
||||
pub(crate) fn table(&self) -> &Arc<FluidStateTable> {
|
||||
&self.table
|
||||
}
|
||||
pub fn state(&self, block: BlockStateId) -> Option<crate::fluid::FluidState> {
|
||||
self.table.get(block)
|
||||
}
|
||||
|
||||
@@ -195,11 +195,19 @@ impl StructureState {
|
||||
for (i, def) in registry.structures.iter().enumerate() {
|
||||
by_step[def.step].push(i);
|
||||
}
|
||||
let bindings = FeatureBlockBindings::with_tags(
|
||||
let mut bindings = FeatureBlockBindings::with_tags(
|
||||
data.registry(),
|
||||
data.integers().clone(),
|
||||
&data.block_tags,
|
||||
)?;
|
||||
// Processors that test what a block is made of read canOcclude.
|
||||
if let Some(blocks) = data
|
||||
.feature_resources
|
||||
.as_ref()
|
||||
.and_then(|r| r.blocks.as_ref())
|
||||
{
|
||||
bindings = bindings.with_block_properties(&blocks.properties)?;
|
||||
}
|
||||
Ok(Some(Self {
|
||||
registry,
|
||||
resources: resources.clone(),
|
||||
|
||||
@@ -3,7 +3,11 @@ use super::{
|
||||
DecodeError, Object, block_feature::FeatureBlockBindings, density::identifier, integer,
|
||||
number_text, required,
|
||||
};
|
||||
use crate::registry::BlockStateId;
|
||||
use crate::{
|
||||
block_properties::BoundBlockProperty,
|
||||
fluid::{FluidKind, FluidStateTable},
|
||||
registry::BlockStateId,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use serde_json::value::RawValue;
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
@@ -21,6 +25,85 @@ enum Node {
|
||||
RandomStates(Arc<BTreeSet<BlockStateId>>, f32),
|
||||
RandomState(BlockStateId, f32),
|
||||
Height(i32, i32),
|
||||
Phase(Box<MatterPhase>),
|
||||
}
|
||||
/// `horizon:matter_phase`: Repurposed Structures' MatterPhaseRuleTest, which
|
||||
/// its mineshafts and Nether monument use to match a block by what it is
|
||||
/// made of (`phase_to_test_for`), optionally inverted (`invert_condition`).
|
||||
#[derive(Clone, Debug)]
|
||||
struct MatterPhase {
|
||||
phase: Phase,
|
||||
invert: bool,
|
||||
air: [BlockStateId; 3],
|
||||
fluids: Arc<FluidStateTable>,
|
||||
/// Only for `SOLID`.
|
||||
can_occlude: Option<BoundBlockProperty>,
|
||||
/// Blocks.RAIL and Blocks.CHAIN (26.3's iron chain).
|
||||
rail_or_chain: BTreeSet<BlockStateId>,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Phase {
|
||||
Solid,
|
||||
Liquid,
|
||||
Air,
|
||||
AirRailOrChain,
|
||||
LiquidRailOrChain,
|
||||
}
|
||||
impl MatterPhase {
|
||||
fn decode(object: &Object, bindings: &FeatureBlockBindings<'_>) -> Result<Self, DecodeError> {
|
||||
let name: String = serde_json::from_str(required(object, "phase_to_test_for")?.get())?;
|
||||
let phase = match name.as_str() {
|
||||
"SOLID" => Phase::Solid,
|
||||
"LIQUID" => Phase::Liquid,
|
||||
"AIR" => Phase::Air,
|
||||
"AIR_RAIL_OR_CHAIN" => Phase::AirRailOrChain,
|
||||
"LIQUID_RAIL_OR_CHAIN" => Phase::LiquidRailOrChain,
|
||||
_ => return Err(DecodeError::Field("matter phase")),
|
||||
};
|
||||
let invert = match object.get("invert_condition") {
|
||||
Some(v) => serde_json::from_str(v.get())?,
|
||||
None => false,
|
||||
};
|
||||
let can_occlude = match phase {
|
||||
Phase::Solid => Some(
|
||||
bindings
|
||||
.can_occlude
|
||||
.clone()
|
||||
.ok_or(DecodeError::Field("matter phase block properties"))?,
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let mut rail_or_chain = BTreeSet::new();
|
||||
for name in ["minecraft:rail", "minecraft:iron_chain"] {
|
||||
rail_or_chain.extend(bindings.blocks.get(name).into_iter().flat_map(|s| s.iter()));
|
||||
}
|
||||
Ok(Self {
|
||||
phase,
|
||||
invert,
|
||||
air: bindings.air,
|
||||
fluids: bindings.fluids.table().clone(),
|
||||
can_occlude,
|
||||
rail_or_chain,
|
||||
})
|
||||
}
|
||||
fn test(&self, state: BlockStateId) -> bool {
|
||||
let air = self.air.contains(&state);
|
||||
let liquid = self
|
||||
.fluids
|
||||
.get(state)
|
||||
.is_some_and(|f| f.kind() != FluidKind::Empty);
|
||||
let rail_or_chain = || self.rail_or_chain.contains(&state);
|
||||
let matched = match self.phase {
|
||||
Phase::Solid => {
|
||||
!air && !liquid && self.can_occlude.as_ref().is_some_and(|c| c.contains(state))
|
||||
}
|
||||
Phase::Liquid => liquid,
|
||||
Phase::Air => air,
|
||||
Phase::AirRailOrChain => air || rail_or_chain(),
|
||||
Phase::LiquidRailOrChain => liquid || rail_or_chain(),
|
||||
};
|
||||
matched != self.invert
|
||||
}
|
||||
}
|
||||
impl RuleTest {
|
||||
pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result<Self, DecodeError> {
|
||||
@@ -104,6 +187,9 @@ impl RuleTest {
|
||||
Node::Any(values)
|
||||
}
|
||||
}
|
||||
"horizon:matter_phase" => {
|
||||
Node::Phase(Box::new(MatterPhase::decode(&object, bindings)?))
|
||||
}
|
||||
_ => return Err(DecodeError::Field("replacement rule type")),
|
||||
};
|
||||
Ok(Self(node))
|
||||
@@ -128,6 +214,7 @@ impl RuleTest {
|
||||
state == *expected && random.next_float() < *probability
|
||||
}
|
||||
Node::Height(min, max) => *min <= position[1] && position[1] <= *max,
|
||||
Node::Phase(phase) => phase.test(state),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,22 @@ enum PosRule {
|
||||
max_dist: i32,
|
||||
axis: Option<usize>,
|
||||
},
|
||||
/// `horizon:piece_origin_axis_aligned_linear_pos`: Repurposed Structures'
|
||||
/// PieceOriginAxisAlignedLinearPosRuleTest, vanilla's axis-aligned chance
|
||||
/// over the block's distance from the template's origin along one axis.
|
||||
PieceOrigin {
|
||||
min_chance: f32,
|
||||
max_chance: f32,
|
||||
min_dist: i32,
|
||||
max_dist: i32,
|
||||
axis: usize,
|
||||
},
|
||||
/// `horizon:y_value`: Repurposed Structures' YValuePosRuleTest, the
|
||||
/// block's world height in `min_y_value..=max_y_value`.
|
||||
YValue {
|
||||
min: i32,
|
||||
max: i32,
|
||||
},
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
enum Modifier {
|
||||
@@ -83,9 +99,97 @@ impl PosRule {
|
||||
}
|
||||
}),
|
||||
},
|
||||
"horizon:piece_origin_axis_aligned_linear_pos" => {
|
||||
let int = |key| p.get(key).and_then(Value::as_i64).unwrap_or(0) as i32;
|
||||
let (min_dist, max_dist) = (int("min_dist"), int("max_dist"));
|
||||
if min_dist >= max_dist {
|
||||
return Err(DecodeError::Field("position predicate distance range"));
|
||||
}
|
||||
Self::PieceOrigin {
|
||||
min_chance: p.get("min_chance").and_then(Value::as_f64).unwrap_or(0.) as f32,
|
||||
max_chance: p.get("max_chance").and_then(Value::as_f64).unwrap_or(0.) as f32,
|
||||
min_dist,
|
||||
max_dist,
|
||||
axis: match p.get("axis").map(|a| a.as_str()) {
|
||||
Some(Some("x")) => 0,
|
||||
None | Some(Some("y")) => 1,
|
||||
Some(Some("z")) => 2,
|
||||
_ => return Err(DecodeError::Field("position predicate axis")),
|
||||
},
|
||||
}
|
||||
}
|
||||
"horizon:y_value" => {
|
||||
let int = |key| {
|
||||
p.get(key)
|
||||
.and_then(Value::as_i64)
|
||||
.map(|v| v as i32)
|
||||
.ok_or(DecodeError::Field("position predicate y value"))
|
||||
};
|
||||
let (min, max) = (int("min_y_value")?, int("max_y_value")?);
|
||||
if min > max {
|
||||
return Err(DecodeError::Field("position predicate y range"));
|
||||
}
|
||||
Self::YValue { min, max }
|
||||
}
|
||||
_ => return Err(DecodeError::Field("position predicate")),
|
||||
})
|
||||
}
|
||||
/// PosRuleTest.test for a block at `world`, `relative` in its template,
|
||||
/// in a piece placed at `reference`.
|
||||
fn test(
|
||||
&self,
|
||||
relative: [i32; 3],
|
||||
world: [i32; 3],
|
||||
reference: [i32; 3],
|
||||
random: &mut impl RandomSource,
|
||||
) -> bool {
|
||||
match *self {
|
||||
Self::Always => true,
|
||||
Self::Linear {
|
||||
min_chance,
|
||||
max_chance,
|
||||
min_dist,
|
||||
max_dist,
|
||||
axis,
|
||||
} => {
|
||||
let dist = match axis {
|
||||
None => (0..3).map(|i| (world[i] - reference[i]).abs()).sum::<i32>(),
|
||||
Some(a) => ((world[a] - reference[a]) as f32).abs() as i32,
|
||||
};
|
||||
random.next_float()
|
||||
<= clamped_chance(min_chance, max_chance, min_dist, max_dist, dist)
|
||||
}
|
||||
Self::PieceOrigin {
|
||||
min_chance,
|
||||
max_chance,
|
||||
min_dist,
|
||||
max_dist,
|
||||
axis,
|
||||
} => {
|
||||
let dist = (relative[axis] as f32).abs() as i32;
|
||||
random.next_float()
|
||||
<= clamped_chance(min_chance, max_chance, min_dist, max_dist, dist)
|
||||
}
|
||||
Self::YValue { min, max } => (min..=max).contains(&world[1]),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Mth.clampedLerp(min_chance, max_chance, Mth.inverseLerp(dist, min_dist, max_dist)).
|
||||
fn clamped_chance(
|
||||
min_chance: f32,
|
||||
max_chance: f32,
|
||||
min_dist: i32,
|
||||
max_dist: i32,
|
||||
dist: i32,
|
||||
) -> f32 {
|
||||
let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32;
|
||||
if t < 0. {
|
||||
min_chance
|
||||
} else if t > 1. {
|
||||
max_chance
|
||||
} else {
|
||||
min_chance + t * (max_chance - min_chance)
|
||||
}
|
||||
}
|
||||
impl Modifier {
|
||||
/// A rule's `block_entity_modifier` (passthrough when missing).
|
||||
@@ -589,42 +693,9 @@ fn process_block<W: PlacementContext>(
|
||||
if !rule.location.test(located, info.pos, &mut random) {
|
||||
continue;
|
||||
}
|
||||
let position_ok = match &rule.position {
|
||||
PosRule::Always => true,
|
||||
PosRule::Linear {
|
||||
min_chance,
|
||||
max_chance,
|
||||
min_dist,
|
||||
max_dist,
|
||||
axis,
|
||||
} => {
|
||||
let dist = match axis {
|
||||
None => (0..3)
|
||||
.map(|i| (info.pos[i] - reference[i]).abs())
|
||||
.sum::<i32>(),
|
||||
Some(a) => {
|
||||
let d: [f32; 3] = std::array::from_fn(|i| {
|
||||
if i == *a {
|
||||
((info.pos[i] - reference[i]) as f32).abs()
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
});
|
||||
(d[0] + d[1] + d[2]) as i32
|
||||
}
|
||||
};
|
||||
let roll = random.next_float();
|
||||
let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32;
|
||||
let chance = if t < 0. {
|
||||
*min_chance
|
||||
} else if t > 1. {
|
||||
*max_chance
|
||||
} else {
|
||||
min_chance + t * (max_chance - min_chance)
|
||||
};
|
||||
roll <= chance
|
||||
}
|
||||
};
|
||||
let position_ok = rule
|
||||
.position
|
||||
.test(relative, info.pos, reference, &mut random);
|
||||
if !position_ok {
|
||||
continue;
|
||||
}
|
||||
@@ -1250,6 +1321,42 @@ mod tests {
|
||||
assert!(SpawnerMobs::decode(&bad, |_| Ok(BlockStateId(0))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repurposed_position_rules() {
|
||||
let decode = |v: Value| PosRule::decode(Some(&v));
|
||||
// Over 3..4 blocks from the template's origin along y, 0 to 1.
|
||||
let rule = decode(
|
||||
json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos",
|
||||
"axis": "y", "min_chance": 0, "max_chance": 1, "min_dist": 3, "max_dist": 4}),
|
||||
)
|
||||
.unwrap();
|
||||
let mut random = LegacyRandom::new(1);
|
||||
let world = [100, 64, -100];
|
||||
// At or under min_dist the chance is 0, a roll of 0 aside; past max_dist it is 1.
|
||||
assert!(!rule.test([9, 2, 9], world, world, &mut random));
|
||||
assert!(rule.test([0, -5, 0], world, world, &mut random));
|
||||
// The world position and the piece's do not count.
|
||||
assert!(rule.test([0, 4, 0], [0, 0, 0], [50, 50, 50], &mut random));
|
||||
// Repurposed refuses an empty distance range and an unknown axis.
|
||||
for bad in [
|
||||
json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos"}),
|
||||
json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos",
|
||||
"min_dist": 0, "max_dist": 1, "axis": "w"}),
|
||||
json!({"predicate_type": "horizon:y_value", "min_y_value": 5, "max_y_value": 4}),
|
||||
json!({"predicate_type": "horizon:y_value", "min_y_value": 5}),
|
||||
] {
|
||||
assert!(decode(bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
let y = decode(
|
||||
json!({"predicate_type": "horizon:y_value", "min_y_value": 0, "max_y_value": 31}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(y.test([0; 3], [7, 31, 7], [0; 3], &mut random));
|
||||
assert!(y.test([0, 99, 0], [7, 0, 7], [0; 3], &mut random));
|
||||
assert!(!y.test([0; 3], [7, 32, 7], [0; 3], &mut random));
|
||||
assert!(!y.test([0; 3], [7, -1, 7], [0; 3], &mut random));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_parts_read_ids_without_a_namespace() {
|
||||
// CTOV writes "always_true"; vanilla reads it as minecraft:always_true.
|
||||
|
||||
@@ -67,3 +67,80 @@ fn binding_rejects_unknown_tag_blocks_and_duplicate_canonical_tags() {
|
||||
]);
|
||||
assert!(FeatureBlockBindings::with_tags(®istry, BTreeSet::new(), &tags).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn matter_phase_matches_what_a_block_is_made_of() {
|
||||
// air, cave_air, void_air, stone, then water (level 0), rail, iron_chain.
|
||||
let mut states: Vec<Tag> = [
|
||||
"minecraft:air",
|
||||
"minecraft:cave_air",
|
||||
"minecraft:void_air",
|
||||
"minecraft:stone",
|
||||
]
|
||||
.iter()
|
||||
.map(|name| Tag::compound([("id", Tag::String((*name).into()))]))
|
||||
.collect();
|
||||
states.push(Tag::compound([
|
||||
("id", Tag::String("minecraft:water".into())),
|
||||
(
|
||||
"properties",
|
||||
Tag::compound([("level", Tag::String("0".into()))]),
|
||||
),
|
||||
]));
|
||||
for name in ["minecraft:rail", "minecraft:iron_chain"] {
|
||||
states.push(Tag::compound([("id", Tag::String(name.into()))]));
|
||||
}
|
||||
let names = [
|
||||
"minecraft:air",
|
||||
"minecraft:cave_air",
|
||||
"minecraft:void_air",
|
||||
"minecraft:stone",
|
||||
"minecraft:water",
|
||||
"minecraft:rail",
|
||||
"minecraft:iron_chain",
|
||||
];
|
||||
let registry = BlockRegistry::from_nbt(&Tag::compound([
|
||||
("DataVersion", Tag::Int(DATA_VERSION)),
|
||||
("states", Tag::List(states)),
|
||||
(
|
||||
"defaults",
|
||||
Tag::Compound(
|
||||
names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, name)| ((*name).into(), Tag::Int(id as i32)))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
]))
|
||||
.unwrap();
|
||||
let bindings = FeatureBlockBindings::new(®istry, BTreeSet::new()).unwrap();
|
||||
let mut random = horizon_core::random::LegacyRandom::new(0);
|
||||
let matches = |phase: &str, invert: bool, random: &mut horizon_core::random::LegacyRandom| {
|
||||
let json = format!(
|
||||
r#"{{"predicate_type":"horizon:matter_phase","phase_to_test_for":"{phase}","invert_condition":{invert}}}"#
|
||||
);
|
||||
let test = RuleTest::from_json(&json, &bindings).unwrap();
|
||||
(0..names.len() as u32)
|
||||
.filter(|&id| test.test(horizon_world::registry::BlockStateId(id), [0; 3], random))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(matches("AIR", false, &mut random), [0, 1, 2]);
|
||||
assert_eq!(matches("LIQUID", false, &mut random), [4]);
|
||||
assert_eq!(
|
||||
matches("AIR_RAIL_OR_CHAIN", false, &mut random),
|
||||
[0, 1, 2, 5, 6]
|
||||
);
|
||||
assert_eq!(
|
||||
matches("LIQUID_RAIL_OR_CHAIN", false, &mut random),
|
||||
[4, 5, 6]
|
||||
);
|
||||
assert_eq!(matches("AIR", true, &mut random), [3, 4, 5, 6]);
|
||||
// The phase is the enum's name as written; SOLID needs canOcclude.
|
||||
for json in [
|
||||
r#"{"predicate_type":"horizon:matter_phase","phase_to_test_for":"air"}"#,
|
||||
r#"{"predicate_type":"horizon:matter_phase","phase_to_test_for":"SOLID"}"#,
|
||||
r#"{"predicate_type":"horizon:matter_phase"}"#,
|
||||
] {
|
||||
assert!(RuleTest::from_json(json, &bindings).is_err(), "{json}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user