Add piece-based structures: buried treasure, igloo, swamp hut, shipwreck, ocean ruin

Port StructurePiece's orientation frame and block helpers, template pieces
with data markers, chest/dispenser loot block entities and the five
smaller legacy structures. Structure stubs use the chunk middle (block 8).
For seed 0 over 97x97 chunks all 35 starts of implemented structure types
match the vanilla oracle (pieces, boxes, positions).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 03:39:16 +02:00
parent c5fc4d7eb5
commit 5732ba362c
8 changed files with 1851 additions and 5 deletions
@@ -174,7 +174,20 @@ fn dump_starts(
s.pieces.len()
));
for piece in &s.pieces {
let Piece::Pool(p) = piece;
let Piece::Pool(p) = piece else {
let b = piece.bounding_box();
lines.push(format!(
"piece {} {} {} {} {} {} {}",
piece.type_name(),
b.min[0],
b.min[1],
b.min[2],
b.max[0],
b.max[1],
b.max[2]
));
continue;
};
let b = p.bounding_box;
let rotation = match p.rotation {
Rotation::None => "NONE",
@@ -2,7 +2,10 @@
//! and structure pieces.
pub mod features;
pub mod jigsaw;
pub mod legacy;
pub mod ocean_ruin;
pub mod processor;
pub mod simple;
pub mod start;
pub mod template;
@@ -0,0 +1,818 @@
//! Piece-based ("legacy") structure support: the StructurePiece helpers,
//! object-safe world/random access and template pieces.
use super::{
BlockInfo, BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate,
processor::{PlaceSettings, Processor, ProcessorList, ProcessorRandom, place_in_world},
};
use crate::{
chunk::BlockState,
fluid::FluidState,
heightmap::HeightmapType,
nbt::{Compound, JavaString, Tag},
registry::BlockStateId,
worldgen::{
feature::FeatureWorld,
placement::{PlacementContext, PlacementQueryError},
},
};
use horizon_core::{
geometry::Direction,
position::{BlockPos, ChunkPos},
random::{LegacyRandom, RandomSource, position_seed},
};
use std::sync::{Arc, Mutex};
pub type Result<T> = std::result::Result<T, PlacementQueryError>;
/// The random draws legacy pieces make.
pub trait PieceRandom: ProcessorRandom {
fn boolean(&mut self) -> bool;
fn double(&mut self) -> f64;
}
impl<R: RandomSource> PieceRandom for R {
fn boolean(&mut self) -> bool {
self.next_boolean()
}
fn double(&mut self) -> f64 {
self.next_double()
}
}
/// Object-safe world access for piece post-processing.
pub trait PieceWorld {
fn block(&mut self, pos: [i32; 3]) -> Result<BlockStateId>;
fn set(&mut self, pos: [i32; 3], state: BlockStateId, flags: i32) -> Result<bool>;
fn fluid(&mut self, pos: [i32; 3]) -> Result<FluidState>;
fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result<i32>;
fn min_y(&mut self) -> Result<i32>;
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 place_template(
&mut self,
resources: &StructureResources,
template: &StructureTemplate,
position: [i32; 3],
reference: [i32; 3],
settings: &mut PlaceSettings<'_>,
random: &mut dyn ProcessorRandom,
flags: i32,
) -> Result<bool>;
}
impl<W: FeatureWorld + PlacementContext> PieceWorld for W {
fn block(&mut self, pos: [i32; 3]) -> Result<BlockStateId> {
self.block_state(pos)
}
fn set(&mut self, pos: [i32; 3], state: BlockStateId, flags: i32) -> Result<bool> {
self.set_block(pos, state, flags)
.map_err(|_| PlacementQueryError::Failed("piece write".into()))
}
fn fluid(&mut self, pos: [i32; 3]) -> Result<FluidState> {
self.fluid_state(pos)
}
fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result<i32> {
PlacementContext::height(self, kind, x, z)
}
fn min_y(&mut self) -> Result<i32> {
PlacementContext::min_y(self)
}
fn max_y(&mut self) -> Result<i32> {
PlacementContext::max_y(self)
}
fn block_entity(&mut self, pos: [i32; 3], nbt: Compound) -> Result<()> {
self.set_block_entity(pos, nbt)
}
fn post_process(&mut self, pos: [i32; 3]) -> Result<()> {
self.mark_postprocessing(pos)
}
fn place_template(
&mut self,
resources: &StructureResources,
template: &StructureTemplate,
position: [i32; 3],
reference: [i32; 3],
settings: &mut PlaceSettings<'_>,
random: &mut dyn ProcessorRandom,
flags: i32,
) -> Result<bool> {
place_in_world(
self,
resources,
template,
position,
reference,
settings,
Some(random),
flags,
)
}
}
/// Everything a piece needs while post-processing one chunk.
pub struct PieceContext<'a> {
pub world: &'a mut dyn PieceWorld,
pub resources: &'a StructureResources,
pub random: &'a mut dyn PieceRandom,
pub chunk_box: BoundingBox,
pub chunk: ChunkPos,
pub reference: [i32; 3],
}
impl PieceContext<'_> {
pub fn state(&self, name: &str) -> BlockStateId {
state(self.resources, name, &[])
}
pub fn state_with(&self, name: &str, properties: &[(&str, &str)]) -> BlockStateId {
state(self.resources, name, properties)
}
pub fn name(&self, state: BlockStateId) -> &str {
self.resources
.registry
.state(state)
.map(|s| s.name.as_str())
.unwrap_or("")
}
pub fn is_block(&mut self, pos: [i32; 3], name: &str) -> Result<bool> {
let state = self.world.block(pos)?;
Ok(self.name(state) == name)
}
pub fn is_air(&self, state: BlockStateId) -> bool {
matches!(
self.name(state),
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
)
}
/// BlockState.liquid(): water and lava blocks.
pub fn is_liquid(&self, state: BlockStateId) -> bool {
matches!(self.name(state), "minecraft:water" | "minecraft:lava")
}
pub fn property<'s>(&'s self, state: BlockStateId, key: &str) -> Option<&'s str> {
self.resources
.registry
.state(state)
.and_then(|s| s.properties.get(key))
.map(String::as_str)
}
pub fn with_property(&self, state: BlockStateId, key: &str, value: &str) -> BlockStateId {
let Some(mut descriptor) = self.resources.registry.state(state).cloned() else {
return state;
};
if let Some(slot) = descriptor.properties.get_mut(key) {
*slot = value.to_owned();
}
self.resources.registry.id(&descriptor).unwrap_or(state)
}
/// Store a loot-table container's block entity (RandomizableContainer.setLootTable).
pub fn loot_table(&mut self, pos: [i32; 3], kind: &str, table: &str) -> Result<()> {
let seed = self.random.long();
let mut nbt = Compound::new();
nbt.insert("id".into(), Tag::String(kind.into()));
nbt.insert("LootTable".into(), Tag::String(table.into()));
nbt.insert("LootTableSeed".into(), Tag::Long(seed));
self.world.block_entity(pos, nbt)
}
}
/// A state by block name and properties (missing properties keep defaults).
pub fn state(
resources: &StructureResources,
name: &str,
properties: &[(&str, &str)],
) -> BlockStateId {
let registry = resources.registry;
let mut descriptor = BlockState {
name: if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
},
properties: Default::default(),
};
for (k, v) in properties {
descriptor
.properties
.insert((*k).to_owned(), (*v).to_owned());
}
registry
.resolve(&descriptor)
.ok()
.or_else(|| registry.default_state(&descriptor.name))
.unwrap_or_else(|| registry.default_state("minecraft:air").unwrap())
}
/// A placed structure piece.
pub trait LegacyPiece: std::fmt::Debug + Send + Sync {
fn bounding_box(&self) -> BoundingBox;
/// The vanilla StructurePieceType id, for diagnostics and comparisons.
fn type_name(&self) -> &'static str;
fn post_process(&self, context: &mut PieceContext<'_>) -> Result<()>;
}
/// StructurePiece's orientation transform and block helpers.
#[derive(Clone, Copy, Debug)]
pub struct PieceFrame {
pub bounding_box: BoundingBox,
pub orientation: Option<Direction>,
pub mirror: Mirror,
pub rotation: Rotation,
}
pub const HORIZONTAL: [Direction; 4] = [
Direction::North,
Direction::East,
Direction::South,
Direction::West,
];
/// Direction.Plane.HORIZONTAL.getRandomDirection.
pub fn random_horizontal(random: &mut impl RandomSource) -> Direction {
HORIZONTAL[random.next_int_bound(4).unwrap_or(0) as usize]
}
pub fn make_bounding_box(
x: i32,
y: i32,
z: i32,
direction: Direction,
width: i32,
height: i32,
depth: i32,
) -> BoundingBox {
if matches!(direction, Direction::North | Direction::South) {
BoundingBox::new([x, y, z], [x + width - 1, y + height - 1, z + depth - 1])
} else {
BoundingBox::new([x, y, z], [x + depth - 1, y + height - 1, z + width - 1])
}
}
impl PieceFrame {
pub fn new(bounding_box: BoundingBox, orientation: Option<Direction>) -> Self {
let (mirror, rotation) = match orientation {
Some(Direction::South) => (Mirror::LeftRight, Rotation::None),
Some(Direction::West) => (Mirror::LeftRight, Rotation::Clockwise90),
Some(Direction::East) => (Mirror::None, Rotation::Clockwise90),
_ => (Mirror::None, Rotation::None),
};
Self {
bounding_box,
orientation,
mirror,
rotation,
}
}
pub fn world_x(&self, x: i32, z: i32) -> i32 {
match self.orientation {
Some(Direction::North | Direction::South) => self.bounding_box.min[0] + x,
Some(Direction::West) => self.bounding_box.max[0] - z,
Some(Direction::East) => self.bounding_box.min[0] + z,
_ => x,
}
}
pub fn world_y(&self, y: i32) -> i32 {
if self.orientation.is_none() {
y
} else {
y + self.bounding_box.min[1]
}
}
pub fn world_z(&self, x: i32, z: i32) -> i32 {
match self.orientation {
Some(Direction::North) => self.bounding_box.max[2] - z,
Some(Direction::South) => self.bounding_box.min[2] + z,
Some(Direction::West | Direction::East) => self.bounding_box.min[2] + x,
_ => z,
}
}
pub fn world_pos(&self, x: i32, y: i32, z: i32) -> [i32; 3] {
[self.world_x(x, z), self.world_y(y), self.world_z(x, z)]
}
/// StructurePiece.placeBlock (canBeReplaced is always true here).
pub fn place(
&self,
c: &mut PieceContext<'_>,
state: BlockStateId,
x: i32,
y: i32,
z: i32,
) -> Result<()> {
let pos = self.world_pos(x, y, z);
if !c.chunk_box.is_inside(pos) {
return Ok(());
}
let mut state = state;
if self.mirror != Mirror::None {
state = c.resources.transforms.mirror(state, self.mirror);
}
if self.rotation != Rotation::None {
state = c.resources.transforms.rotate(state, self.rotation);
}
c.world.set(pos, state, 2)?;
let fluid = c.world.fluid(pos)?;
if fluid.kind() != crate::fluid::FluidKind::Empty {
// scheduleTick(pos, fluid, 0) is a no-op for generation output.
}
if matches!(
c.name(state),
"minecraft:nether_brick_fence"
| "minecraft:torch"
| "minecraft:wall_torch"
| "minecraft:oak_fence"
| "minecraft:spruce_fence"
| "minecraft:dark_oak_fence"
| "minecraft:pale_oak_fence"
| "minecraft:acacia_fence"
| "minecraft:birch_fence"
| "minecraft:jungle_fence"
| "minecraft:ladder"
| "minecraft:iron_bars"
) {
c.world.post_process(pos)?;
}
Ok(())
}
pub fn get(&self, c: &mut PieceContext<'_>, x: i32, y: i32, z: i32) -> Result<BlockStateId> {
let pos = self.world_pos(x, y, z);
if c.chunk_box.is_inside(pos) {
c.world.block(pos)
} else {
Ok(c.state("air"))
}
}
pub fn is_interior(&self, c: &mut PieceContext<'_>, x: i32, y: i32, z: i32) -> Result<bool> {
let pos = self.world_pos(x, y + 1, z);
if !c.chunk_box.is_inside(pos) {
return Ok(false);
}
Ok(pos[1]
< c.world
.height(HeightmapType::OceanFloorWg, pos[0], pos[2])?)
}
#[allow(clippy::too_many_arguments)]
pub fn generate_box(
&self,
c: &mut PieceContext<'_>,
[x0, y0, z0]: [i32; 3],
[x1, y1, z1]: [i32; 3],
edge: BlockStateId,
fill: BlockStateId,
skip_air: bool,
) -> Result<()> {
for y in y0..=y1 {
for x in x0..=x1 {
for z in z0..=z1 {
if skip_air {
let s = self.get(c, x, y, z)?;
if c.is_air(s) {
continue;
}
}
let interior = y != y0 && y != y1 && x != x0 && x != x1 && z != z0 && z != z1;
self.place(c, if interior { fill } else { edge }, x, y, z)?;
}
}
}
Ok(())
}
/// generateBox with a block selector called as (random, x, y, z, edge).
pub fn generate_box_selector(
&self,
c: &mut PieceContext<'_>,
[x0, y0, z0]: [i32; 3],
[x1, y1, z1]: [i32; 3],
skip_air: bool,
selector: &mut dyn FnMut(&mut PieceContext<'_>, i32, i32, i32, bool) -> BlockStateId,
) -> Result<()> {
for y in y0..=y1 {
for x in x0..=x1 {
for z in z0..=z1 {
if skip_air {
let s = self.get(c, x, y, z)?;
if c.is_air(s) {
continue;
}
}
let edge = y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || z == z1;
let state = selector(c, x, y, z, edge);
self.place(c, state, x, y, z)?;
}
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn generate_maybe_box(
&self,
c: &mut PieceContext<'_>,
probability: f32,
[x0, y0, z0]: [i32; 3],
[x1, y1, z1]: [i32; 3],
edge: BlockStateId,
fill: BlockStateId,
skip_air: bool,
inside: bool,
) -> Result<()> {
for y in y0..=y1 {
for x in x0..=x1 {
for z in z0..=z1 {
if c.random.float() > probability {
continue;
}
if skip_air {
let s = self.get(c, x, y, z)?;
if c.is_air(s) {
continue;
}
}
if inside && !self.is_interior(c, x, y, z)? {
continue;
}
let interior = y != y0 && y != y1 && x != x0 && x != x1 && z != z0 && z != z1;
self.place(c, if interior { fill } else { edge }, x, y, z)?;
}
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn maybe_block(
&self,
c: &mut PieceContext<'_>,
probability: f32,
x: i32,
y: i32,
z: i32,
state: BlockStateId,
) -> Result<()> {
if c.random.float() < probability {
self.place(c, state, x, y, z)?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn upper_half_sphere(
&self,
c: &mut PieceContext<'_>,
[x0, y0, z0]: [i32; 3],
[x1, y1, z1]: [i32; 3],
fill: BlockStateId,
skip_air: bool,
) -> Result<()> {
let dx = (x1 - x0 + 1) as f32;
let dy = (y1 - y0 + 1) as f32;
let dz = (z1 - z0 + 1) as f32;
let cx = x0 as f32 + dx / 2.;
let cz = z0 as f32 + dz / 2.;
for y in y0..=y1 {
let ny = (y - y0) as f32 / dy;
for x in x0..=x1 {
let nx = (x as f32 - cx) / (dx * 0.5);
for z in z0..=z1 {
let nz = (z as f32 - cz) / (dz * 0.5);
if skip_air {
let s = self.get(c, x, y, z)?;
if c.is_air(s) {
continue;
}
}
if nx * nx + ny * ny + nz * nz <= 1.05 {
self.place(c, fill, x, y, z)?;
}
}
}
}
Ok(())
}
pub fn fill_column_down(
&self,
c: &mut PieceContext<'_>,
state: BlockStateId,
x: i32,
y: i32,
z: i32,
) -> Result<()> {
let mut pos = self.world_pos(x, y, z);
if !c.chunk_box.is_inside(pos) {
return Ok(());
}
let min = c.world.min_y()?;
loop {
let current = c.world.block(pos)?;
let replaceable = c.is_air(current)
|| c.is_liquid(current)
|| matches!(
c.name(current),
"minecraft:glow_lichen" | "minecraft:seagrass" | "minecraft:tall_seagrass"
);
if !replaceable || pos[1] <= min + 1 {
break;
}
c.world.set(pos, state, 2)?;
pos[1] -= 1;
}
Ok(())
}
/// StructurePiece.createChest at piece coordinates.
pub fn create_chest(
&self,
c: &mut PieceContext<'_>,
x: i32,
y: i32,
z: i32,
table: &str,
) -> Result<bool> {
let pos = self.world_pos(x, y, z);
create_chest(c, pos, table, None)
}
#[allow(clippy::too_many_arguments)]
pub fn create_dispenser(
&self,
c: &mut PieceContext<'_>,
x: i32,
y: i32,
z: i32,
facing: Direction,
table: &str,
) -> Result<bool> {
let pos = self.world_pos(x, y, z);
if !c.chunk_box.is_inside(pos) || c.is_block(pos, "minecraft:dispenser")? {
return Ok(false);
}
let state = c.state_with("dispenser", &[("facing", direction_name(facing))]);
self.place(c, state, x, y, z)?;
c.loot_table(pos, "minecraft:dispenser", table)?;
Ok(true)
}
}
pub fn direction_name(d: Direction) -> &'static str {
match d {
Direction::Down => "down",
Direction::Up => "up",
Direction::North => "north",
Direction::South => "south",
Direction::West => "west",
Direction::East => "east",
}
}
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 {
c.resources.transforms.full_block(state) && !c.is_liquid(state)
}
/// StructurePiece.createChest with an absolute position.
pub fn create_chest(
c: &mut PieceContext<'_>,
pos: [i32; 3],
table: &str,
state: Option<BlockStateId>,
) -> Result<bool> {
if !c.chunk_box.is_inside(pos) || c.is_block(pos, "minecraft:chest")? {
return Ok(false);
}
let state = match state {
Some(s) => s,
None => reorient(c, pos, c.state("chest"))?,
};
c.world.set(pos, state, 2)?;
c.loot_table(pos, "minecraft:chest", table)?;
Ok(true)
}
/// StructurePiece.reorient for chests (solid-render approximated by the
/// full collision cube of non-liquid blocks).
fn reorient(c: &mut PieceContext<'_>, pos: [i32; 3], state: BlockStateId) -> Result<BlockStateId> {
let mut solid: Option<Direction> = None;
for d in HORIZONTAL {
let n = c.world.block(offset(pos, d, 1))?;
if c.name(n) == "minecraft:chest" {
return Ok(state);
}
if solid_render(c, n) {
if solid.is_some() {
solid = None;
break;
}
solid = Some(d);
}
}
if let Some(d) = solid {
return Ok(c.with_property(state, "facing", direction_name(opposite(d))));
}
let mut facing = match c.property(state, "facing") {
Some("south") => Direction::South,
Some("east") => Direction::East,
Some("west") => Direction::West,
_ => Direction::North,
};
let solid_at = |c: &mut PieceContext<'_>, d: Direction| -> Result<bool> {
let s = c.world.block(offset(pos, d, 1))?;
Ok(solid_render(c, s))
};
if solid_at(c, facing)? {
facing = opposite(facing);
}
if solid_at(c, facing)? {
facing = clockwise(facing);
}
if solid_at(c, facing)? {
facing = opposite(facing);
}
Ok(c.with_property(state, "facing", direction_name(facing)))
}
pub fn opposite(d: Direction) -> Direction {
match d {
Direction::Down => Direction::Up,
Direction::Up => Direction::Down,
Direction::North => Direction::South,
Direction::South => Direction::North,
Direction::West => Direction::East,
Direction::East => Direction::West,
}
}
pub fn clockwise(d: Direction) -> Direction {
match d {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
other => other,
}
}
pub fn counter_clockwise(d: Direction) -> Direction {
match d {
Direction::North => Direction::West,
Direction::West => Direction::South,
Direction::South => Direction::East,
Direction::East => Direction::North,
other => other,
}
}
/// TemplateStructurePiece: one template with fixed settings; data markers
/// are handed to the owning structure.
#[derive(Debug)]
pub struct TemplatePiece {
pub type_name: &'static str,
pub template_name: String,
pub template: Arc<StructureTemplate>,
pub position: [i32; 3],
pub rotation: Rotation,
pub mirror: Mirror,
pub pivot: [i32; 3],
pub processors: Arc<ProcessorList>,
pub waterlogging: bool,
/// Ignore structure blocks (and air, for ocean ruins) before processors.
pub ignore: Vec<String>,
pub bounding_box: BoundingBox,
pub handler: TemplateHandler,
/// Per-piece state mutated by vanilla post-processing (e.g. ruined
/// portals record nothing; shipwrecks/igloos re-place at a height).
pub state: Mutex<Option<i32>>,
}
#[derive(Clone, Copy, Debug)]
pub enum TemplateHandler {
Igloo,
Shipwreck {
beached: bool,
},
OceanRuin {
warm: bool,
large: bool,
integrity: f32,
},
Plain,
}
impl TemplatePiece {
#[allow(clippy::too_many_arguments)]
pub fn new(
type_name: &'static str,
template_name: &str,
template: Arc<StructureTemplate>,
position: [i32; 3],
rotation: Rotation,
mirror: Mirror,
pivot: [i32; 3],
processors: Arc<ProcessorList>,
waterlogging: bool,
ignore: Vec<String>,
handler: TemplateHandler,
) -> Self {
Self {
bounding_box: template.bounding_box(position, rotation, pivot, mirror),
type_name,
template_name: template_name.to_owned(),
template,
position,
rotation,
mirror,
pivot,
processors,
waterlogging,
ignore,
handler,
state: Mutex::new(None),
}
}
pub fn settings(&self) -> PlaceSettings<'_> {
let mut s = PlaceSettings::new(self.rotation);
s.mirror = self.mirror;
s.pivot = self.pivot;
s.waterlogging = self.waterlogging;
s
}
/// TemplateStructurePiece.postProcess at a (possibly shifted) position;
/// returns the data markers (metadata, absolute position) on success.
pub fn place_at(
&self,
c: &mut PieceContext<'_>,
position: [i32; 3],
extra: &[Processor],
) -> Result<Option<Vec<(String, [i32; 3])>>> {
let ignore = Processor::BlockIgnore(self.ignore.iter().cloned().collect());
let mut settings = self.settings();
settings.bounding_box = Some(c.chunk_box);
settings.processors.push(&ignore);
settings.processors.extend(extra.iter());
settings.processors.extend(self.processors.0.iter());
let resources = c.resources;
let reference = c.reference;
if !c.world.place_template(
resources,
&self.template,
position,
reference,
&mut settings,
&mut *c.random,
2,
)? {
return Ok(None);
}
let mut markers = Vec::new();
let mut jigsaws = Vec::new();
for info in filter_blocks(resources, &self.template, position, &settings) {
let name = c.name(info.state).to_owned();
let Some(nbt) = &info.nbt else { continue };
let text = |key: &str| match nbt.get(&JavaString::from(key)) {
Some(Tag::String(s)) => s.to_string_lossy(),
_ => String::new(),
};
if name == "minecraft:structure_block" && text("mode").eq_ignore_ascii_case("data") {
markers.push((text("metadata"), info.pos));
} else if name == "minecraft:jigsaw" {
let final_state = nbt
.get(&JavaString::from("final_state"))
.map(|_| text("final_state"))
.unwrap_or_else(|| "minecraft:air".into());
jigsaws.push((info.pos, final_state));
}
}
for (pos, final_state) in jigsaws {
let state = super::template::parse_state_string(resources.registry, &final_state)
.unwrap_or_else(|| c.state("air"));
c.world.set(pos, state, 3)?;
}
Ok(Some(markers))
}
}
/// StructureTemplate.filterBlocks for structure and jigsaw blocks (palette
/// chosen by settings' random or a position seed), within the settings box.
fn filter_blocks(
resources: &StructureResources,
template: &StructureTemplate,
position: [i32; 3],
settings: &PlaceSettings<'_>,
) -> Vec<BlockInfo> {
if template.palettes().is_empty() {
return Vec::new();
}
let palette = LegacyRandom::new(position_seed(BlockPos::new(
position[0],
position[1],
position[2],
)))
.next_int_bound(template.palettes().len() as i32)
.unwrap_or(0) as usize;
template.palettes()[palette]
.blocks()
.iter()
.filter(|b| {
let name = resources
.registry
.state(b.state)
.map(|s| s.name.as_str())
.unwrap_or("");
name == "minecraft:structure_block" || name == "minecraft:jigsaw"
})
.filter_map(|b| {
let relative = StructureTemplate::transform(
b.pos,
settings.mirror,
settings.rotation,
settings.pivot,
);
let pos: [i32; 3] = std::array::from_fn(|i| relative[i] + position[i]);
settings
.bounding_box
.is_none_or(|bb| bb.is_inside(pos))
.then(|| BlockInfo {
pos,
state: resources.transforms.rotate(b.state, settings.rotation),
nbt: b.nbt.clone(),
})
})
.collect()
}
@@ -0,0 +1,353 @@
//! Ocean ruins (OceanRuinPieces).
use super::{
BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate,
legacy::{PieceContext, Result, TemplateHandler, TemplatePiece},
processor::ProcessorList,
};
use crate::{
fluid::FluidKind,
heightmap::HeightmapType,
worldgen::{DecodeError, block_feature::FeatureBlockBindings},
};
use horizon_core::random::RandomSource;
use std::sync::Arc;
const WARM: [&str; 8] = [
"warm_1", "warm_2", "warm_3", "warm_4", "warm_5", "warm_6", "warm_7", "warm_8",
];
const BIG_WARM: [&str; 4] = ["big_warm_4", "big_warm_5", "big_warm_6", "big_warm_7"];
const BRICK: [&str; 8] = [
"brick_1", "brick_2", "brick_3", "brick_4", "brick_5", "brick_6", "brick_7", "brick_8",
];
const CRACKED: [&str; 8] = [
"cracked_1",
"cracked_2",
"cracked_3",
"cracked_4",
"cracked_5",
"cracked_6",
"cracked_7",
"cracked_8",
];
const MOSSY: [&str; 8] = [
"mossy_1", "mossy_2", "mossy_3", "mossy_4", "mossy_5", "mossy_6", "mossy_7", "mossy_8",
];
const BIG_BRICK: [&str; 4] = ["big_brick_1", "big_brick_2", "big_brick_3", "big_brick_8"];
const BIG_CRACKED: [&str; 4] = [
"big_cracked_1",
"big_cracked_2",
"big_cracked_3",
"big_cracked_8",
];
const BIG_MOSSY: [&str; 4] = ["big_mossy_1", "big_mossy_2", "big_mossy_3", "big_mossy_8"];
/// Mth.nextInt(random, min, max).
pub fn next_int(random: &mut impl RandomSource, min: i32, max: i32) -> i32 {
if min >= max {
min
} else {
random.next_int_bound(max - min + 1).unwrap_or(0) + min
}
}
pub struct OceanRuinConfig {
pub warm: bool,
pub large_probability: f32,
pub cluster_probability: f32,
}
fn processors(
resources: &StructureResources,
bindings: &FeatureBlockBindings<'_>,
integrity: f32,
warm: bool,
) -> std::result::Result<Arc<ProcessorList>, DecodeError> {
let (candidate, replacement, table) = if warm {
(
"minecraft:sand",
"minecraft:suspicious_sand",
"minecraft:archaeology/ocean_ruin_warm",
)
} else {
(
"minecraft:gravel",
"minecraft:suspicious_gravel",
"minecraft:archaeology/ocean_ruin_cold",
)
};
let json = serde_json::json!({"processors": [
{"processor_type": "minecraft:block_rot", "integrity": integrity},
{"processor_type": "minecraft:block_ignore", "blocks": [{"id": "minecraft:structure_block"}, {"id": "minecraft:air"}]},
{"processor_type": "minecraft:capped", "limit": 5, "delegate": {"processor_type": "minecraft:rule", "rules": [{
"input_predicate": {"predicate_type": "minecraft:block_match", "block": candidate},
"location_predicate": {"predicate_type": "minecraft:always_true"},
"output_state": {"id": replacement},
"block_entity_modifier": {"type": "minecraft:append_loot", "loot_table": table}
}]}}
]});
Ok(Arc::new(ProcessorList::decode(
&json.to_string(),
resources,
bindings,
)?))
}
#[allow(clippy::too_many_arguments)]
fn piece(
resources: &StructureResources,
bindings: &FeatureBlockBindings<'_>,
name: &str,
position: [i32; 3],
rotation: Rotation,
integrity: f32,
warm: bool,
large: bool,
) -> Option<TemplatePiece> {
let name = format!("minecraft:underwater_ruin/{name}");
Some(TemplatePiece::new(
"minecraft:orp",
&name,
resources.template(&name)?,
position,
rotation,
Mirror::None,
[0; 3],
processors(resources, bindings, integrity, warm).ok()?,
true,
Vec::new(),
TemplateHandler::OceanRuin {
warm,
large,
integrity,
},
))
}
#[allow(clippy::too_many_arguments)]
fn add_piece(
out: &mut Vec<TemplatePiece>,
resources: &StructureResources,
bindings: &FeatureBlockBindings<'_>,
position: [i32; 3],
rotation: Rotation,
random: &mut impl RandomSource,
config: &OceanRuinConfig,
large: bool,
integrity: f32,
) -> Option<()> {
if config.warm {
let names: &[&str] = if large { &BIG_WARM } else { &WARM };
let name = names[random.next_int_bound(names.len() as i32).ok()? as usize];
out.push(piece(
resources, bindings, name, position, rotation, integrity, true, large,
)?);
} else {
let (bricks, cracked, mossy): (&[&str], &[&str], &[&str]) = if large {
(&BIG_BRICK, &BIG_CRACKED, &BIG_MOSSY)
} else {
(&BRICK, &CRACKED, &MOSSY)
};
let idx = random.next_int_bound(bricks.len() as i32).ok()? as usize;
out.push(piece(
resources,
bindings,
bricks[idx],
position,
rotation,
integrity,
false,
large,
)?);
out.push(piece(
resources,
bindings,
cracked[idx],
position,
rotation,
0.7,
false,
large,
)?);
out.push(piece(
resources, bindings, mossy[idx], position, rotation, 0.5, false, large,
)?);
}
Some(())
}
/// OceanRuinPieces.addPieces.
pub fn pieces(
resources: &StructureResources,
bindings: &FeatureBlockBindings<'_>,
position: [i32; 3],
rotation: Rotation,
random: &mut impl RandomSource,
config: &OceanRuinConfig,
) -> Option<Vec<TemplatePiece>> {
let mut out = Vec::new();
let large = random.next_float() <= config.large_probability;
let integrity = if large { 0.9 } else { 0.8 };
add_piece(
&mut out, resources, bindings, position, rotation, random, config, large, integrity,
)?;
if large && random.next_float() <= config.cluster_probability {
let parent = [position[0], 90, position[2]];
let corner = StructureTemplate::transform([15, 0, 15], Mirror::None, rotation, [0; 3]);
let corner = [
corner[0] + parent[0],
corner[1] + parent[1],
corner[2] + parent[2],
];
let parent_box = BoundingBox::from_corners(parent, corner);
let origin = [
parent[0].min(corner[0]),
parent[1],
parent[2].min(corner[2]),
];
let mut all = vec![
[
origin[0] - 16 + next_int(random, 1, 8),
origin[1],
origin[2] + 16 + next_int(random, 1, 7),
],
[
origin[0] - 16 + next_int(random, 1, 8),
origin[1],
origin[2] + next_int(random, 1, 7),
],
[
origin[0] - 16 + next_int(random, 1, 8),
origin[1],
origin[2] - 16 + next_int(random, 4, 8),
],
[
origin[0] + next_int(random, 1, 7),
origin[1],
origin[2] + 16 + next_int(random, 1, 7),
],
[
origin[0] + next_int(random, 1, 7),
origin[1],
origin[2] - 16 + next_int(random, 4, 6),
],
[
origin[0] + 16 + next_int(random, 1, 7),
origin[1],
origin[2] + 16 + next_int(random, 3, 8),
],
[
origin[0] + 16 + next_int(random, 1, 7),
origin[1],
origin[2] + next_int(random, 1, 7),
],
[
origin[0] + 16 + next_int(random, 1, 7),
origin[1],
origin[2] - 16 + next_int(random, 4, 8),
],
];
let ruins = next_int(random, 4, 8);
for _ in 0..ruins {
if all.is_empty() {
continue;
}
let idx = random.next_int_bound(all.len() as i32).ok()? as usize;
let pos = all.remove(idx);
let next_rotation = Rotation::random(random);
let c = StructureTemplate::transform([5, 0, 6], Mirror::None, next_rotation, [0; 3]);
let next_box =
BoundingBox::from_corners(pos, [c[0] + pos[0], c[1] + pos[1], c[2] + pos[2]]);
if !next_box.intersects(&parent_box) {
add_piece(
&mut out,
resources,
bindings,
pos,
next_rotation,
random,
config,
false,
0.8,
)?;
}
}
}
Some(out)
}
fn is_water(c: &mut PieceContext<'_>, pos: [i32; 3]) -> Result<bool> {
Ok(matches!(
c.world.fluid(pos)?.kind(),
FluidKind::Water | FluidKind::FlowingWater
))
}
/// OceanRuinPiece.postProcess.
pub fn post_process(piece: &TemplatePiece, c: &mut PieceContext<'_>) -> Result<()> {
let TemplateHandler::OceanRuin { large, .. } = piece.handler else {
return Ok(());
};
let [x, _, z] = piece.position;
let mut position = [x, c.world.height(HeightmapType::OceanFloorWg, x, z)?, z];
let size = piece.template.size;
let r = StructureTemplate::transform(
[size[0] - 1, 0, size[2] - 1],
Mirror::None,
piece.rotation,
[0; 3],
);
let corner = [r[0] + position[0], r[1] + position[1], r[2] + position[2]];
// getHeight over the footprint.
let mut new_y = position[1];
let mut min_y = 512;
let top_y = new_y - 1;
let mut area = 0;
let min_world = c.world.min_y()?;
for px in position[0].min(corner[0])..=position[0].max(corner[0]) {
for pz in position[2].min(corner[2])..=position[2].max(corner[2]) {
let mut floor = position[1] - 1;
loop {
let state = c.world.block([px, floor, pz])?;
let ice = c
.resources
.block_tags
.get("minecraft:ice")
.is_some_and(|t| t.contains(c.name(state)));
let open = c.is_air(state) || is_water(c, [px, floor, pz])? || ice;
if !(open && floor > min_world + 1) {
break;
}
floor -= 1;
}
min_y = min_y.min(floor);
if floor < top_y - 2 {
area += 1;
}
}
}
let width = (position[0] - corner[0]).abs();
if top_y - min_y > 2 && area > width - 2 {
new_y = min_y + 1;
}
position[1] = new_y;
if let Some(markers) = piece.place_at(c, position, &[])? {
for (marker, pos) in markers {
if marker == "chest" {
let water = if is_water(c, pos)? { "true" } else { "false" };
let chest = c.state_with("chest", &[("waterlogged", water)]);
c.world.set(pos, chest, 2)?;
let table = if large {
"minecraft:chests/underwater_ruin_big"
} else {
"minecraft:chests/underwater_ruin_small"
};
c.loot_table(pos, "minecraft:chest", table)?;
} else if marker == "drowned" {
// The drowned entity is not created; its marker block is cleared.
let sea = 63;
let state = if pos[1] > sea {
c.state("air")
} else {
c.state("water")
};
c.world.set(pos, state, 2)?;
}
}
}
Ok(())
}
@@ -0,0 +1,486 @@
//! Small piece-based structures: buried treasure, igloo, swamp hut, shipwreck.
use super::{
BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate,
legacy::{
LegacyPiece, PieceContext, PieceFrame, Result, TemplateHandler, TemplatePiece,
create_chest, make_bounding_box, offset, random_horizontal,
},
processor::ProcessorList,
};
use crate::heightmap::HeightmapType;
use horizon_core::{geometry::Direction, random::RandomSource};
use std::sync::{Arc, Mutex};
fn empty_processors() -> Arc<ProcessorList> {
Arc::new(ProcessorList::default())
}
#[derive(Debug)]
pub struct BuriedTreasurePiece {
pub position: [i32; 3],
}
impl LegacyPiece for BuriedTreasurePiece {
fn bounding_box(&self) -> BoundingBox {
BoundingBox::new(self.position, self.position)
}
fn type_name(&self) -> &'static str {
"minecraft:btp"
}
fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> {
let [x, _, z] = self.position;
let mut pos = [x, c.world.height(HeightmapType::OceanFloorWg, x, z)?, z];
let min = c.world.min_y()?;
while pos[1] > min {
let current = c.world.block(pos)?;
let below = c.world.block(offset(pos, Direction::Down, 1))?;
if matches!(
c.name(below),
"minecraft:sandstone"
| "minecraft:stone"
| "minecraft:andesite"
| "minecraft:granite"
| "minecraft:diorite"
) {
let soft = if !c.is_air(current) && !c.is_liquid(current) {
current
} else {
c.state("sand")
};
for d in Direction::ALL {
let relative = offset(pos, d, 1);
let state = c.world.block(relative)?;
if c.is_air(state) || c.is_liquid(state) {
let under = c.world.block(offset(relative, Direction::Down, 1))?;
if (c.is_air(under) || c.is_liquid(under)) && d != Direction::Up {
c.world.set(relative, below, 3)?;
} else {
c.world.set(relative, soft, 3)?;
}
}
}
create_chest(c, pos, "minecraft:chests/buried_treasure", None)?;
return Ok(());
}
pos[1] -= 1;
}
Ok(())
}
}
pub const IGLOO_TOP: &str = "minecraft:igloo/top";
const IGLOO_MIDDLE: &str = "minecraft:igloo/middle";
const IGLOO_BOTTOM: &str = "minecraft:igloo/bottom";
fn igloo_pivot(name: &str) -> [i32; 3] {
match name {
IGLOO_TOP => [3, 5, 5],
IGLOO_MIDDLE => [1, 3, 1],
_ => [3, 6, 7],
}
}
fn igloo_offset(name: &str) -> [i32; 3] {
match name {
IGLOO_TOP => [0, 0, 0],
IGLOO_MIDDLE => [2, -3, 4],
_ => [0, -3, -2],
}
}
/// IglooPieces.addPieces.
pub fn igloo_pieces(
resources: &StructureResources,
position: [i32; 3],
rotation: Rotation,
random: &mut impl RandomSource,
) -> Option<Vec<TemplatePiece>> {
let piece = |name: &str, depth: i32| -> Option<TemplatePiece> {
let o = igloo_offset(name);
Some(TemplatePiece::new(
"minecraft:iglu",
name,
resources.template(name)?,
[
position[0] + o[0],
position[1] + o[1] - depth,
position[2] + o[2],
],
rotation,
Mirror::None,
igloo_pivot(name),
empty_processors(),
false,
vec!["minecraft:structure_block".into()],
TemplateHandler::Igloo,
))
};
let mut pieces = Vec::new();
if random.next_double() < 0.5 {
let depth = random.next_int_bound(8).unwrap_or(0) + 4;
pieces.push(piece(IGLOO_BOTTOM, depth * 3)?);
for i in 0..depth - 1 {
pieces.push(piece(IGLOO_MIDDLE, i * 3)?);
}
}
pieces.push(piece(IGLOO_TOP, 0)?);
Some(pieces)
}
const SHIPWRECK_BEACHED: [&str; 11] = [
"with_mast",
"sideways_full",
"sideways_fronthalf",
"sideways_backhalf",
"rightsideup_full",
"rightsideup_fronthalf",
"rightsideup_backhalf",
"with_mast_degraded",
"rightsideup_full_degraded",
"rightsideup_fronthalf_degraded",
"rightsideup_backhalf_degraded",
];
const SHIPWRECK_OCEAN: [&str; 20] = [
"with_mast",
"upsidedown_full",
"upsidedown_fronthalf",
"upsidedown_backhalf",
"sideways_full",
"sideways_fronthalf",
"sideways_backhalf",
"rightsideup_full",
"rightsideup_fronthalf",
"rightsideup_backhalf",
"with_mast_degraded",
"upsidedown_full_degraded",
"upsidedown_fronthalf_degraded",
"upsidedown_backhalf_degraded",
"sideways_full_degraded",
"sideways_fronthalf_degraded",
"sideways_backhalf_degraded",
"rightsideup_full_degraded",
"rightsideup_fronthalf_degraded",
"rightsideup_backhalf_degraded",
];
/// ShipwreckPieces.addRandomPiece.
pub fn shipwreck_piece(
resources: &StructureResources,
position: [i32; 3],
rotation: Rotation,
random: &mut impl RandomSource,
beached: bool,
) -> Option<TemplatePiece> {
let names: &[&str] = if beached {
&SHIPWRECK_BEACHED
} else {
&SHIPWRECK_OCEAN
};
let name = format!(
"minecraft:shipwreck/{}",
names[random.next_int_bound(names.len() as i32).ok()? as usize]
);
Some(TemplatePiece::new(
"minecraft:shipwreck",
&name,
resources.template(&name)?,
position,
rotation,
Mirror::None,
[4, 0, 15],
empty_processors(),
true,
vec!["minecraft:structure_block".into(), "minecraft:air".into()],
TemplateHandler::Shipwreck { beached },
))
}
pub fn shipwreck_too_big(template: &StructureTemplate) -> bool {
template.size[0] > 32 || template.size[1] > 32
}
impl LegacyPiece for TemplatePiece {
fn bounding_box(&self) -> BoundingBox {
self.bounding_box
}
fn type_name(&self) -> &'static str {
self.type_name
}
fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> {
match self.handler {
TemplateHandler::Plain => {
self.place_at(c, self.position, &[])?;
}
TemplateHandler::Igloo => {
let o = igloo_offset(&self.template_name);
let entrance_relative = StructureTemplate::transform(
[3 - o[0], 0, -o[2]],
Mirror::None,
self.rotation,
self.pivot,
);
let entrance = [
self.position[0] + entrance_relative[0],
0,
self.position[2] + entrance_relative[2],
];
let height =
c.world
.height(HeightmapType::WorldSurfaceWg, entrance[0], entrance[2])?;
let position = [
self.position[0],
self.position[1] + height - 90 - 1,
self.position[2],
];
if let Some(markers) = self.place_at(c, position, &[])? {
for (marker, pos) in markers {
if marker == "chest" {
c.world.set(pos, c.state("air"), 3)?;
let below = offset(pos, Direction::Down, 1);
if c.is_block(below, "minecraft:chest")? {
c.loot_table(
below,
"minecraft:chest",
"minecraft:chests/igloo_chest",
)?;
}
}
}
}
if self.template_name == IGLOO_TOP {
let r = StructureTemplate::transform(
[3, 0, 5],
Mirror::None,
self.rotation,
self.pivot,
);
let trapdoor = [position[0] + r[0], position[1] + r[1], position[2] + r[2]];
let below = c.world.block(offset(trapdoor, Direction::Down, 1))?;
if !c.is_air(below) && c.name(below) != "minecraft:ladder" {
c.world.set(trapdoor, c.state("snow_block"), 3)?;
}
}
}
TemplateHandler::Shipwreck { beached } => {
let adjusted = *self.state.lock().unwrap();
let y = match adjusted {
Some(y) => y,
None if shipwreck_too_big(&self.template) => self.position[1],
None => {
let kind = if beached {
HeightmapType::WorldSurfaceWg
} else {
HeightmapType::OceanFloorWg
};
let size = self.template.size;
let mut min = c.world.max_y()? + 1;
let mut mean = 0;
let base = size[0] * size[2];
if base == 0 {
mean = c.world.height(kind, self.position[0], self.position[2])?;
} else {
for x in self.position[0]..self.position[0] + size[0] {
for z in self.position[2]..self.position[2] + size[2] {
let h = c.world.height(kind, x, z)?;
mean += h;
min = min.min(h);
}
}
mean /= base;
}
let y = if beached {
min - size[1] / 2 - c.random.int(3)
} else {
mean
};
*self.state.lock().unwrap() = Some(y);
y
}
};
let position = [self.position[0], y, self.position[2]];
if let Some(markers) = self.place_at(c, position, &[])? {
for (marker, pos) in markers {
let table = match marker.as_str() {
"map_chest" => "minecraft:chests/shipwreck_map",
"treasure_chest" => "minecraft:chests/shipwreck_treasure",
"supply_chest" => "minecraft:chests/shipwreck_supply",
_ => continue,
};
let below = offset(pos, Direction::Down, 1);
let state = c.world.block(below)?;
if c.resources.transforms.loot_container(state) {
let kind = c.name(state).to_owned();
c.loot_table(below, &kind, table)?;
}
}
}
}
TemplateHandler::OceanRuin { .. } => {
super::ocean_ruin::post_process(self, c)?;
}
}
Ok(())
}
}
/// ScatteredFeaturePiece: an oriented box whose height is fixed on first use.
#[derive(Debug)]
pub struct Scattered {
pub frame: Mutex<PieceFrame>,
pub width: i32,
pub height: i32,
pub depth: i32,
pub height_position: Mutex<i32>,
}
impl Scattered {
pub fn new(
west: i32,
floor: i32,
north: i32,
width: i32,
height: i32,
depth: i32,
direction: Direction,
) -> Self {
Self {
frame: Mutex::new(PieceFrame::new(
make_bounding_box(west, floor, north, direction, width, height, depth),
Some(direction),
)),
width,
height,
depth,
height_position: Mutex::new(-1),
}
}
pub fn frame(&self) -> PieceFrame {
*self.frame.lock().unwrap()
}
/// updateAverageGroundHeight over the part of the box inside the chunk.
pub fn average_ground(&self, c: &mut PieceContext<'_>, offset: i32) -> Result<bool> {
if *self.height_position.lock().unwrap() >= 0 {
return Ok(true);
}
let b = self.frame().bounding_box;
let (mut total, mut count) = (0, 0);
for z in b.min[2]..=b.max[2] {
for x in b.min[0]..=b.max[0] {
if c.chunk_box.is_inside([x, 64, z]) {
total += c
.world
.height(HeightmapType::MotionBlockingNoLeaves, x, z)?;
count += 1;
}
}
}
if count == 0 {
return Ok(false);
}
let h = total / count;
*self.height_position.lock().unwrap() = h;
let mut frame = self.frame.lock().unwrap();
frame.bounding_box =
frame
.bounding_box
.moved([0, h - frame.bounding_box.min[1] + offset, 0]);
Ok(true)
}
/// updateHeightPositionToLowestGroundHeight over the whole box.
pub fn lowest_ground(&self, c: &mut PieceContext<'_>, offset: i32) -> Result<bool> {
if *self.height_position.lock().unwrap() >= 0 {
return Ok(true);
}
let b = self.frame().bounding_box;
let mut lowest = c.world.max_y()? + 1;
for z in b.min[2]..=b.max[2] {
for x in b.min[0]..=b.max[0] {
lowest = lowest.min(
c.world
.height(HeightmapType::MotionBlockingNoLeaves, x, z)?,
);
}
}
*self.height_position.lock().unwrap() = lowest;
let mut frame = self.frame.lock().unwrap();
frame.bounding_box =
frame
.bounding_box
.moved([0, lowest - frame.bounding_box.min[1] + offset, 0]);
Ok(true)
}
}
#[derive(Debug)]
pub struct SwampHutPiece {
pub base: Scattered,
}
impl SwampHutPiece {
pub fn new(random: &mut impl RandomSource, west: i32, north: i32) -> Self {
let direction = random_horizontal(random);
Self {
base: Scattered::new(west, 64, north, 7, 7, 9, direction),
}
}
}
impl LegacyPiece for SwampHutPiece {
fn bounding_box(&self) -> BoundingBox {
self.base.frame().bounding_box
}
fn type_name(&self) -> &'static str {
"minecraft:tesh"
}
fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> {
if !self.base.average_ground(c, 0)? {
return Ok(());
}
let f = self.base.frame();
let planks = c.state("spruce_planks");
let log = c.state("oak_log");
for (a, b) in [
([1, 1, 1], [5, 1, 7]),
([1, 4, 2], [5, 4, 7]),
([2, 1, 0], [4, 1, 0]),
([2, 2, 2], [3, 3, 2]),
([1, 2, 3], [1, 3, 6]),
([5, 2, 3], [5, 3, 6]),
([2, 2, 7], [4, 3, 7]),
] {
f.generate_box(c, a, b, planks, planks, false)?;
}
for (a, b) in [
([1, 0, 2], [1, 3, 2]),
([5, 0, 2], [5, 3, 2]),
([1, 0, 7], [1, 3, 7]),
([5, 0, 7], [5, 3, 7]),
] {
f.generate_box(c, a, b, log, log, false)?;
}
let fence = c.state("oak_fence");
let air = c.state("air");
f.place(c, fence, 2, 3, 2)?;
f.place(c, fence, 3, 3, 7)?;
f.place(c, air, 1, 3, 4)?;
f.place(c, air, 5, 3, 4)?;
f.place(c, air, 5, 3, 5)?;
f.place(c, c.state("potted_red_mushroom"), 1, 3, 5)?;
f.place(c, c.state("crafting_table"), 3, 2, 6)?;
f.place(c, c.state("cauldron"), 4, 2, 6)?;
f.place(c, fence, 1, 2, 1)?;
f.place(c, fence, 5, 2, 1)?;
let stairs = |c: &PieceContext<'_>, facing: &str, shape: &str| {
c.state_with("spruce_stairs", &[("facing", facing), ("shape", shape)])
};
let north = stairs(c, "north", "straight");
let east = stairs(c, "east", "straight");
let west = stairs(c, "west", "straight");
let south = stairs(c, "south", "straight");
f.generate_box(c, [0, 4, 1], [6, 4, 1], north, north, false)?;
f.generate_box(c, [0, 4, 2], [0, 4, 7], east, east, false)?;
f.generate_box(c, [6, 4, 2], [6, 4, 7], west, west, false)?;
f.generate_box(c, [0, 4, 8], [6, 4, 8], south, south, false)?;
f.place(c, stairs(c, "north", "outer_right"), 0, 4, 1)?;
f.place(c, stairs(c, "north", "outer_left"), 6, 4, 1)?;
f.place(c, stairs(c, "south", "outer_left"), 0, 4, 8)?;
f.place(c, stairs(c, "south", "outer_right"), 6, 4, 8)?;
for z in [2, 7] {
for x in [1, 5] {
f.fill_column_down(c, log, x, -1, z)?;
}
}
Ok(())
}
}
@@ -3,6 +3,7 @@
use super::{
BoundingBox, StructureResources,
jigsaw::{JigsawConfig, JigsawContext, PoolPiece, Pools, Projection, assemble},
legacy::{LegacyPiece, PieceContext},
};
use crate::{
heightmap::HeightmapType,
@@ -58,6 +59,17 @@ pub struct JigsawDef {
#[derive(Debug)]
pub enum StructureKind {
Jigsaw(JigsawDef),
BuriedTreasure,
Igloo,
SwampHut,
Shipwreck {
beached: bool,
},
OceanRuin {
warm: bool,
large: f32,
cluster: f32,
},
/// A structure type whose generator is not implemented yet.
Unsupported(String),
}
@@ -160,6 +172,17 @@ impl StructureRegistry {
padding: pair(v.get("dimension_padding"), "bottom", "top", 0),
waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"),
}),
"minecraft:buried_treasure" => StructureKind::BuriedTreasure,
"minecraft:igloo" => StructureKind::Igloo,
"minecraft:swamp_hut" => StructureKind::SwampHut,
"minecraft:shipwreck" => StructureKind::Shipwreck {
beached: v["is_beached"].as_bool().unwrap_or(false),
},
"minecraft:ocean_ruin" => StructureKind::OceanRuin {
warm: v["biome_temp"].as_str() == Some("warm"),
large: v["large_probability"].as_f64().unwrap_or(0.) as f32,
cluster: v["cluster_probability"].as_f64().unwrap_or(0.) as f32,
},
other => StructureKind::Unsupported(other.to_owned()),
};
defs.push(StructureDef {
@@ -312,13 +335,52 @@ fn reduce(method: Reduction, seed: i64, salt: i32, x: i32, z: i32, probability:
#[derive(Debug)]
pub enum Piece {
Pool(PoolPiece),
Legacy(Box<dyn LegacyPiece>),
}
impl Piece {
pub fn bounding_box(&self) -> BoundingBox {
match self {
Self::Pool(p) => p.bounding_box,
Self::Legacy(p) => p.bounding_box(),
}
}
pub fn type_name(&self) -> &'static str {
match self {
Self::Pool(_) => "minecraft:jigsaw",
Self::Legacy(p) => p.type_name(),
}
}
}
fn legacy(pieces: Vec<impl LegacyPiece + 'static>) -> Vec<Piece> {
pieces
.into_iter()
.map(|p| Piece::Legacy(Box::new(p)))
.collect()
}
/// Structure.onTopOfChunkCenter: the start position, or None when no valid
/// biome can exist in the chunk-center column.
fn top_of_chunk_center(
context: &mut impl StartContext,
chunk: ChunkPos,
kind: HeightmapType,
) -> Option<[i32; 3]> {
let (x, z) = (chunk.x * 16 + 8, chunk.z * 16 + 8);
let (min, max) = (context.min_y(), context.max_y());
if !context.column_has_valid_biome(x, z, min - 1, max) {
return None;
}
Some([x, context.base_height(x, z, kind) - 1, z])
}
fn first_occupied(context: &mut impl StartContext, x: i32, z: i32) -> i32 {
context.base_height(x, z, HeightmapType::WorldSurfaceWg) - 1
}
fn corner_heights(context: &mut impl StartContext, x: i32, sx: i32, z: i32, sz: i32) -> [i32; 4] {
[
first_occupied(context, x, z),
first_occupied(context, x, z + sz),
first_occupied(context, x + sx, z),
first_occupied(context, x + sx, z + sz),
]
}
#[derive(Debug)]
pub struct StructureStart {
@@ -445,6 +507,80 @@ fn try_generate(
pieces.into_iter().map(Piece::Pool).collect::<Vec<_>>(),
)
}
StructureKind::BuriedTreasure => {
let stub = top_of_chunk_center(context, chunk, HeightmapType::OceanFloorWg)?;
let piece = super::simple::BuriedTreasurePiece {
position: [chunk.x * 16 + 9, 90, chunk.z * 16 + 9],
};
(stub, legacy(vec![piece]))
}
StructureKind::Igloo => {
let stub = top_of_chunk_center(context, chunk, HeightmapType::WorldSurfaceWg)?;
let rotation = super::Rotation::random(&mut random);
let pieces = super::simple::igloo_pieces(
resources,
[chunk.x * 16, 90, chunk.z * 16],
rotation,
&mut random,
)?;
(stub, legacy(pieces))
}
StructureKind::SwampHut => {
let stub = top_of_chunk_center(context, chunk, HeightmapType::WorldSurfaceWg)?;
let piece = super::simple::SwampHutPiece::new(&mut random, chunk.x * 16, chunk.z * 16);
(stub, legacy(vec![piece]))
}
StructureKind::Shipwreck { beached } => {
let kind = if *beached {
HeightmapType::WorldSurfaceWg
} else {
HeightmapType::OceanFloorWg
};
let stub = top_of_chunk_center(context, chunk, kind)?;
let rotation = super::Rotation::random(&mut random);
let piece = super::simple::shipwreck_piece(
resources,
[chunk.x * 16, 90, chunk.z * 16],
rotation,
&mut random,
*beached,
)?;
if super::simple::shipwreck_too_big(&piece.template) {
let b = piece.bounding_box;
let [sx, _, sz] = b.span();
let heights = corner_heights(context, b.min[0], sx, b.min[2], sz);
let height = if *beached {
let min = heights.into_iter().min().unwrap_or(0);
min - piece.template.size[1] / 2 - random.next_int_bound(3).unwrap_or(0)
} else {
heights.iter().sum::<i32>() / 4
};
*piece.state.lock().unwrap() = Some(height);
}
(stub, legacy(vec![piece]))
}
StructureKind::OceanRuin {
warm,
large,
cluster,
} => {
let stub = top_of_chunk_center(context, chunk, HeightmapType::OceanFloorWg)?;
let rotation = super::Rotation::random(&mut random);
let config = super::ocean_ruin::OceanRuinConfig {
warm: *warm,
large_probability: *large,
cluster_probability: *cluster,
};
let pieces = super::ocean_ruin::pieces(
resources,
bindings,
[chunk.x * 16, 90, chunk.z * 16],
rotation,
&mut random,
&config,
)?;
(stub, legacy(pieces))
}
StructureKind::Unsupported(_) => return None,
};
let quart = position.map(|v| v >> 2);
@@ -544,7 +680,15 @@ pub fn beardifier(
if !near {
continue;
}
let Piece::Pool(pool) = piece;
let Piece::Pool(pool) = piece else {
rigids.push(RigidPiece {
bounds: StructureBounds::new(b.min, b.max)?,
adjustment,
ground_level_delta: 0,
});
include(b, &mut any);
continue;
};
if pool.element.projection() == Projection::Rigid {
rigids.push(RigidPiece {
bounds: StructureBounds::new(b.min, b.max)?,
@@ -581,7 +725,7 @@ pub fn beardifier(
/// StructureStart.placeInChunk for pieces intersecting the chunk's writable box.
#[allow(clippy::too_many_arguments)]
pub fn place_in_chunk<W: FeatureWorld + PlacementContext, R: RandomSource>(
pub fn place_in_chunk<W: FeatureWorld + PlacementContext, R: RandomSource + 'static>(
start: &StructureStart,
world: &mut W,
resources: &StructureResources,
@@ -613,6 +757,17 @@ pub fn place_in_chunk<W: FeatureWorld + PlacementContext, R: RandomSource>(
place_feature,
)?;
}
Piece::Legacy(p) => {
let mut context = PieceContext {
world,
resources,
random,
chunk_box,
chunk: ChunkPos::new(chunk_box.min[0] >> 4, chunk_box.min[2] >> 4),
reference,
};
p.post_process(&mut context)?;
}
}
}
}
@@ -58,11 +58,20 @@ 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_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);
var resolver=biomeSource.createResolver(climate);
StringBuilder biomes=new StringBuilder();
for(int qy=(floor-12)>>2;qy<=(floor+8)>>2;qy++)biomes.append(" "+qy+":"+resolver.getNoiseBiome(x>>2,qy,z>>2).unwrapKey().get().identifier().getPath());
w.println("height "+x+" "+z+" "+floor+" "+surface+biomes);
}
for(int cx=x0;cx<=x1;cx++)for(int cz=z0;cz<=z1;cz++) {
ChunkPos pos=new ChunkPos(cx,cz);
for(var set:state.possibleStructureSets()) {
var placement=set.value().placement();var entries=set.value().structures();
if(!placement.isStructureChunk(state,cx,cz))continue;
if(System.getenv("HORIZON_PLACED")!=null)w.println("placed "+cx+" "+cz+" "+set.unwrapKey().get().identifier());
var options=new ArrayList<>(entries);
WorldgenRandom random=new WorldgenRandom(new LegacyRandomSource(0L));random.setLargeFeatureSeed(seed,cx,cz);
int total=0;for(var o:options)total+=o.weight();
@@ -72,6 +81,13 @@ public final class VanillaStructureStartOracle {
else{int choice=random.nextInt(total);for(var o:options){choice-=o.weight();if(choice<0)break;index++;}selected=options.get(index);}
var structure=selected.structure();
StructureStart start=structure.value().generate(structure,Level.OVERWORLD,access,generator,biomeSource,climate,randomState,templates,seed,pos,0,height,structure.value().biomes()::contains);
if(System.getenv("HORIZON_PLACED")!=null){
w.println("generate "+structure.unwrapKey().get().identifier()+" "+start.isValid());
var ctx=new Structure.GenerationContext(access,generator,biomeSource,climate,randomState,templates,seed,pos,height,structure.value().biomes()::contains);
try{var m=Structure.class.getDeclaredMethod("findGenerationPoint",Structure.GenerationContext.class);m.setAccessible(true);
var stub=(java.util.Optional<?>)m.invoke(structure.value(),ctx);
stub.ifPresent(st->{var sp=((Structure.GenerationStub)st).position();w.println("stub "+sp+" "+ctx.biomeResolver().getNoiseBiome(sp.getX()>>2,sp.getY()>>2,sp.getZ()>>2).unwrapKey().get().identifier());});}catch(Exception e){w.println("err "+e);}
}
if(start.isValid()) {
var b=start.getBoundingBox();
w.println("start "+cx+" "+cz+" "+structure.unwrapKey().get().identifier()+" "+b.minX()+" "+b.minY()+" "+b.minZ()+" "+b.maxX()+" "+b.maxY()+" "+b.maxZ()+" "+start.getPieces().size());
+4 -2
View File
@@ -21,8 +21,10 @@ def main():
classes = build/'classes'
classes.mkdir(parents=True, exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
'-d', str(classes), str(source)], check=True)
compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
'-d', str(classes), str(source)], capture_output=True, text=True)
if compiled.returncode:
raise SystemExit('javac failed:\n' + compiled.stderr[-3000:])
result = subprocess.run(['java', '-Xmx2G', '-cp', str(classes)+os.pathsep+dependencies,
'dev.horizonlab.parity.VanillaStructureStartOracle', out, seed, x0, z0, x1, z1],
capture_output=True, text=True)