WIP snapshot: mineshaft and stronghold structures

Uncommitted work from a finished agent worktree on ludothinkpad (/home/ludovic/.t3/scratch/2026-10-03-i-want-you-to-retro-e5fa4461/.claude/worktrees/agent-ac2ea1edb29c4454e), saved before the worktree was removed. Not built or verified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 11:20:05 +02:00
parent 5732ba362c
commit 5159883086
11 changed files with 1957 additions and 10 deletions
@@ -1137,6 +1137,9 @@ where
fn set_valid_biomes(&mut self, biomes: &BTreeSet<BiomeId>) {
self.valid = biomes.clone();
}
fn sea_level(&self) -> i32 {
self.pipeline.settings.sea_level
}
}
enum Biomes<'a, 'b> {
@@ -571,6 +571,17 @@ impl PlacementContext for World<'_> {
.is_face_sturdy(self, state, position, direction, SupportType::Full)
.map_err(query)
}
fn center_sturdy(
&mut self,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let state = self.region.block_state(position)?;
let support = self.blocks()?.support.clone();
support
.is_face_sturdy(self, state, position, direction, SupportType::Center)
.map_err(query)
}
fn collision_full_block(
&mut self,
state: BlockStateId,
@@ -5,14 +5,14 @@ use super::{
generator::{GeneratorData, GeneratorError},
structure::{
StructureResources,
start::{StructureRegistry, StructureStart, beardifier, create_starts},
start::{Rings, StructureRegistry, StructureStart, beardifier, create_starts},
},
};
use horizon_core::{density::Beardifier, position::ChunkPos};
use serde_json::Value;
use std::{
collections::{BTreeSet, HashMap},
sync::{Arc, Mutex},
sync::{Arc, Mutex, OnceLock},
};
pub(super) type Starts = Arc<Vec<Arc<StructureStart>>>;
@@ -24,6 +24,8 @@ pub(super) struct StructureState {
/// Structure indices of each decoration step, in registry order.
pub(super) by_step: Vec<Vec<usize>>,
starts: Mutex<HashMap<(i32, i32), Starts>>,
/// Concentric ring positions, computed on first use.
rings: OnceLock<Rings>,
}
const START_CACHE_LIMIT: usize = 65536;
@@ -85,6 +87,7 @@ impl StructureState {
possible_sets,
by_step,
starts: Mutex::new(HashMap::new()),
rings: OnceLock::new(),
}))
}
/// The (cached) structure starts owned by a chunk.
@@ -96,6 +99,11 @@ impl StructureState {
if let Some(found) = self.starts.lock().unwrap().get(&(chunk.x, chunk.z)) {
return found.clone();
}
let rings = self.rings.get_or_init(|| {
let seed = context.seed();
self.registry
.ring_positions(&self.possible_sets, seed, &mut |q| context.noise_biome(q))
});
let starts: Starts = Arc::new(
create_starts(
&self.registry,
@@ -103,7 +111,7 @@ impl StructureState {
&self.bindings,
context,
&self.possible_sets,
&[],
rings,
chunk,
)
.into_iter()
@@ -237,6 +237,14 @@ pub trait PlacementContext {
) -> Result<bool, PlacementQueryError> {
Err(PlacementQueryError::Unavailable)
}
/// Block.canSupportCenter: CENTER support on the requested face.
fn center_sturdy(
&mut self,
_position: [i32; 3],
_direction: horizon_core::geometry::Direction,
) -> Result<bool, PlacementQueryError> {
Err(PlacementQueryError::Unavailable)
}
/// Test entity obstruction of a unit-block shape with no excluded entity.
fn unobstructed_block(&mut self, _position: [i32; 3]) -> Result<bool, PlacementQueryError> {
Err(PlacementQueryError::Unavailable)
@@ -3,10 +3,12 @@
pub mod features;
pub mod jigsaw;
pub mod legacy;
pub mod mineshaft;
pub mod ocean_ruin;
pub mod processor;
pub mod simple;
pub mod start;
pub mod stronghold;
pub mod template;
use crate::{
@@ -11,6 +11,7 @@ use crate::{
nbt::{Compound, JavaString, Tag},
registry::BlockStateId,
worldgen::{
biome::BiomeId,
feature::FeatureWorld,
placement::{PlacementContext, PlacementQueryError},
},
@@ -48,6 +49,10 @@ pub trait PieceWorld {
fn max_y(&mut self) -> Result<i32>;
fn block_entity(&mut self, pos: [i32; 3], nbt: Compound) -> Result<()>;
fn post_process(&mut self, pos: [i32; 3]) -> Result<()>;
fn face_sturdy(&mut self, pos: [i32; 3], face: Direction) -> Result<bool>;
fn center_sturdy(&mut self, pos: [i32; 3], face: Direction) -> Result<bool>;
/// WorldGenLevel.getBiome (zoomed).
fn biome(&mut self, pos: [i32; 3]) -> Result<BiomeId>;
fn place_template(
&mut self,
resources: &StructureResources,
@@ -85,6 +90,15 @@ impl<W: FeatureWorld + PlacementContext> PieceWorld for W {
fn post_process(&mut self, pos: [i32; 3]) -> Result<()> {
self.mark_postprocessing(pos)
}
fn face_sturdy(&mut self, pos: [i32; 3], face: Direction) -> Result<bool> {
PlacementContext::face_sturdy(self, pos, face)
}
fn center_sturdy(&mut self, pos: [i32; 3], face: Direction) -> Result<bool> {
PlacementContext::center_sturdy(self, pos, face)
}
fn biome(&mut self, pos: [i32; 3]) -> Result<BiomeId> {
self.biome_identity(pos)
}
fn place_template(
&mut self,
resources: &StructureResources,
@@ -170,6 +184,18 @@ impl PieceContext<'_> {
nbt.insert("LootTableSeed".into(), Tag::Long(seed));
self.world.block_entity(pos, nbt)
}
/// Place a spawner and set its entity (SpawnerBlockEntity.setEntityId).
pub fn spawner(&mut self, pos: [i32; 3], entity: &str) -> Result<()> {
self.world.set(pos, self.state("spawner"), 2)?;
let mut id = Compound::new();
id.insert("id".into(), Tag::String(entity.into()));
let mut data = Compound::new();
data.insert("entity".into(), Tag::Compound(id));
let mut nbt = Compound::new();
nbt.insert("id".into(), Tag::String("minecraft:mob_spawner".into()));
nbt.insert("SpawnData".into(), Tag::Compound(data));
self.world.block_entity(pos, nbt)
}
}
/// A state by block name and properties (missing properties keep defaults).
pub fn state(
@@ -213,6 +239,8 @@ pub struct PieceFrame {
pub orientation: Option<Direction>,
pub mirror: Mirror,
pub rotation: Rotation,
/// Blocks placeBlock must not replace (StructurePiece.canBeReplaced).
pub keep: &'static [&'static str],
}
pub const HORIZONTAL: [Direction; 4] = [
Direction::North,
@@ -252,6 +280,7 @@ impl PieceFrame {
orientation,
mirror,
rotation,
keep: &[],
}
}
pub fn world_x(&self, x: i32, z: i32) -> i32 {
@@ -293,6 +322,12 @@ impl PieceFrame {
if !c.chunk_box.is_inside(pos) {
return Ok(());
}
if !self.keep.is_empty() {
let current = c.world.block(pos)?;
if self.keep.contains(&c.name(current)) {
return Ok(());
}
}
let mut state = state;
if self.mirror != Mirror::None {
state = c.resources.transforms.mirror(state, self.mirror);
@@ -551,7 +586,7 @@ pub fn offset(pos: [i32; 3], d: Direction, n: i32) -> [i32; 3] {
let s = d.normal();
[pos[0] + s[0] * n, pos[1] + s[1] * n, pos[2] + s[2] * n]
}
fn solid_render(c: &PieceContext<'_>, state: BlockStateId) -> bool {
pub fn solid_render(c: &PieceContext<'_>, state: BlockStateId) -> bool {
c.resources.transforms.full_block(state) && !c.is_liquid(state)
}
/// StructurePiece.createChest with an absolute position.
@@ -0,0 +1,743 @@
//! Mineshafts: MineshaftStructure and MineshaftPieces.
use super::{
BoundingBox,
legacy::{LegacyPiece, PieceContext, PieceFrame, Result, solid_render},
};
use crate::worldgen::biome::BiomeId;
use horizon_core::{geometry::Direction, random::RandomSource};
use std::{
collections::BTreeSet,
sync::{Arc, Mutex},
};
/// MineshaftStructure.Type: wood, planks, fence, and the blocks pieces keep.
#[derive(Clone, Copy, Debug)]
pub struct Wood {
log: &'static str,
planks: &'static str,
fence: &'static str,
keep: &'static [&'static str],
}
pub const NORMAL: Wood = Wood {
log: "minecraft:oak_log",
planks: "minecraft:oak_planks",
fence: "minecraft:oak_fence",
keep: &[
"minecraft:oak_planks",
"minecraft:oak_log",
"minecraft:oak_fence",
"minecraft:iron_chain",
],
};
pub const MESA: Wood = Wood {
log: "minecraft:dark_oak_log",
planks: "minecraft:dark_oak_planks",
fence: "minecraft:dark_oak_fence",
keep: &[
"minecraft:dark_oak_planks",
"minecraft:dark_oak_log",
"minecraft:dark_oak_fence",
"minecraft:iron_chain",
],
};
#[derive(Debug)]
enum Kind {
Room(Vec<BoundingBox>),
Corridor {
rails: bool,
spider: bool,
sections: i32,
placed_spider: Mutex<bool>,
},
Crossing {
direction: Direction,
two_floored: bool,
},
Stairs,
}
#[derive(Debug)]
pub struct MineshaftPiece {
kind: Kind,
frame: PieceFrame,
depth: i32,
wood: Wood,
blocking: Arc<BTreeSet<BiomeId>>,
}
fn int(r: &mut impl RandomSource, bound: i32) -> i32 {
r.next_int_bound(bound).unwrap_or(0)
}
fn bb(a: [i32; 3], b: [i32; 3], at: [i32; 3]) -> BoundingBox {
BoundingBox::new(a, b).moved(at)
}
struct Builder {
pieces: Vec<MineshaftPiece>,
}
impl Builder {
fn collides(&self, b: &BoundingBox) -> bool {
self.pieces
.iter()
.any(|p| p.frame.bounding_box.intersects(b))
}
fn piece(
&self,
kind: Kind,
b: BoundingBox,
o: Option<Direction>,
depth: i32,
) -> MineshaftPiece {
let start = &self.pieces[0];
let mut frame = PieceFrame::new(b, o);
frame.keep = start.wood.keep;
MineshaftPiece {
kind,
frame,
depth,
wood: start.wood,
blocking: start.blocking.clone(),
}
}
/// MineshaftPieces.createRandomShaftPiece.
fn create(
&self,
r: &mut impl RandomSource,
at: [i32; 3],
d: Direction,
depth: i32,
) -> Option<MineshaftPiece> {
let selection = int(r, 100);
if selection >= 80 {
let y1 = if int(r, 4) == 0 { 6 } else { 2 };
let b = match d {
Direction::South => bb([-1, 0, 0], [3, y1, 4], at),
Direction::West => bb([-4, 0, -1], [0, y1, 3], at),
Direction::East => bb([0, 0, -1], [4, y1, 3], at),
_ => bb([-1, 0, -4], [3, y1, 0], at),
};
if self.collides(&b) {
return None;
}
let kind = Kind::Crossing {
direction: d,
two_floored: b.span()[1] > 3,
};
Some(self.piece(kind, b, None, depth))
} else if selection >= 70 {
let b = match d {
Direction::South => bb([0, -5, 0], [2, 2, 8], at),
Direction::West => bb([-8, -5, 0], [0, 2, 2], at),
Direction::East => bb([0, -5, 0], [8, 2, 2], at),
_ => bb([0, -5, -8], [2, 2, 0], at),
};
(!self.collides(&b)).then(|| self.piece(Kind::Stairs, b, Some(d), depth))
} else {
let mut length = int(r, 3) + 2;
while length > 0 {
let l = length * 5 - 1;
let b = match d {
Direction::South => bb([0, 0, 0], [2, 2, l], at),
Direction::West => bb([-l, 0, 0], [0, 2, 2], at),
Direction::East => bb([0, 0, 0], [l, 2, 2], at),
_ => bb([0, 0, -l], [2, 2, 0], at),
};
if !self.collides(&b) {
let rails = int(r, 3) == 0;
let spider = !rails && int(r, 23) == 0;
let axis = if matches!(d, Direction::North | Direction::South) {
2
} else {
0
};
let kind = Kind::Corridor {
rails,
spider,
sections: b.span()[axis] / 5,
placed_spider: Mutex::new(false),
};
return Some(self.piece(kind, b, Some(d), depth));
}
length -= 1;
}
None
}
}
/// MineshaftPieces.generateAndAddPiece; returns the new piece's box.
fn add(
&mut self,
r: &mut impl RandomSource,
at: [i32; 3],
d: Direction,
depth: i32,
) -> Option<BoundingBox> {
if depth > 8 {
return None;
}
let start = self.pieces[0].frame.bounding_box;
if (at[0] - start.min[0]).abs() > 80 || (at[2] - start.min[2]).abs() > 80 {
return None;
}
let piece = self.create(r, at, d, depth + 1)?;
let b = piece.frame.bounding_box;
self.pieces.push(piece);
self.add_children(r, self.pieces.len() - 1);
Some(b)
}
fn add_children(&mut self, r: &mut impl RandomSource, index: usize) {
let p = &self.pieces[index];
let (b, depth, orientation) = (p.frame.bounding_box, p.depth, p.frame.orientation);
let ([x0, y0, z0], [x1, y1, z1]) = (b.min, b.max);
use Direction::*;
match &p.kind {
Kind::Room(_) => {
let height = (b.span()[1] - 4).max(1);
let [xs, _, zs] = b.span();
for side in 0..4 {
let span = if side < 2 { xs } else { zs };
let mut pos = 0;
while pos < span {
pos += int(r, span);
if pos + 3 > span {
break;
}
let y = y0 + int(r, height) + 1;
let (at, d) = match side {
0 => ([x0 + pos, y, z0 - 1], North),
1 => ([x0 + pos, y, z1 + 1], South),
2 => ([x0 - 1, y, z0 + pos], West),
_ => ([x1 + 1, y, z0 + pos], East),
};
if let Some(c) = self.add(r, at, d, depth) {
let entrance = match side {
0 => BoundingBox::new(
[c.min[0], c.min[1], z0],
[c.max[0], c.max[1], z0 + 1],
),
1 => BoundingBox::new(
[c.min[0], c.min[1], z1 - 1],
[c.max[0], c.max[1], z1],
),
2 => BoundingBox::new(
[x0, c.min[1], c.min[2]],
[x0 + 1, c.max[1], c.max[2]],
),
_ => BoundingBox::new(
[x1 - 1, c.min[1], c.min[2]],
[x1, c.max[1], c.max[2]],
),
};
if let Kind::Room(entrances) = &mut self.pieces[index].kind {
entrances.push(entrance);
}
}
pos += 4;
}
}
}
Kind::Corridor { .. } => {
let end = int(r, 4);
let o = orientation.unwrap_or(North);
let (forward, left, right) = match o {
South => (
[x0, z1 + 1],
(West, [x0 - 1, z1 - 3]),
(East, [x1 + 1, z1 - 3]),
),
West => ([x0 - 1, z0], (North, [x0, z0 - 1]), (South, [x0, z1 + 1])),
East => (
[x1 + 1, z0],
(North, [x1 - 3, z0 - 1]),
(South, [x1 - 3, z1 + 1]),
),
_ => ([x0, z0 - 1], (West, [x0 - 1, z0]), (East, [x1 + 1, z0])),
};
let (d, [x, z]) = match end {
0 | 1 => (o, forward),
2 => left,
_ => right,
};
let y = y0 - 1 + int(r, 3);
self.add(r, [x, y, z], d, depth);
if depth < 8 {
if o != North && o != South {
let mut x = x0 + 3;
while x + 3 <= x1 {
match int(r, 5) {
0 => {
self.add(r, [x, y0, z0 - 1], North, depth + 1);
}
1 => {
self.add(r, [x, y0, z1 + 1], South, depth + 1);
}
_ => {}
}
x += 5;
}
} else {
let mut z = z0 + 3;
while z + 3 <= z1 {
match int(r, 5) {
0 => {
self.add(r, [x0 - 1, y0, z], West, depth + 1);
}
1 => {
self.add(r, [x1 + 1, y0, z], East, depth + 1);
}
_ => {}
}
z += 5;
}
}
}
}
Kind::Crossing {
direction,
two_floored,
} => {
let two = *two_floored;
let n = ([x0 + 1, y0, z0 - 1], North);
let s = ([x0 + 1, y0, z1 + 1], South);
let w = ([x0 - 1, y0, z0 + 1], West);
let e = ([x1 + 1, y0, z0 + 1], East);
let order = match direction {
South => [s, w, e],
West => [n, s, w],
East => [n, s, e],
_ => [n, w, e],
};
for (at, d) in order {
self.add(r, at, d, depth);
}
if two {
for (at, d) in [n, w, e, s] {
if r.next_boolean() {
self.add(r, [at[0], y0 + 4, at[2]], d, depth);
}
}
}
}
Kind::Stairs => {
let (at, d) = match orientation.unwrap_or(North) {
South => ([x0, y0, z1 + 1], South),
West => ([x0 - 1, y0, z0], West),
East => ([x1 + 1, y0, z0], East),
_ => ([x0, y0, z0 - 1], North),
};
self.add(r, at, d, depth);
}
}
}
}
/// MineshaftStructure.findGenerationPoint: the pieces and the start position.
pub fn generate(
r: &mut impl RandomSource,
chunk: [i32; 2],
mesa: bool,
blocking: Arc<BTreeSet<BiomeId>>,
sea_level: i32,
min_y: i32,
surface: &mut dyn FnMut(i32, i32) -> i32,
) -> ([i32; 3], Vec<MineshaftPiece>) {
r.next_double();
let (west, north) = (chunk[0] * 16 + 2, chunk[1] * 16 + 2);
let room = BoundingBox::new(
[west, 50, north],
[west + 7 + int(r, 6), 54 + int(r, 6), north + 7 + int(r, 6)],
);
let wood = if mesa { MESA } else { NORMAL };
let mut frame = PieceFrame::new(room, None);
frame.keep = wood.keep;
let mut builder = Builder {
pieces: vec![MineshaftPiece {
kind: Kind::Room(Vec::new()),
frame,
depth: 0,
wood,
blocking,
}],
};
builder.add_children(r, 0);
let mut all = builder.pieces[0].frame.bounding_box;
for p in &builder.pieces[1..] {
all.encapsulate(&p.frame.bounding_box);
}
let dy = if mesa {
let center = all.center();
let height = surface(center[0], center[2]);
let target = if height <= sea_level {
sea_level
} else {
int(r, height - sea_level + 1) + sea_level
};
target - center[1]
} else {
let max = sea_level - 10;
let mut y1 = all.span()[1] + min_y + 1;
if y1 < max {
y1 += int(r, max - y1);
}
y1 - all.max[1]
};
for p in &mut builder.pieces {
p.frame.bounding_box = p.frame.bounding_box.moved([0, dy, 0]);
if let Kind::Room(entrances) = &mut p.kind {
for e in entrances {
*e = e.moved([0, dy, 0]);
}
}
}
([chunk[0] * 16 + 8, 50 + dy, chunk[1] * 16], builder.pieces)
}
fn replaceable(name: &str) -> bool {
matches!(
name,
"minecraft:air"
| "minecraft:cave_air"
| "minecraft:void_air"
| "minecraft:water"
| "minecraft:lava"
| "minecraft:glow_lichen"
| "minecraft:seagrass"
| "minecraft:tall_seagrass"
)
}
fn falling(name: &str) -> bool {
matches!(
name,
"minecraft:sand"
| "minecraft:red_sand"
| "minecraft:gravel"
| "minecraft:anvil"
| "minecraft:chipped_anvil"
| "minecraft:damaged_anvil"
| "minecraft:dragon_egg"
) || name.ends_with("_concrete_powder")
}
impl MineshaftPiece {
fn invalid(&self, c: &mut PieceContext<'_>) -> Result<bool> {
let (b, k) = (self.frame.bounding_box, c.chunk_box);
let lo: [i32; 3] = std::array::from_fn(|i| (b.min[i] - 1).max(k.min[i]));
let hi: [i32; 3] = std::array::from_fn(|i| (b.max[i] + 1).min(k.max[i]));
let center = std::array::from_fn(|i| (lo[i] + hi[i]) / 2);
if self.blocking.contains(&c.world.biome(center)?) {
return Ok(true);
}
let liquid = |c: &mut PieceContext<'_>, p: [i32; 3]| -> Result<bool> {
let s = c.world.block(p)?;
Ok(c.is_liquid(s))
};
for x in lo[0]..=hi[0] {
for z in lo[2]..=hi[2] {
if liquid(c, [x, lo[1], z])? || liquid(c, [x, hi[1], z])? {
return Ok(true);
}
}
}
for x in lo[0]..=hi[0] {
for y in lo[1]..=hi[1] {
if liquid(c, [x, y, lo[2]])? || liquid(c, [x, y, hi[2]])? {
return Ok(true);
}
}
}
for z in lo[2]..=hi[2] {
for y in lo[1]..=hi[1] {
if liquid(c, [lo[0], y, z])? || liquid(c, [hi[0], y, z])? {
return Ok(true);
}
}
}
Ok(false)
}
fn set_planks(&self, c: &mut PieceContext<'_>, x: i32, y: i32, z: i32) -> Result<()> {
if self.frame.is_interior(c, x, y, z)? {
let pos = self.frame.world_pos(x, y, z);
if !c.world.face_sturdy(pos, Direction::Up)? {
c.world.set(pos, c.state(self.wood.planks), 2)?;
}
}
Ok(())
}
fn air_box(&self, c: &mut PieceContext<'_>, a: [i32; 3], b: [i32; 3]) -> Result<()> {
let air = c.state("cave_air");
self.frame.generate_box(c, a, b, air, air, false)
}
fn room(&self, c: &mut PieceContext<'_>, entrances: &[BoundingBox]) -> Result<()> {
let b = self.frame.bounding_box;
self.air_box(
c,
[b.min[0], b.min[1] + 1, b.min[2]],
[b.max[0], (b.min[1] + 3).min(b.max[1]), b.max[2]],
)?;
for e in entrances {
self.air_box(c, [e.min[0], e.max[1] - 2, e.min[2]], e.max)?;
}
let air = c.state("cave_air");
self.frame
.upper_half_sphere(c, [b.min[0], b.min[1] + 4, b.min[2]], b.max, air, false)
}
fn crossing(&self, c: &mut PieceContext<'_>, two_floored: bool) -> Result<()> {
let ([x0, y0, z0], [x1, y1, z1]) =
(self.frame.bounding_box.min, self.frame.bounding_box.max);
if two_floored {
self.air_box(c, [x0 + 1, y0, z0], [x1 - 1, y0 + 2, z1])?;
self.air_box(c, [x0, y0, z0 + 1], [x1, y0 + 2, z1 - 1])?;
self.air_box(c, [x0 + 1, y1 - 2, z0], [x1 - 1, y1, z1])?;
self.air_box(c, [x0, y1 - 2, z0 + 1], [x1, y1, z1 - 1])?;
self.air_box(c, [x0 + 1, y0 + 3, z0 + 1], [x1 - 1, y0 + 3, z1 - 1])?;
} else {
self.air_box(c, [x0 + 1, y0, z0], [x1 - 1, y1, z1])?;
self.air_box(c, [x0, y0, z0 + 1], [x1, y1, z1 - 1])?;
}
let planks = c.state(self.wood.planks);
let air = c.state("cave_air");
for (x, z) in [
(x0 + 1, z0 + 1),
(x0 + 1, z1 - 1),
(x1 - 1, z0 + 1),
(x1 - 1, z1 - 1),
] {
let above = self.frame.get(c, x, y1 + 1, z)?;
if !c.is_air(above) {
self.frame
.generate_box(c, [x, y0, z], [x, y1, z], planks, air, false)?;
}
}
for x in x0..=x1 {
for z in z0..=z1 {
self.set_planks(c, x, y0 - 1, z)?;
}
}
Ok(())
}
fn stairs(&self, c: &mut PieceContext<'_>) -> Result<()> {
self.air_box(c, [0, 5, 0], [2, 7, 1])?;
self.air_box(c, [0, 0, 7], [2, 2, 8])?;
for i in 0..5 {
self.air_box(c, [0, 5 - i - i32::from(i < 4), 2 + i], [2, 7 - i, 2 + i])?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn corridor(
&self,
c: &mut PieceContext<'_>,
rails: bool,
spider: bool,
sections: i32,
placed_spider: &Mutex<bool>,
) -> Result<()> {
let f = self.frame;
let length = sections * 5 - 1;
let air = c.state("cave_air");
let web = c.state("cobweb");
f.generate_box(c, [0, 0, 0], [2, 1, length], air, air, false)?;
f.generate_maybe_box(c, 0.8, [0, 2, 0], [2, 2, length], air, air, false, false)?;
if spider {
f.generate_maybe_box(c, 0.6, [0, 0, 0], [2, 1, length], web, air, false, true)?;
}
for section in 0..sections {
let z = 2 + section * 5;
self.support(c, z)?;
for (p, x, dz) in [
(0.1, 0, -1),
(0.1, 2, -1),
(0.1, 0, 1),
(0.1, 2, 1),
(0.05, 0, -2),
(0.05, 2, -2),
(0.05, 0, 2),
(0.05, 2, 2),
] {
if f.is_interior(c, x, 2, z + dz)?
&& c.random.float() < p
&& self.sturdy_neighbours(c, [x, 2, z + dz])?
{
f.place(c, web, x, 2, z + dz)?;
}
}
if c.random.int(100) == 0 {
self.minecart_chest(c, 2, 0, z - 1)?;
}
if c.random.int(100) == 0 {
self.minecart_chest(c, 0, 0, z + 1)?;
}
if spider && !*placed_spider.lock().unwrap() {
let nz = z - 1 + c.random.int(3);
let pos = f.world_pos(1, 0, nz);
if c.chunk_box.is_inside(pos) && f.is_interior(c, 1, 0, nz)? {
*placed_spider.lock().unwrap() = true;
c.spawner(pos, "minecraft:cave_spider")?;
}
}
}
for x in 0..=2 {
for z in 0..=length {
self.set_planks(c, x, -1, z)?;
}
}
self.double_support(c, 2)?;
if sections > 1 {
self.double_support(c, length - 2)?;
}
if rails {
let rail = c.state_with("rail", &[("shape", "north_south")]);
for z in 0..=length {
let floor = f.get(c, 1, -1, z)?;
if !c.is_air(floor) && solid_render(c, floor) {
let p = if f.is_interior(c, 1, 0, z)? { 0.7 } else { 0.9 };
f.maybe_block(c, p, 1, 0, z, rail)?;
}
}
}
Ok(())
}
/// MineShaftCorridor.createChest: a rail with a chest minecart.
fn minecart_chest(&self, c: &mut PieceContext<'_>, x: i32, y: i32, z: i32) -> Result<()> {
let pos = self.frame.world_pos(x, y, z);
if !c.chunk_box.is_inside(pos) {
return Ok(());
}
let here = c.world.block(pos)?;
let below = c.world.block([pos[0], pos[1] - 1, pos[2]])?;
if c.is_air(here) && !c.is_air(below) {
let shape = if c.random.boolean() {
"north_south"
} else {
"east_west"
};
let rail = c.state_with("rail", &[("shape", shape)]);
self.frame.place(c, rail, x, y, z)?;
// The chest minecart entity (loot table seed drawn here) is not
// stored: worldgen output carries no entities.
c.random.long();
}
Ok(())
}
/// MineShaftCorridor.placeSupport(x0 0, y0 0, z, y1 2, x1 2).
fn support(&self, c: &mut PieceContext<'_>, z: i32) -> Result<()> {
let f = self.frame;
for x in 0..=2 {
let above = f.get(c, x, 3, z)?;
if c.is_air(above) {
return Ok(());
}
}
let air = c.state("cave_air");
let planks = c.state(self.wood.planks);
let west = c.state_with(self.wood.fence, &[("west", "true")]);
let east = c.state_with(self.wood.fence, &[("east", "true")]);
f.generate_box(c, [0, 0, z], [0, 1, z], west, air, false)?;
f.generate_box(c, [2, 0, z], [2, 1, z], east, air, false)?;
if c.random.int(4) == 0 {
f.generate_box(c, [0, 2, z], [0, 2, z], planks, air, false)?;
f.generate_box(c, [2, 2, z], [2, 2, z], planks, air, false)?;
} else {
f.generate_box(c, [0, 2, z], [2, 2, z], planks, air, false)?;
let south = c.state_with("wall_torch", &[("facing", "south")]);
let north = c.state_with("wall_torch", &[("facing", "north")]);
f.maybe_block(c, 0.05, 1, 2, z - 1, south)?;
f.maybe_block(c, 0.05, 1, 2, z + 1, north)?;
}
Ok(())
}
fn sturdy_neighbours(&self, c: &mut PieceContext<'_>, [x, y, z]: [i32; 3]) -> Result<bool> {
let pos = self.frame.world_pos(x, y, z);
let mut count = 0;
for d in Direction::ALL {
let n = super::legacy::offset(pos, d, 1);
if c.chunk_box.is_inside(n) && c.world.face_sturdy(n, d.opposite())? {
count += 1;
if count >= 2 {
return Ok(true);
}
}
}
Ok(false)
}
fn double_support(&self, c: &mut PieceContext<'_>, z: i32) -> Result<()> {
for x in [0, 2] {
let s = self.frame.get(c, x, -1, z)?;
if c.name(s) == self.wood.planks {
self.pillar_or_chain(c, x, -1, z)?;
}
}
Ok(())
}
/// MineShaftCorridor.fillPillarDownOrChainUp.
fn pillar_or_chain(&self, c: &mut PieceContext<'_>, x: i32, y: i32, z: i32) -> Result<()> {
let [px, wy, pz] = self.frame.world_pos(x, y, z);
if !c.chunk_box.is_inside([px, wy, pz]) {
return Ok(());
}
let (min, max) = (c.world.min_y()?, c.world.max_y()?);
let (mut below, mut above) = (true, true);
let mut distance = 1;
while below || above {
if below {
let p = [px, wy - distance, pz];
let s = c.world.block(p)?;
let name = c.name(s).to_owned();
let empty = replaceable(&name) && name != "minecraft:lava";
if !empty && c.world.face_sturdy(p, Direction::Up)? {
let log = c.state(self.wood.log);
for py in wy - distance + 1..wy {
c.world.set([px, py, pz], log, 2)?;
}
return Ok(());
}
below = distance <= 20 && empty && p[1] > min + 1;
}
if above {
let p = [px, wy + distance, pz];
let s = c.world.block(p)?;
let name = c.name(s).to_owned();
let empty = replaceable(&name);
if !empty && c.world.center_sturdy(p, Direction::Down)? && !falling(&name) {
c.world.set([px, wy + 1, pz], c.state(self.wood.fence), 2)?;
let chain = c.state("iron_chain");
for py in wy + 2..wy + distance {
c.world.set([px, py, pz], chain, 2)?;
}
return Ok(());
}
above = distance <= 50 && empty && p[1] < max;
}
distance += 1;
}
Ok(())
}
}
impl LegacyPiece for MineshaftPiece {
fn bounding_box(&self) -> BoundingBox {
self.frame.bounding_box
}
fn type_name(&self) -> &'static str {
match self.kind {
Kind::Room(_) => "minecraft:msroom",
Kind::Corridor { .. } => "minecraft:mscorridor",
Kind::Crossing { .. } => "minecraft:mscrossing",
Kind::Stairs => "minecraft:msstairs",
}
}
fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> {
if self.invalid(c)? {
return Ok(());
}
match &self.kind {
Kind::Room(entrances) => self.room(c, entrances),
Kind::Crossing { two_floored, .. } => self.crossing(c, *two_floored),
Kind::Stairs => self.stairs(c),
Kind::Corridor {
rails,
spider,
sections,
placed_spider,
} => self.corridor(c, *rails, *spider, *sections, placed_spider),
}
}
}
@@ -70,6 +70,12 @@ pub enum StructureKind {
large: f32,
cluster: f32,
},
Mineshaft {
mesa: bool,
/// #minecraft:mineshaft_blocking
blocking: Arc<BTreeSet<BiomeId>>,
},
Stronghold,
/// A structure type whose generator is not implemented yet.
Unsupported(String),
}
@@ -95,9 +101,16 @@ enum Placement {
separation: i32,
triangular: bool,
},
ConcentricRings,
ConcentricRings {
distance: i32,
spread: i32,
count: i32,
preferred: BTreeSet<BiomeId>,
},
Unsupported,
}
/// Concentric ring chunk positions by structure set name.
pub type Rings = BTreeMap<String, Vec<ChunkPos>>;
#[derive(Debug)]
pub struct StructureSet {
pub name: String,
@@ -183,6 +196,13 @@ impl StructureRegistry {
large: v["large_probability"].as_f64().unwrap_or(0.) as f32,
cluster: v["cluster_probability"].as_f64().unwrap_or(0.) as f32,
},
"minecraft:mineshaft" => StructureKind::Mineshaft {
mesa: v["mineshaft_type"].as_str() == Some("mesa"),
blocking: Arc::new(biome_set(&Value::String(
"#minecraft:mineshaft_blocking".into(),
))?),
},
"minecraft:stronghold" => StructureKind::Stronghold,
other => StructureKind::Unsupported(other.to_owned()),
};
defs.push(StructureDef {
@@ -207,7 +227,12 @@ impl StructureRegistry {
separation: p["separation"].as_i64().unwrap_or(0) as i32,
triangular: p["spread_type"].as_str() == Some("triangular"),
},
"minecraft:concentric_rings" => Placement::ConcentricRings,
"minecraft:concentric_rings" => Placement::ConcentricRings {
distance: p["distance"].as_i64().unwrap_or(0) as i32,
spread: p["spread"].as_i64().unwrap_or(0) as i32,
count: p["count"].as_i64().unwrap_or(0) as i32,
preferred: biome_set(&p["preferred_biomes"])?,
},
_ => Placement::Unsupported,
};
out.push(StructureSet {
@@ -246,6 +271,32 @@ impl StructureRegistry {
pools: Pools::new(pools),
})
}
/// ChunkGeneratorStructureState ring positions of the concentric-ring
/// sets among `possible_sets`.
pub fn ring_positions(
&self,
possible_sets: &[usize],
seed: i64,
biome: &mut dyn FnMut([i32; 3]) -> BiomeId,
) -> Rings {
let mut rings = Rings::new();
for &i in possible_sets {
let set = &self.sets[i];
if let Placement::ConcentricRings {
distance,
spread,
count,
preferred,
} = &set.placement
{
let positions = super::stronghold::ring_positions(
seed, *distance, *spread, *count, preferred, biome,
);
rings.insert(set.name.clone(), positions);
}
}
rings
}
/// RandomSpreadStructurePlacement.getPotentialStructureChunk et al.
pub fn is_structure_chunk(
&self,
@@ -253,7 +304,7 @@ impl StructureRegistry {
seed: i64,
x: i32,
z: i32,
rings: &[ChunkPos],
rings: &Rings,
) -> bool {
let placed = match set.placement {
Placement::RandomSpread {
@@ -278,7 +329,9 @@ impl StructureRegistry {
let sz = spread(&mut random);
gx * spacing + sx == x && gz * spacing + sz == z
}
Placement::ConcentricRings => rings.contains(&ChunkPos::new(x, z)),
Placement::ConcentricRings { .. } => rings
.get(&set.name)
.is_some_and(|r| r.contains(&ChunkPos::new(x, z))),
Placement::Unsupported => false,
};
if !placed {
@@ -399,6 +452,7 @@ pub trait StartContext: JigsawContext {
/// Noise biome at a quart position (caching resolver, no zoom).
fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId;
fn set_valid_biomes(&mut self, biomes: &BTreeSet<BiomeId>);
fn sea_level(&self) -> i32;
}
/// ChunkGenerator.createStructures for one chunk: the starts it owns.
@@ -408,7 +462,7 @@ pub fn create_starts(
bindings: &FeatureBlockBindings<'_>,
context: &mut impl StartContext,
possible_sets: &[usize],
rings: &[ChunkPos],
rings: &Rings,
chunk: ChunkPos,
) -> Vec<StructureStart> {
let seed = context.seed();
@@ -581,6 +635,25 @@ fn try_generate(
)?;
(stub, legacy(pieces))
}
StructureKind::Mineshaft { mesa, blocking } => {
let (sea, min) = (context.sea_level(), context.min_y());
let (position, pieces) = super::mineshaft::generate(
&mut random,
[chunk.x, chunk.z],
*mesa,
blocking.clone(),
sea,
min,
&mut |x, z| context.base_height(x, z, HeightmapType::WorldSurfaceWg),
);
(position, legacy(pieces))
}
StructureKind::Stronghold => {
let (sea, min) = (context.sea_level(), context.min_y());
let pieces =
super::stronghold::generate(&mut random, seed, [chunk.x, chunk.z], sea, min);
([chunk.x * 16, 0, chunk.z * 16], legacy(pieces))
}
StructureKind::Unsupported(_) => return None,
};
let quart = position.map(|v| v >> 2);
File diff suppressed because it is too large Load Diff
@@ -58,6 +58,9 @@ public final class VanillaStructureStartOracle {
var structures=world.lookupOrThrow(Registries.STRUCTURE);
try(var w=new PrintWriter(Files.newBufferedWriter(out,StandardCharsets.UTF_8))) {
structures.listElements().forEach(h->w.println("registry "+h.key().identifier()+" "+h.value().step().ordinal()));
if(System.getenv("HORIZON_RINGS")!=null)for(var set:state.possibleStructureSets())
if(set.value().placement() instanceof net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement rings)
for(var p:state.getRingPositionsFor(rings))w.println("ring "+set.unwrapKey().get().identifier()+" "+p.x()+" "+p.z());
if(System.getenv("HORIZON_HEIGHTS")!=null)for(String p:System.getenv("HORIZON_HEIGHTS").split(";")){
String[] xz=p.split(",");int x=Integer.parseInt(xz[0]),z=Integer.parseInt(xz[1]);
int floor=generator.getBaseHeight(x,z,Heightmap.Types.OCEAN_FLOOR_WG,height,randomState),surface=generator.getBaseHeight(x,z,Heightmap.Types.WORLD_SURFACE_WG,height,randomState);
+2 -1
View File
@@ -5,6 +5,7 @@ usage: structure_start_oracle.py OUT SEED X0 Z0 X1 Z1
"""
import os
import subprocess
from pathlib import Path
import sys
try:
from . import lab, test_rust_parity as base
@@ -17,7 +18,7 @@ def main():
out, seed, x0, z0, x1, z1 = sys.argv[1:7]
lock, jars, libraries = base.verify_artifacts()
source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureStartOracle.java'
build = lab.LOCAL/'structure-start-oracle'
build = Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'structure-start-oracle'
classes = build/'classes'
classes.mkdir(parents=True, exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))