WIP: checkpoint interrupted agent work

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-07 23:23:48 +02:00
parent 8178ccede2
commit 42f8960604
5 changed files with 359 additions and 5 deletions
+1
View File
@@ -34,6 +34,7 @@ pub mod feature_region;
pub mod feature_sort;
pub mod fluid_predicate;
pub mod generator;
mod generator_blocks;
mod generator_decoration;
pub mod height_provider;
pub mod material_condition;
+34 -3
View File
@@ -142,6 +142,9 @@ pub(super) struct FeatureResources {
pub(super) placed: BTreeMap<String, String>,
pub(super) feature_tags: BTreeMap<String, String>,
pub(super) fluid_tags: BTreeMap<String, Vec<String>>,
pub(super) state_providers: BTreeMap<String, String>,
/// Block properties, support, collision and survival for placement checks.
pub(super) blocks: Option<super::generator_blocks::BlockBehavior>,
}
/// Seed-independent generation resources, loaded once and shared by every
@@ -255,7 +258,8 @@ impl GeneratorData {
/// per registry state. Multi-noise tables come from `presets.json`
/// (quantized) or `biome_parameters/<name>.json` data-generator reports.
/// Optional decoration inputs: `features`, `placed_features`,
/// `feature_tags`, `fluid_tags`. Integer block properties are derived from
/// `feature_tags`, `fluid_tags`, `state_providers` and the Java-exported
/// block behavior files in `blocks/` (see `generator_blocks`). Integer block properties are derived from
/// the registry: properties whose every value is a decimal integer.
pub fn load(dir: &Path, registry: &'static BlockRegistry) -> Result<Arc<Self>, GeneratorError> {
let flags: Vec<(bool, bool)> =
@@ -376,7 +380,15 @@ impl GeneratorData {
features,
placed,
feature_tags: read_optional_bundle(dir, "feature_tags")?.unwrap_or_default(),
blocks: super::generator_blocks::BlockBehavior::load(
&dir.join("blocks"),
registry,
&block_tags,
&fluid_tags,
)?,
fluid_tags,
state_providers: read_optional_bundle(dir, "state_providers")?
.unwrap_or_default(),
})
}
_ => None,
@@ -512,11 +524,12 @@ struct Pipeline<R: RandomSource> {
extensions: MaterialExtensions<R::Positional>,
picker: GlobalFluidPicker,
zoom: BiomeZoom,
biome_cache: Mutex<HashMap<(i32, i32), Arc<BiomeChunk<BiomeId>>>>,
biome_cache: BiomeCache,
carver_cache: Mutex<HashMap<(i32, i32), BiomeId>>,
pub(super) decoration: Option<super::generator_decoration::Decoration>,
}
const CACHE_LIMIT: usize = 16384;
type BiomeCache = Mutex<HashMap<(i32, i32), Arc<BiomeChunk<BiomeId>>>>;
fn state(registry: &BlockRegistry, raw: &Value) -> Result<BlockStateId, GeneratorError> {
let name = raw
@@ -1052,7 +1065,25 @@ where
) -> Result<DecorateStats, GeneratorError> {
match &self.decoration {
Some(decoration) => {
decoration.decorate(&self.data, self.seed, self.generation(), worker, region)
let center = region[4].position();
// WorldGenRegion's level random, positioned at the center chunk.
let mut random = self
.root
.from_hash_of("minecraft:worldgen_region_random")
.fork_positional()
.at(BlockPos::new(
center.x.wrapping_shl(4),
0,
center.z.wrapping_shl(4),
));
decoration.decorate(
&self.data,
self.seed,
self.generation(),
worker,
region,
|| random.next_boolean(),
)
}
None => Err(resource("decoration resources were not loaded")),
}
@@ -0,0 +1,161 @@
//! Optional block-behavior registries used by feature placement: physical
//! properties, face support, collision and survival rules. Loaded from the
//! bundle's `blocks/` directory (Java-exported, see prepare_native_client.py).
use super::generator::GeneratorError;
use crate::{
block_collision::BlockCollisionRegistry,
block_properties::BlockPropertiesRegistry,
block_support::BlockSupportRegistry,
block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule},
collision::CachedCollisionRegistry,
nbt::{self, Limits, Tag},
registry::BlockRegistry,
};
use serde_json::Value;
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::Path,
sync::Arc,
};
pub(super) struct BlockBehavior {
pub(super) properties: BlockPropertiesRegistry<'static>,
pub(super) support: Arc<BlockSupportRegistry<'static>>,
pub(super) collision: Arc<BlockCollisionRegistry<'static>>,
pub(super) survival: BlockSurvivalRegistry<'static>,
pub(super) double_plants: BTreeSet<String>,
pub(super) mossy_carpets: BTreeSet<String>,
}
fn resource(message: impl Into<String>) -> GeneratorError {
GeneratorError::Resource(message.into())
}
fn rule(name: &str) -> Option<SurvivalRule> {
use SurvivalRule::*;
if let Some(tag) = name.strip_prefix("TagBelow:") {
return Some(TagBelow(tag.to_owned()));
}
Some(match name {
"CactusFlower" => CactusFlower,
"Seagrass" => Seagrass,
"BubbleColumn" => BubbleColumn,
"RedstoneWire" => RedstoneWire,
"DoublePlant" => DoublePlant,
"Door" => Door,
"BigDripleaf" => BigDripleaf,
"BigDripleafStem" => BigDripleafStem,
"Farmland" => Farmland,
"Cocoa" => Cocoa,
"Crop" => Crop,
"GrowingPlant" => GrowingPlant,
"MangrovePropagule" => MangrovePropagule,
"Speleothem" => Speleothem,
"Scaffolding" => Scaffolding,
"PistonHead" => PistonHead,
"ChorusPlant" => ChorusPlant,
"ChorusFlower" => ChorusFlower,
"PitcherCrop" => PitcherCrop,
"Multiface" => Multiface,
"Vine" => Vine,
"HangingMoss" => HangingMoss,
"SnowLayer" => SnowLayer,
"SeaPickle" => SeaPickle,
"Fire" => Fire,
"Cactus" => Cactus,
"Path" => Path,
"Mushroom" => Mushroom,
"Bell" => Bell,
"SugarCane" => SugarCane,
"LilyPad" => LilyPad,
"Frogspawn" => Frogspawn,
"SporeBlossom" => SporeBlossom,
"SmallDripleaf" => SmallDripleaf,
"TallSeagrass" => TallSeagrass,
"Always" => Always,
"SolidBelow" => SolidBelow,
"SolidBehind" => SolidBehind,
"NonAirBelow" => NonAirBelow,
"MossCarpet" => MossCarpet,
"CenterBelow" => CenterBelow,
"Lantern" => Lantern,
"FullAbove" => FullAbove,
"FullBehind" => FullBehind,
"RigidOrCenterBelow" => RigidOrCenterBelow,
"RigidBelow" => RigidBelow,
"FullBelow" => FullBelow,
"CenterAbove" => CenterAbove,
"FaceAttached" => FaceAttached,
"SupportsBamboo" => SupportsBamboo,
_ => return None,
})
}
impl BlockBehavior {
/// Files: `block-properties.nbt`, `cached-collision.nbt`,
/// `cached-support.nbt`, `survival-rules.json`,
/// `survival-extra-definitions.json` and `placement-definitions.json`.
pub(super) fn load(
dir: &Path,
registry: &'static BlockRegistry,
tags: &BTreeMap<String, Vec<String>>,
fluid_tags: &BTreeMap<String, Vec<String>>,
) -> Result<Option<Self>, GeneratorError> {
if !dir.join("block-properties.nbt").exists() {
return Ok(None);
}
let read = |name: &str| -> Result<Tag, GeneratorError> {
let limits = Limits {
max_bytes: 1 << 28,
..Limits::default()
};
Ok(nbt::read_named(&fs::read(dir.join(name))?, limits)
.map_err(|e| resource(format!("{name}: {e:?}")))?
.0
.tag)
};
let json = |name: &str| -> Result<Value, GeneratorError> {
Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?)
};
let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?;
let properties = BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?;
let support = Arc::new(BlockSupportRegistry::from_nbt(
&read("cached-support.nbt")?,
registry,
)?);
let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?);
let rules = json("survival-rules.json")?
.as_object()
.ok_or_else(|| resource("survival rules"))?
.iter()
.map(|(name, value)| {
let text = value.as_str().unwrap_or_default();
rule(text)
.map(|rule| (name.clone(), rule))
.ok_or_else(|| resource(format!("unknown survival rule {text}")))
})
.collect::<Result<_, _>>()?;
let extra = json("survival-extra-definitions.json")?;
let definitions = SurvivalDefinitions {
rules,
ignition_odds: serde_json::from_value(extra["ignition_odds"].clone())?,
fence_gates: serde_json::from_value(extra["fence_gates"].clone())?,
};
let survival = BlockSurvivalRegistry::new(
registry,
&properties,
support.clone(),
collision.clone(),
&definitions,
tags,
fluid_tags,
)?;
let placement = json("placement-definitions.json")?;
Ok(Some(Self {
double_plants: serde_json::from_value(placement["double_plants"].clone())?,
mossy_carpets: serde_json::from_value(placement["mossy_carpets"].clone())?,
properties,
support,
collision,
survival,
}))
}
}
@@ -27,13 +27,23 @@ use super::{
terrain::PreLightChunkStage,
write_zone::GenerationWriteZone,
};
use super::{
generator_blocks::BlockBehavior,
state_provider::{StateProviderBindings, StateProviderCatalog},
};
use crate::{
block_collision::{DynamicCollisionWorld, ShulkerCollisionState},
block_placement::BlockPlacementBindings,
block_support::SupportType,
block_survival::SurvivalWorld,
dynamic_support::DynamicSupportWorld,
fluid::{FluidKind, FluidState},
heightmap::{HeightmapState, HeightmapType},
registry::BlockStateId,
};
use horizon_core::{
biome::obfuscate_seed,
geometry::{Direction, VoxelShape},
position::{BlockPos, ChunkPos},
};
use serde_json::Value;
@@ -111,10 +121,31 @@ impl Decoration {
.collect(),
&data.biome_tags,
)?);
let bindings =
let mut bindings =
FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)?
.with_fluid_tags(&resources.fluid_tags)?
.with_biomes(biomes);
.with_biomes(biomes.clone());
if let Some(blocks) = &resources.blocks {
bindings = bindings
.with_block_properties(&blocks.properties)?
.with_state_providers(
StateProviderBindings::new(
registry,
data.integers().clone(),
&data.block_tags,
)?
.with_block_properties(&blocks.properties)?
.with_fluid_tags(&resources.fluid_tags)?
.with_biomes(biomes),
StateProviderCatalog::from_resources(&resources.state_providers)?,
BlockPlacementBindings::new(
registry,
&blocks.properties,
&blocks.double_plants,
&blocks.mossy_carpets,
)?,
)?;
}
let tags = feature_tags
.build(|name, _| resources.placed.contains_key(name).then(|| name.to_owned()))
.map_err(|e| resource(format!("feature tags: {e:?}")))?
@@ -196,6 +227,7 @@ impl Decoration {
generation: WorldGenerationContext,
worker: &mut WorkerState,
region: &mut [ProtoChunk; 9],
next_boolean: impl FnMut() -> bool,
) -> Result<DecorateStats, GeneratorError> {
let center = region[4].position();
for (i, chunk) in region.iter().enumerate() {
@@ -234,7 +266,13 @@ impl Decoration {
Ok(terrain) => terrain,
Err(e) => return Err(resource(e.to_string())),
};
let mut next_boolean = next_boolean;
let mut world = World {
next_boolean: &mut next_boolean,
blocks: data
.feature_resources
.as_ref()
.and_then(|r| r.blocks.as_ref()),
region: terrain,
biomes: BiomeRegion::new(biomes, obfuscate_seed(seed))
.map_err(|e| resource(e.to_string()))?,
@@ -287,6 +325,8 @@ impl Decoration {
/// WorldGenRegion-style view: reads anywhere in the 3×3 region, writes within
/// the FEATURES step's write radius, biome lookups through the biome zoom.
struct World<'a> {
next_boolean: &'a mut dyn FnMut() -> bool,
blocks: Option<&'a BlockBehavior>,
region: TerrainRegion<'static, GenBlockStates>,
biomes: BiomeRegion<BiomeId>,
zone: GenerationWriteZone,
@@ -335,7 +375,113 @@ impl FeatureWorld for World<'_> {
fn query(e: impl std::fmt::Display) -> PlacementQueryError {
PlacementQueryError::Failed(e.to_string())
}
impl<'a> World<'a> {
fn blocks(&self) -> Result<&'a BlockBehavior, PlacementQueryError> {
self.blocks.ok_or(PlacementQueryError::Unavailable)
}
}
/// Proto chunks hold no block entities, so dynamic shapes resolve to absent.
impl DynamicSupportWorld for World<'_> {
type Error = PlacementQueryError;
fn shulker_is_closed(&mut self, _: [i32; 3]) -> Result<Option<bool>, PlacementQueryError> {
Ok(None)
}
fn moving_piston_shape(
&mut self,
_: [i32; 3],
) -> Result<Option<VoxelShape>, PlacementQueryError> {
Ok(None)
}
}
impl DynamicCollisionWorld for World<'_> {
fn shulker_collision_state(
&mut self,
_: [i32; 3],
) -> Result<Option<ShulkerCollisionState>, PlacementQueryError> {
Ok(None)
}
}
impl SurvivalWorld for World<'_> {
fn fluid_state(&mut self, position: [i32; 3]) -> Result<FluidState, PlacementQueryError> {
self.region.fluid_state(position)
}
/// Unlit generation chunks report no sky or block light.
fn raw_brightness(&mut self, _: [i32; 3], _: i32) -> Result<i32, PlacementQueryError> {
Ok(0)
}
fn block_state(&mut self, position: [i32; 3]) -> Result<BlockStateId, PlacementQueryError> {
self.region.block_state(position)
}
}
impl PlacementContext for World<'_> {
fn state_collision_empty(
&mut self,
state: BlockStateId,
position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
let collision = self.blocks()?.collision.clone();
collision
.collision_shape(self, state, position)
.map(|shape| shape.is_empty())
.map_err(query)
}
/// Block entities are not stored in proto chunks; loot tables are no-ops.
fn set_block_entity_loot_table(
&mut self,
_: [i32; 3],
_: &str,
_: &mut impl horizon_core::random::RandomSource,
) -> Result<(), PlacementQueryError> {
Ok(())
}
fn attachment_at(
&mut self,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let blocks = self.blocks()?;
blocks
.survival
.can_attach_to(self, position, direction)
.map_err(query)
}
fn next_world_boolean(&mut self) -> Result<bool, PlacementQueryError> {
Ok((self.next_boolean)())
}
fn block_survives(
&mut self,
state: BlockStateId,
position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
let blocks = self.blocks()?;
blocks
.survival
.can_survive(self, state, position)
.map_err(query)
}
fn face_sturdy(
&mut self,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let state = self.region.block_state(position)?;
self.state_face_sturdy(state, position, direction)
}
fn state_face_sturdy(
&mut self,
state: BlockStateId,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let support = self.blocks()?.support.clone();
support
.is_face_sturdy(self, state, position, direction, SupportType::Full)
.map_err(query)
}
/// Generation regions contain no entities.
fn unobstructed_block(&mut self, _: [i32; 3]) -> Result<bool, PlacementQueryError> {
Ok(true)
}
fn destroy_block_without_entity(
&mut self,
position: [i32; 3],
+15
View File
@@ -42,12 +42,27 @@ def prepare_worldgen(root, jars, local):
(out/'block_flags.json').write_text(json.dumps([[s[1], s[2]] for s in facts['states']], separators=(',', ':')))
reports = out/'biome_parameters'
reports.mkdir(exist_ok=True)
presets = reports
for source in [root/'biome-parameters', local/'datagen/out/reports/biome_parameters/minecraft']:
if (source/'overworld.json').exists():
for report in sorted(source.glob('*.json')):
(reports/report.name).write_bytes(report.read_bytes())
break
else:
presets = None
# Block behavior used by feature placement checks (survival, support, collision).
# These come from the Java exporters of the simple-block parity run.
behavior = local/'rust-simple-block-parity'
blocks = out/'blocks'
names = ['block-properties.nbt', 'cached-collision.nbt', 'cached-support.nbt', 'survival-rules.json',
'survival-extra-definitions.json', 'placement-definitions.json']
if all((behavior/name).exists() for name in names):
blocks.mkdir(exist_ok=True)
for name in names:
(blocks/name).write_bytes((behavior/name).read_bytes())
else:
print('Feature block behavior exports missing; run tools/test_simple_block_parity.py for full decoration')
if presets is None:
# Fall back to the Java-exported quantized tables from the material-stage parity run.
presets = local/'rust-material-stage-parity/presets.json'
if not presets.exists():