diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index b2c48e7c9..bfe79244d 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -1346,6 +1346,13 @@ impl ArgType { ArgType::ItemPredicate => Arg::Item(parse_item(reader, reg, true)?), ArgType::BlockState => Arg::Block(parse_block(reader, reg, false)?), ArgType::BlockPredicate => Arg::Block(parse_block(reader, reg, true)?), + // ResourceOrTagKeyArgument: structures and biomes also take a #tag. + ArgType::Resource(kind @ (Resource::Structure | Resource::Biome)) + if reader.can_read() && reader.peek() == '#' => + { + reader.cursor += 1; + Arg::Resource(format!("#{}", read_id(reader)?)) + } ArgType::Resource(kind) => { let id = read_id(reader)?; let values = kind.values(reg); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4ddeec651..15420be04 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4720,8 +4720,7 @@ impl Game<'_> { let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), res.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { format!("{e}\nPrepare the worldgen bundle with: python3 tools/prepare_native_client.py") })?); - self.end - .set_locator((dim == Dim::Overworld).then(|| inner.clone())); + self.end.set_locator(Some(inner.clone())); Streaming::new( Arc::new(Persistent { inner, diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 655a98cb5..c9f7c1b3b 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1835,10 +1835,82 @@ impl Game<'_> { let Some(Arg::Resource(s)) = ctx.get("structure").cloned() else { return Ok(0); }; - Err(CommandError::new(Text::tr( - "commands.locate.structure.not_found", - &[&s], - ))) + // LocateCommand.locateStructure: an id or a #tag of structures. + let names = match s.strip_prefix('#') { + Some(tag) => self.structure_tag(tag), + None => vec![s.clone()], + }; + let from = origin.map(|v| v.floor() as i32); + let found = self.end.locator().and_then(|t| t.locate(&names, from, 100)); + let Some((name, p)) = found else { + return Err(CommandError::new(Text::tr( + "commands.locate.structure.not_found", + &[&s], + ))); + }; + let coords = Text::translate( + "chat.coordinates", + &[ + Text::literal(p[0].to_string()), + Text::literal("~"), + Text::literal(p[2].to_string()), + ], + ); + let link = Text::literal("[") + .append(coords) + .append("]") + .with_style(&Style { + color: Some(text::GREEN), + suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])), + ..Style::default() + }); + let (dx, dz) = (f64::from(p[0] - from[0]), f64::from(p[2] - from[2])); + let distance = (dx * dx + dz * dz).sqrt().floor() as i32; + let shown = if s.starts_with('#') { + format!("{s} ({name})") + } else { + name + }; + self.feedback(Text::translate( + "commands.locate.structure.success", + &[ + Text::literal(shown), + link, + Text::literal(distance.to_string()), + ], + )); + Ok(distance) + } + /// The structures of a `worldgen/structure` tag, nested tags expanded. + fn structure_tag(&self, tag: &str) -> Vec { + let mut out = Vec::new(); + let mut pending = vec![tag.to_owned()]; + let mut seen = std::collections::HashSet::new(); + while let Some(t) = pending.pop() { + if !seen.insert(t.clone()) { + continue; + } + let (ns, path) = t.split_once(':').unwrap_or(("minecraft", &t)); + let file = self + .options + .resources + .join(format!("data/{ns}/tags/worldgen/structure/{path}.json")); + let Ok(v) = std::fs::read(file) + .map_err(|_| ()) + .and_then(|b| serde_json::from_slice::(&b).map_err(|_| ())) + else { + continue; + }; + for e in v["values"].as_array().into_iter().flatten() { + let id = e.as_str().or_else(|| e["id"].as_str()).unwrap_or_default(); + match id.strip_prefix('#') { + Some(nested) => pending.push(nested.to_owned()), + None if !id.is_empty() => out.push(id.to_owned()), + None => {} + } + } + } + out } fn cmd_say(&mut self, id: &str, ctx: &Context) -> R { let raw = match ctx.get(if id == "me" { "action" } else { "message" }) { diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index d94e5a52b..3f88a5ed9 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -93,6 +93,9 @@ impl EndFlash { } } impl EndState { + pub(super) fn locator(&self) -> Option> { + self.locator.lock().unwrap().clone() + } pub(super) fn set_locator(&self, terrain: Option>) { *self.locator.lock().unwrap() = terrain; } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 53ac3206d..b6c58cb8d 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -206,9 +206,23 @@ impl Game<'_> { } _ if self.res.mob_types.contains_key(&kind) => { self.next_entity += 1; - if let Some(m) = + // Structure entities placed with finalizeEntities. + let mut tag = tag; + let finalize = match &mut tag { + Tag::Compound(c) => c.remove(&"horizon:finalize".into()).is_some(), + _ => false, + }; + if let Some(mut m) = entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, self.next_entity) { + if finalize { + let facts = self.biome_facts( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + horizon_client::mobs::spawning::finalize(&mut m, &facts); + } self.remember(m.id, uuid, tag); self.mobs.push(m); } diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index f085f4edd..35211d6e0 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -68,6 +68,16 @@ impl VanillaTerrain { loot, }) } + /// `/locate structure`: the nearest start of one of `names` within + /// `radius` placement sectors of block `from`. + pub fn locate( + &self, + names: &[String], + from: [i32; 3], + radius: i32, + ) -> Option<(String, [i32; 3])> { + self.generator.worker().locate(names, from, radius) + } /// Concentric ring positions of a structure set (strongholds), once known. pub fn ring_positions(&self, set: &str) -> Option> { self.generator.ring_positions(set) @@ -142,7 +152,7 @@ impl ChunkGenerator for VanillaTerrain { } fn finish(&self, proto: Proto) -> Chunk { let proto = proto.downcast::().expect("vanilla proto"); - let chunk = match *proto { + let mut chunk = match *proto { VanillaProto::Ready(c) => c, VanillaProto::Failed(x, z) => return Chunk::empty(x, z), }; @@ -190,6 +200,10 @@ impl ChunkGenerator for VanillaTerrain { } out.biomes = Arc::new(biomes); out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); + out.entities = std::mem::take(&mut chunk.entities) + .into_iter() + .map(horizon_world::nbt::Tag::Compound) + .collect(); for s in &mut out.sections { Arc::make_mut(s).compact(); } diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index f28bb950e..91a5e0f1d 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -500,6 +500,9 @@ pub struct ProtoChunk { pub block_entities: Vec<([i32; 3], crate::nbt::Compound)>, /// Structure starts referencing this chunk (STRUCTURE_REFERENCES). pub(super) structure_starts: Vec>, + /// Entities placed by structures (`ProtoChunk.addEntity`), as NBT with + /// absolute `Pos`. + pub entities: Vec, } impl ProtoChunk { pub fn position(&self) -> ChunkPos { @@ -1021,6 +1024,7 @@ where decorated: false, block_entities: Vec::new(), structure_starts: references, + entities: Vec::new(), }) } } @@ -1326,6 +1330,13 @@ trait SeededPipeline: Send + Sync { ) -> Vec>; fn unsupported_features(&self) -> Vec<(String, String)>; fn ring_positions(&self, set: &str) -> Option>; + fn locate( + &self, + worker: &mut WorkerState, + names: &[String], + from: [i32; 3], + radius: i32, + ) -> Option<(String, [i32; 3])>; } impl SeededPipeline for Pipeline where @@ -1403,6 +1414,24 @@ where fn ring_positions(&self, set: &str) -> Option> { self.structures.as_ref()?.cached_rings(set) } + fn locate( + &self, + worker: &mut WorkerState, + names: &[String], + from: [i32; 3], + radius: i32, + ) -> Option<(String, [i32; 3])> { + self.structures.as_ref()?.locate( + &mut StructureQueries { + pipeline: self, + worker, + valid: BTreeSet::new(), + }, + names, + from, + radius, + ) + } } /// Counters from one FEATURES pass. @@ -1541,6 +1570,15 @@ impl GeneratorWorker { self.state.timings.chunks += 1; result } + /// `/locate structure`: the nearest start of one of `names`. + pub fn locate( + &mut self, + names: &[String], + from: [i32; 3], + radius: i32, + ) -> Option<(String, [i32; 3])> { + self.pipeline.locate(&mut self.state, names, from, radius) + } /// STRUCTURE_STARTS: the structure starts owned by a chunk (cached). pub fn structure_starts( &mut self, diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index 53cb5b237..7cef04bd9 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -316,6 +316,7 @@ impl Decoration { } let mut world = World { block_entities, + entities: Vec::new(), level_random, blocks: data .feature_resources @@ -418,6 +419,22 @@ impl Decoration { chunk.block_entities.push((pos, nbt)); } } + // WorldGenRegion.addFreshEntity: into the chunk holding the position. + for nbt in std::mem::take(&mut world.entities) { + let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + continue; + }; + let coord = |i: usize| match p.get(i) { + Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, + _ => 0, + }; + let index = ((coord(2) >> 4).wrapping_sub(center.z) + 1) * 3 + + (coord(0) >> 4).wrapping_sub(center.x) + + 1; + if let Some(chunk) = usize::try_from(index).ok().and_then(|i| region.get_mut(i)) { + chunk.entities.push(nbt); + } + } for terrain in world.region.into_chunks() { let p = terrain.position(); let index = (p.z.wrapping_sub(center.z) + 1) * 3 + p.x.wrapping_sub(center.x) + 1; @@ -437,6 +454,7 @@ impl Decoration { /// the FEATURES step's write radius, biome lookups through the biome zoom. struct World<'a> { block_entities: Vec<([i32; 3], crate::nbt::Compound)>, + entities: Vec, level_random: &'a mut dyn super::structure::legacy::PieceRandom, blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, @@ -721,6 +739,10 @@ impl PlacementContext for World<'_> { (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) })) } + fn add_entity(&mut self, nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + self.entities.push(nbt); + Ok(()) + } fn set_block_entity( &mut self, position: [i32; 3], diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index b88cf0613..136c85264 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -130,6 +130,105 @@ impl StructureState { cache.insert((chunk.x, chunk.z), starts.clone()); starts } + /// ChunkGenerator.findNearestMapStructure: the nearest start of one of + /// `names` from block `from` (rings: every ring chunk; random spreads: + /// sectors in growing squares up to `radius`). Returns the structure and + /// its locate position (the start chunk's corner at y 0). + pub(super) fn locate( + &self, + context: &mut impl super::structure::start::StartContext, + names: &[String], + from: [i32; 3], + radius: i32, + ) -> Option<(String, [i32; 3])> { + let seed = context.seed(); + let rings = self + .rings + .get_or_init(|| { + self.registry + .ring_positions(&self.possible_sets, seed, &mut |q| context.noise_biome(q)) + }) + .clone(); + let wanted = |s: usize| names.iter().any(|n| *n == self.registry.structures[s].name); + let dist = |p: [i32; 3]| { + let (dx, dz) = (f64::from(p[0] - from[0]), f64::from(p[2] - from[2])); + dx * dx + dz * dz + }; + let mut best: Option<(f64, String, [i32; 3])> = None; + let found_at = |this: &Self, context: &mut _, chunk: ChunkPos| -> Option { + this.starts_at(context, chunk) + .iter() + .find(|s| wanted(s.structure)) + .map(|s| s.name.clone()) + }; + for &si in &self.possible_sets { + let set = &self.registry.sets[si]; + if !set.structures.iter().any(|(s, _)| wanted(*s)) { + continue; + } + match set.spacing() { + None => { + // Rings: nearest by the chunk's (8, 32, 8) block. + let Some(chunks) = rings.get(&set.name) else { + continue; + }; + let mut nearest: Option<(f64, ChunkPos)> = None; + for &c in chunks { + let d = dist([c.x * 16 + 8, 32, c.z * 16 + 8]); + if nearest.is_none_or(|(n, _)| d < n) + && self + .registry + .is_structure_chunk(set, seed, c.x, c.z, &rings) + { + nearest = Some((d, c)); + } + } + if let Some((_, c)) = nearest + && let Some(name) = found_at(self, context, c) + { + let p = [c.x * 16, 0, c.z * 16]; + let d = dist(p); + if best.as_ref().is_none_or(|(b, ..)| d < *b) { + best = Some((d, name, p)); + } + } + } + Some(spacing) => { + let (cx, cz) = (from[0] >> 4, from[2] >> 4); + 'search: for r in 0..=radius { + for dx in -r..=r { + let x_edge = dx == -r || dx == r; + for dz in -r..=r { + if !(x_edge || dz == -r || dz == r) { + continue; + } + let (sx, sz) = (cx + spacing * dx, cz + spacing * dz); + let Some(c) = StructureRegistry::potential_chunk(set, seed, sx, sz) + else { + continue; + }; + if !self + .registry + .is_structure_chunk(set, seed, c.x, c.z, &rings) + { + continue; + } + if let Some(name) = found_at(self, context, c) { + let p = [c.x * 16, 0, c.z * 16]; + let d = dist(p); + if best.as_ref().is_none_or(|(b, ..)| d < *b) { + best = Some((d, name, p)); + } + break 'search; + } + } + } + } + } + } + } + best.map(|(_, n, p)| (n, p)) + } /// ChunkGenerator.createReferences: starts within 8 chunks whose box /// intersects this chunk's column. pub(super) fn references( diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index 1cfb98c81..7da5310d4 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -309,6 +309,11 @@ pub trait PlacementContext { fn layer_block(&mut self, _position: [i32; 3]) -> Result { Err(PlacementQueryError::Unavailable) } + /// Add an entity from its NBT (structure templates and pieces; `Pos` is + /// absolute). Worlds without entity storage drop it. + fn add_entity(&mut self, _nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + Ok(()) + } /// Store block-entity data loaded at a just-placed block (structure /// templates). Worlds without block-entity storage drop it. fn set_block_entity( diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index f360e6a4e..a50275941 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -484,6 +484,8 @@ fn place_element( }; let mut settings = PlaceSettings::new(rotation); settings.known_shape = true; + // SinglePoolElement.getSettings. + settings.finalize_entities = true; settings.bounding_box = Some(chunk_box); settings.waterlogging = override_liquid.unwrap_or(waterlogging); if !*legacy { diff --git a/crates/horizon-world/src/worldgen/structure/legacy.rs b/crates/horizon-world/src/worldgen/structure/legacy.rs index abd011c51..275b8a98d 100644 --- a/crates/horizon-world/src/worldgen/structure/legacy.rs +++ b/crates/horizon-world/src/worldgen/structure/legacy.rs @@ -785,6 +785,9 @@ impl TemplatePiece { s.mirror = self.mirror; s.pivot = self.pivot; s.waterlogging = self.waterlogging; + // Mansions and end cities spawn their mobs from data markers. + s.ignore_entities = self.template_name.contains("woodland_mansion/") + || self.template_name.contains("end_city/"); s } /// TemplateStructurePiece.postProcess at a (possibly shifted) position; diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index 728658bfe..b5bf2e22f 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -317,6 +317,9 @@ pub struct PlaceSettings<'a> { /// StructurePlaceSettings.knownShape: skip the neighbor shape updates /// after placement (jigsaw pieces). pub known_shape: bool, + /// StructurePlaceSettings.ignoreEntities / finalizeEntities. + pub ignore_entities: bool, + pub finalize_entities: bool, } impl<'a> PlaceSettings<'a> { pub fn new(rotation: Rotation) -> Self { @@ -329,6 +332,8 @@ impl<'a> PlaceSettings<'a> { waterlogging: true, random: None, known_shape: false, + ignore_entities: false, + finalize_entities: false, } } pub fn with_processors(mut self, list: &'a ProcessorList) -> Self { @@ -832,9 +837,115 @@ pub fn place_in_world( world.update_from_neighbour_shapes(pos, flags & !1 | 16)?; } } + if !settings.ignore_entities { + place_entities(world, template, position, settings)?; + } Ok(true) } +/// StructureTemplate.placeEntities: each saved entity moved, turned and +/// mirrored with the template, its NBT handed to the world. +fn place_entities( + world: &mut W, + template: &StructureTemplate, + position: [i32; 3], + settings: &PlaceSettings<'_>, +) -> Result<(), PlacementQueryError> { + let (mirror, rotation, pivot) = (settings.mirror, settings.rotation, settings.pivot); + for e in &template.entities { + let b = StructureTemplate::transform(e.block_pos, mirror, rotation, pivot); + let block_pos = [b[0] + position[0], b[1] + position[1], b[2] + position[2]]; + if settings + .bounding_box + .is_some_and(|bb| !bb.is_inside(block_pos)) + { + continue; + } + let r = StructureTemplate::transform_vec(e.pos, mirror, rotation, pivot); + let pos = [ + r[0] + f64::from(position[0]), + r[1] + f64::from(position[1]), + r[2] + f64::from(position[2]), + ]; + let mut nbt = e.nbt.clone(); + nbt.insert( + "Pos".into(), + Tag::List(pos.iter().map(|v| Tag::Double(v.to_bits())).collect()), + ); + nbt.remove(&"UUID".into()); + if nbt.contains_key(&"block_pos".into()) { + nbt.insert("block_pos".into(), Tag::IntArray(block_pos.to_vec())); + } + for (key, i) in [("TileX", 0), ("TileY", 1), ("TileZ", 2)] { + if nbt.contains_key(&key.into()) { + nbt.insert(key.into(), Tag::Int(block_pos[i])); + } + } + // Entity.rotate + Entity.mirror on the yaw. + let wrap = |a: f32| { + let a = a % 360.0; + if a >= 180.0 { + a - 360.0 + } else if a < -180.0 { + a + 360.0 + } else { + a + } + }; + if let Some(Tag::List(rot)) = nbt.get(&"Rotation".into()).cloned() + && let Some(Tag::Float(bits)) = rot.first() + { + let yaw = wrap(f32::from_bits(*bits)); + let rotated = match rotation { + Rotation::Clockwise180 => yaw + 180.0, + Rotation::Counterclockwise90 => yaw + 270.0, + Rotation::Clockwise90 => yaw + 90.0, + Rotation::None => yaw, + }; + let mirrored = match mirror { + Mirror::FrontBack => -yaw, + Mirror::LeftRight => 180.0 - yaw, + Mirror::None => yaw, + }; + let mut rot = rot.clone(); + rot[0] = Tag::Float((rotated + mirrored - yaw).to_bits()); + nbt.insert("Rotation".into(), Tag::List(rot)); + } + // HangingEntity.rotate/mirror: the facing turns with the template. + if let Some(&Tag::Byte(f)) = nbt.get(&"Facing".into()) { + nbt.insert("Facing".into(), Tag::Byte(turn_facing(f, mirror, rotation))); + } + if settings.finalize_entities { + nbt.insert("horizon:finalize".into(), Tag::Byte(1)); + } + world.add_entity(nbt)?; + } + Ok(()) +} +/// A 3D data value (2 north, 3 south, 4 west, 5 east) mirrored then rotated. +fn turn_facing(f: i8, mirror: Mirror, rotation: Rotation) -> i8 { + if !(2..=5).contains(&f) { + return f; + } + let mirrored = match (mirror, f) { + (Mirror::LeftRight, 2) => 3, + (Mirror::LeftRight, 3) => 2, + (Mirror::FrontBack, 4) => 5, + (Mirror::FrontBack, 5) => 4, + (_, f) => f, + }; + // Clockwise order: north, east, south, west. + let order = [2, 5, 3, 4]; + let i = order.iter().position(|&d| d == mirrored).unwrap_or(0); + let steps = match rotation { + Rotation::None => 0, + Rotation::Clockwise90 => 1, + Rotation::Clockwise180 => 2, + Rotation::Counterclockwise90 => 3, + }; + order[(i + steps) % 4] +} + /// StructureTemplate.updateShapeAtEdge over the placed positions' voxel /// shape (DiscreteVoxelShape.forAllFaces order: X-Y rows along Z, then /// Z-X rows along Y, then Y-Z rows along X). diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index e6dcfeadb..1526e08ed 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -326,6 +326,32 @@ impl StructureRegistry { rings } /// RandomSpreadStructurePlacement.getPotentialStructureChunk et al. + /// RandomSpreadStructurePlacement.getPotentialStructureChunk for the + /// sector holding chunk (`x`, `z`); `None` for other placements. + pub fn potential_chunk(set: &StructureSet, seed: i64, x: i32, z: i32) -> Option { + let Placement::RandomSpread { + spacing, + separation, + triangular, + } = set.placement + else { + return None; + }; + let (gx, gz) = (x.div_euclid(spacing), z.div_euclid(spacing)); + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_large_feature_with_salt(seed, gx, gz, set.salt); + let limit = spacing - separation; + let spread = |r: &mut WorldgenRandom| { + if triangular { + (r.next_int_bound(limit).unwrap_or(0) + r.next_int_bound(limit).unwrap_or(0)) / 2 + } else { + r.next_int_bound(limit).unwrap_or(0) + } + }; + let sx = spread(&mut random); + let sz = spread(&mut random); + Some(ChunkPos::new(gx * spacing + sx, gz * spacing + sz)) + } pub fn is_structure_chunk( &self, set: &StructureSet, @@ -386,6 +412,15 @@ impl StructureRegistry { } } } +impl StructureSet { + /// The random spread's spacing in chunks (`None` for rings). + pub fn spacing(&self) -> Option { + match self.placement { + Placement::RandomSpread { spacing, .. } => Some(spacing), + _ => None, + } + } +} fn reduce(method: Reduction, seed: i64, salt: i32, x: i32, z: i32, probability: f32) -> bool { let mut random = WorldgenRandom::new(LegacyRandom::new(0)); match method { diff --git a/crates/horizon-world/src/worldgen/structure/template.rs b/crates/horizon-world/src/worldgen/structure/template.rs index c4e9b4f9f..149033b8c 100644 --- a/crates/horizon-world/src/worldgen/structure/template.rs +++ b/crates/horizon-world/src/worldgen/structure/template.rs @@ -33,10 +33,18 @@ impl Palette { &self.blocks } } +/// StructureTemplate.StructureEntityInfo: an entity saved with the template. +#[derive(Clone, Debug)] +pub struct EntityInfo { + pub pos: [f64; 3], + pub block_pos: [i32; 3], + pub nbt: Compound, +} #[derive(Debug)] pub struct StructureTemplate { pub size: [i32; 3], palettes: Vec, + pub entities: Vec, } fn int_list(tag: Option<&Tag>) -> [i32; 3] { @@ -123,6 +131,7 @@ impl StructureTemplate { Self { size: [0; 3], palettes: Vec::new(), + entities: Vec::new(), } } /// StructureTemplate.load. Blocks are ordered as vanilla orders them: @@ -199,7 +208,54 @@ impl StructureTemplate { _ => load(&[]), }, } - Self { size, palettes } + let mut entities = Vec::new(); + if let Some(Tag::List(list)) = get(root, "entities") { + for e in list { + let Tag::Compound(e) = e else { continue }; + let Some(Tag::Compound(nbt)) = get(e, "nbt") else { + continue; + }; + let mut pos = [0.0; 3]; + if let Some(Tag::List(p)) = get(e, "pos") { + for (slot, v) in pos.iter_mut().zip(p) { + if let Tag::Double(bits) = v { + *slot = f64::from_bits(*bits); + } + } + } + entities.push(EntityInfo { + pos, + block_pos: int_list(get(e, "blockPos")), + nbt: nbt.clone(), + }); + } + } + Self { + size, + palettes, + entities, + } + } + /// StructureTemplate.transform(Vec3, ...): entity positions. + pub fn transform_vec( + pos: [f64; 3], + mirror: Mirror, + rotation: Rotation, + pivot: [i32; 3], + ) -> [f64; 3] { + let [mut x, y, mut z] = pos; + match mirror { + Mirror::LeftRight => z = 1.0 - z, + Mirror::FrontBack => x = 1.0 - x, + Mirror::None => {} + } + let (px, pz) = (f64::from(pivot[0]), f64::from(pivot[2])); + match rotation { + Rotation::Counterclockwise90 => [px - pz + z, y, px + pz + 1.0 - x], + Rotation::Clockwise90 => [px + pz + 1.0 - z, y, pz - px + x], + Rotation::Clockwise180 => [px + px + 1.0 - x, y, pz + pz + 1.0 - z], + Rotation::None => [x, y, z], + } } pub fn palettes(&self) -> &[Palette] { &self.palettes