Merge pull request #116 from ludovic111/fix/world-spawn-seed
Find a new world's spawn as vanilla does (NoiseSpawnFinder, setInitialSpawn, PlayerSpawnFinder)
This commit is contained in:
@@ -96,6 +96,20 @@ impl SceneCollisions<'_, '_> {
|
||||
/// `noCollision(null, box)`: block collisions under the empty collision
|
||||
/// context, as entity-less queries such as spawn checks use.
|
||||
pub fn no_collision_empty<W, E>(world: &mut W, bounds: Aabb) -> bool
|
||||
where
|
||||
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
|
||||
{
|
||||
no_collision_in(world, bounds, false)
|
||||
}
|
||||
/// `noCollision(null, box, true)`: the same with liquids colliding as
|
||||
/// blocks (`CollisionContext.emptyWithFluidCollisions`).
|
||||
pub fn no_collision_or_liquid<W, E>(world: &mut W, bounds: Aabb) -> bool
|
||||
where
|
||||
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
|
||||
{
|
||||
no_collision_in(world, bounds, true)
|
||||
}
|
||||
fn no_collision_in<W, E>(world: &mut W, bounds: Aabb, fluids: bool) -> bool
|
||||
where
|
||||
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
|
||||
{
|
||||
@@ -103,7 +117,7 @@ where
|
||||
world,
|
||||
CollisionCheckRequest {
|
||||
entity: EntityIdentity(0),
|
||||
context: CollisionContext::empty(false),
|
||||
context: CollisionContext::empty(fluids),
|
||||
bounds,
|
||||
candidate_budget: 1_000_000,
|
||||
},
|
||||
|
||||
@@ -39,6 +39,10 @@ impl FlatTerrain {
|
||||
biome: biomes.id(&biome),
|
||||
})
|
||||
}
|
||||
/// FlatLevelSource.getSpawnHeight: the top of the layers.
|
||||
pub fn spawn_height(&self) -> i32 {
|
||||
crate::chunk::MIN_Y + self.layers.len().min(crate::chunk::HEIGHT as usize) as i32
|
||||
}
|
||||
}
|
||||
impl ChunkGenerator for FlatTerrain {
|
||||
type Worker = ();
|
||||
|
||||
@@ -45,6 +45,7 @@ mod ghasts;
|
||||
mod golems;
|
||||
mod growth;
|
||||
mod hand;
|
||||
mod initial_spawn;
|
||||
mod item_draw;
|
||||
mod item_particles;
|
||||
mod jukebox;
|
||||
@@ -685,7 +686,13 @@ struct Game<'a> {
|
||||
book: Option<books::BookScreen>,
|
||||
/// Lecterns whose page-turn pulse is running (ticks left).
|
||||
lectern_pulses: Vec<((i32, i32, i32), i32)>,
|
||||
/// Steps of the world spawn's chunk spiral taken so far.
|
||||
spawn_search: u32,
|
||||
/// The world spawn search's origin chunk and fallback height, once known.
|
||||
spawn_origin: Option<((i32, i32), i32)>,
|
||||
spawn_spiral: horizon_client::world_spawn::ChunkSpiral,
|
||||
/// A new player's spawn search, while its candidates' chunks load.
|
||||
player_spawn: Option<horizon_client::world_spawn::PlayerSpawnFinder>,
|
||||
mobs: Vec<Mob>,
|
||||
arrows: Vec<Arrow>,
|
||||
creatures: creatures::Creatures,
|
||||
@@ -2502,31 +2509,6 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The i-th world spawn search point: a square spiral in 48-block steps.
|
||||
fn spawn_candidate(i: u32) -> (i32, i32) {
|
||||
if i == 0 {
|
||||
return (0, 0);
|
||||
}
|
||||
let mut k = 1u32;
|
||||
let mut ring = 1i32;
|
||||
loop {
|
||||
let points = 8 * ring as u32;
|
||||
if i < k + points {
|
||||
let j = (i - k) as i32;
|
||||
let side = j / (2 * ring);
|
||||
let t = j % (2 * ring) - ring;
|
||||
let (x, z) = match side {
|
||||
0 => (t, -ring),
|
||||
1 => (ring, t),
|
||||
2 => (-t, ring),
|
||||
_ => (-ring, -t),
|
||||
};
|
||||
return (x * 48, z * 48);
|
||||
}
|
||||
k += points;
|
||||
ring += 1;
|
||||
}
|
||||
}
|
||||
/// A column whose surface is a full solid, non-fluid, non-leaf block open to the sky.
|
||||
fn land_column(&self, x: i32, z: i32) -> Option<i32> {
|
||||
if self.dim == Dim::Nether {
|
||||
@@ -2585,48 +2567,48 @@ impl Game<'_> {
|
||||
.spawn
|
||||
.map(|s| Vec3::new(s[0] + 0.5, s[1], s[2] + 0.5));
|
||||
}
|
||||
let anchor = match saved.or(self.spawn) {
|
||||
Some(p) => (p.x.floor() as i32, p.z.floor() as i32),
|
||||
None => Self::spawn_candidate(self.spawn_search),
|
||||
};
|
||||
let (cx, cz) = (anchor.0 >> 4, anchor.1 >> 4);
|
||||
self.streaming.center = (cx, cz);
|
||||
if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
|
||||
return Ok(());
|
||||
}
|
||||
let feet = if let Some(p) = saved {
|
||||
let (cx, cz) = ((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4);
|
||||
self.streaming.center = (cx, cz);
|
||||
if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
|
||||
return Ok(());
|
||||
}
|
||||
self.level.position = None;
|
||||
p
|
||||
} else if let Some(s) = self.spawn {
|
||||
} else if self.spawn.is_none() || self.player_spawn.is_some() {
|
||||
// A new world: its spawn, then the first player around it.
|
||||
if self.spawn.is_none() {
|
||||
let Some([x, y, z]) = self.find_world_spawn()? else {
|
||||
return Ok(());
|
||||
};
|
||||
self.spawn = Some(Vec3::new(
|
||||
f64::from(x) + 0.5,
|
||||
f64::from(y),
|
||||
f64::from(z) + 0.5,
|
||||
));
|
||||
self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]);
|
||||
}
|
||||
let s = self
|
||||
.level
|
||||
.spawn
|
||||
.unwrap_or_default()
|
||||
.map(|v| v.floor() as i32);
|
||||
let Some(feet) = self.find_player_spawn(s)? else {
|
||||
return Ok(());
|
||||
};
|
||||
feet
|
||||
} else {
|
||||
let s = self.spawn.unwrap_or_default();
|
||||
let (cx, cz) = ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4);
|
||||
self.streaming.center = (cx, cz);
|
||||
if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
|
||||
return Ok(());
|
||||
}
|
||||
// WorldSpawn: the stored column, lifted onto its current surface.
|
||||
let y = self
|
||||
.land_column(s.x.floor() as i32, s.z.floor() as i32)
|
||||
.map_or(s.y, f64::from);
|
||||
Vec3::new(s.x, y.max(s.y), s.z)
|
||||
} else {
|
||||
let mut best: Option<(i64, i32, i32, i32)> = None;
|
||||
for z in (cz - 1) * 16..(cz + 2) * 16 {
|
||||
for x in (cx - 1) * 16..(cx + 2) * 16 {
|
||||
if let Some(y) = self.land_column(x, z) {
|
||||
let d = i64::from(x - anchor.0).pow(2) + i64::from(z - anchor.1).pow(2);
|
||||
if best.is_none_or(|b| d < b.0) {
|
||||
best = Some((d, x, y, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match best {
|
||||
Some((_, x, y, z)) => {
|
||||
let spawn = Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5);
|
||||
self.spawn = Some(spawn);
|
||||
self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]);
|
||||
spawn
|
||||
}
|
||||
None => {
|
||||
self.spawn_search += 1;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut player = PlayerMotion::new(self.motion, feet)?;
|
||||
player.yaw = self.yaw;
|
||||
@@ -5559,6 +5541,9 @@ impl Game<'_> {
|
||||
self.player = None;
|
||||
self.spawn = None;
|
||||
self.spawn_search = 0;
|
||||
self.spawn_origin = None;
|
||||
self.spawn_spiral = Default::default();
|
||||
self.player_spawn = None;
|
||||
self.mobs.clear();
|
||||
self.creatures.reset_trader();
|
||||
self.arrows.clear();
|
||||
@@ -8969,6 +8954,9 @@ pub fn run() -> Result<()> {
|
||||
book: None,
|
||||
lectern_pulses: Vec::new(),
|
||||
spawn_search: 0,
|
||||
spawn_origin: None,
|
||||
spawn_spiral: Default::default(),
|
||||
player_spawn: None,
|
||||
mobs: Vec::new(),
|
||||
arrows: Vec::new(),
|
||||
creatures: Default::default(),
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
//! A new world's spawn and its first player's position: MinecraftServer.
|
||||
//! setInitialSpawn walks a chunk spiral around NoiseBasedChunkGenerator.
|
||||
//! getOrigin, then PlayerSpawnFinder.findSpawn picks a free column around
|
||||
//! the world spawn within the respawn radius.
|
||||
use super::{Game, dispenser::entity_random};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Properties,
|
||||
chunk::{HEIGHT, MIN_Y},
|
||||
collisions::{SceneCollisions, no_collision_or_liquid},
|
||||
world::World,
|
||||
world_spawn::{
|
||||
PlayerSpawnFinder, SpawnCandidate, SpawnLevel, level_respawn_pos, spawn_pos_in_chunk,
|
||||
},
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape},
|
||||
position::BlockPos,
|
||||
random::RandomSource,
|
||||
};
|
||||
use horizon_world::{
|
||||
block_collision::BlockCollisionRegistry, collision_context::CollisionContext,
|
||||
heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates,
|
||||
};
|
||||
|
||||
/// The loaded world as the spawn searches query it.
|
||||
struct Columns<'a, 'r> {
|
||||
world: &'a World,
|
||||
properties: &'a Properties,
|
||||
binding: &'a BlockCollisionRegistry<'r>,
|
||||
}
|
||||
impl SpawnLevel for Columns<'_, '_> {
|
||||
fn min_y(&self) -> i32 {
|
||||
MIN_Y
|
||||
}
|
||||
fn height(&self, kind: HeightmapType, x: i32, z: i32) -> i32 {
|
||||
(MIN_Y..MIN_Y + HEIGHT)
|
||||
.rev()
|
||||
.find(|&y| kind.is_opaque(self.properties.heightmap_state(self.world.block(x, y, z))))
|
||||
.map_or(MIN_Y, |y| y + 1)
|
||||
}
|
||||
fn has_fluid(&self, x: i32, y: i32, z: i32) -> bool {
|
||||
use horizon_world::heightmap::HeightmapState;
|
||||
self.properties
|
||||
.heightmap_state(self.world.block(x, y, z))
|
||||
.has_fluid()
|
||||
}
|
||||
fn top_face_full(&self, x: i32, y: i32, z: i32) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.binding,
|
||||
subject: None,
|
||||
};
|
||||
let state = self.world.block(x, y, z);
|
||||
let Ok(shape) = self.binding.collision_shape_with_context(
|
||||
&mut scene,
|
||||
state,
|
||||
BlockPos::new(x, y, z),
|
||||
&CollisionContext::empty(false),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
shape.face_shape(Direction::Up).is_ok_and(|face| {
|
||||
VoxelShape::block()
|
||||
.join_is_not_empty(&face, ShapeOp::XOR)
|
||||
.is_ok_and(|differs| !differs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn spawn_columns(&self) -> Columns<'_, '_> {
|
||||
Columns {
|
||||
world: &self.world,
|
||||
properties: &self.res.assets.properties,
|
||||
binding: self.collision,
|
||||
}
|
||||
}
|
||||
/// ChunkGenerator.getOrigin and getSpawnHeight of the overworld.
|
||||
fn spawn_origin(&self) -> Result<((i32, i32), i32)> {
|
||||
if let Some(flat) =
|
||||
horizon_client::save::world_gen_settings(&self.world_root).and_then(|s| {
|
||||
horizon_client::flatgen::FlatTerrain::from_settings(
|
||||
&s,
|
||||
self.res.assets.registry,
|
||||
&self.res.biomes,
|
||||
)
|
||||
})
|
||||
{
|
||||
return Ok(((0, 0), flat.spawn_height()));
|
||||
}
|
||||
if self.options.test_terrain {
|
||||
return Ok(((0, 0), 64));
|
||||
}
|
||||
let origin = match self.end.locator() {
|
||||
Some(terrain) => terrain.origin()?,
|
||||
None => horizon_core::position::ChunkPos::new(0, 0),
|
||||
};
|
||||
Ok(((origin.x, origin.z), 64))
|
||||
}
|
||||
/// MinecraftServer.setInitialSpawn: the first chunk of the spiral with a
|
||||
/// valid respawn column gives the world spawn, else the origin chunk's
|
||||
/// centre at the spawn height. None while a chunk to test is loading.
|
||||
pub(super) fn find_world_spawn(&mut self) -> Result<Option<[i32; 3]>> {
|
||||
let ((ox, oz), height) = match self.spawn_origin {
|
||||
Some(origin) => origin,
|
||||
None => *self.spawn_origin.insert(self.spawn_origin()?),
|
||||
};
|
||||
while let Some((dx, dz)) = self.spawn_spiral.current() {
|
||||
self.spawn_search = self.spawn_spiral.steps() as u32;
|
||||
if self.spawn_spiral.tested() {
|
||||
let (cx, cz) = (ox + dx, oz + dz);
|
||||
if !self.streaming.is_lit(cx, cz) {
|
||||
self.streaming.center = (cx, cz);
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(pos) = spawn_pos_in_chunk(&self.spawn_columns(), cx, cz) {
|
||||
return Ok(Some(pos));
|
||||
}
|
||||
}
|
||||
self.spawn_spiral.advance();
|
||||
}
|
||||
Ok(Some([ox * 16 + 8, height, oz * 16 + 8]))
|
||||
}
|
||||
/// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a
|
||||
/// player who has no position yet. None while a candidate's chunk loads.
|
||||
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
|
||||
let mut finder = match self.player_spawn {
|
||||
Some(finder) => finder,
|
||||
None if self.level.game_mode == 2 => {
|
||||
// Adventure mode: the suggestion itself.
|
||||
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
|
||||
finder.next_candidate();
|
||||
finder
|
||||
}
|
||||
None => {
|
||||
let mut radius = self.ui.rules.int("respawn_radius").max(0);
|
||||
let to_border = self
|
||||
.border
|
||||
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
|
||||
.floor() as i32;
|
||||
if to_border < radius {
|
||||
radius = to_border;
|
||||
}
|
||||
if to_border <= 1 {
|
||||
radius = 1;
|
||||
}
|
||||
PlayerSpawnFinder::new(suggestion, radius, |n| {
|
||||
entity_random().next_int_bound(n).unwrap_or(0)
|
||||
})
|
||||
}
|
||||
};
|
||||
let found = loop {
|
||||
let Some(candidate) = finder.next_candidate() else {
|
||||
break Some(self.fixup_spawn_height(suggestion));
|
||||
};
|
||||
let (x, z) = match candidate {
|
||||
SpawnCandidate::Column(x, z) => (x, z),
|
||||
SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]),
|
||||
};
|
||||
if !self.streaming.is_lit(x >> 4, z >> 4) {
|
||||
self.streaming.center = (x >> 4, z >> 4);
|
||||
finder.retry();
|
||||
break None;
|
||||
}
|
||||
match candidate {
|
||||
SpawnCandidate::Column(x, z) => {
|
||||
if let Some(pos) = level_respawn_pos(&self.spawn_columns(), x, z)
|
||||
&& self.player_fits(pos)
|
||||
{
|
||||
break Some(bottom_center(pos));
|
||||
}
|
||||
}
|
||||
SpawnCandidate::Suggestion => break Some(self.fixup_spawn_height(suggestion)),
|
||||
}
|
||||
};
|
||||
self.player_spawn = found.is_none().then_some(finder);
|
||||
Ok(found)
|
||||
}
|
||||
/// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the
|
||||
/// block's bottom centre touches no block or liquid.
|
||||
fn player_fits(&self, pos: [i32; 3]) -> bool {
|
||||
let feet = bottom_center(pos);
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(feet.x - 0.3, feet.y, feet.z - 0.3),
|
||||
Vec3::new(feet.x + 0.3, feet.y + 1.8, feet.z + 0.3),
|
||||
);
|
||||
let mut scene = SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
subject: None,
|
||||
};
|
||||
no_collision_or_liquid(&mut scene, bounds)
|
||||
}
|
||||
/// PlayerSpawnFinder.fixupSpawnHeight: up out of anything solid, then
|
||||
/// down onto the ground.
|
||||
fn fixup_spawn_height(&self, pos: [i32; 3]) -> Vec3 {
|
||||
let [x, mut y, z] = pos;
|
||||
while !self.player_fits([x, y, z]) && y < MIN_Y + HEIGHT - 1 {
|
||||
y += 1;
|
||||
}
|
||||
y -= 1;
|
||||
while self.player_fits([x, y, z]) && y > MIN_Y {
|
||||
y -= 1;
|
||||
}
|
||||
bottom_center([x, y + 1, z])
|
||||
}
|
||||
}
|
||||
|
||||
/// Vec3.atBottomCenterOf.
|
||||
fn bottom_center(pos: [i32; 3]) -> Vec3 {
|
||||
Vec3::new(
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]),
|
||||
f64::from(pos[2]) + 0.5,
|
||||
)
|
||||
}
|
||||
@@ -140,6 +140,7 @@ pub mod weather;
|
||||
pub mod widgets;
|
||||
pub mod window;
|
||||
pub mod world;
|
||||
pub mod world_spawn;
|
||||
pub mod worldborder;
|
||||
pub mod zip;
|
||||
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
@@ -126,6 +126,10 @@ impl VanillaTerrain {
|
||||
let worker = worker.get_or_insert_with(|| self.generator.worker());
|
||||
worker.jigsaw_pieces(query)
|
||||
}
|
||||
/// NoiseBasedChunkGenerator.getOrigin: where the world spawn search starts.
|
||||
pub fn origin(&self) -> crate::Result<ChunkPos> {
|
||||
Ok(self.generator.origin()?)
|
||||
}
|
||||
/// Concentric ring positions of a structure set (strongholds), once known.
|
||||
pub fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
|
||||
self.generator.ring_positions(set)
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
//! Where a new world's spawn is and where a player first appears around it:
|
||||
//! MinecraftServer.setInitialSpawn's chunk spiral and PlayerSpawnFinder.
|
||||
use horizon_world::heightmap::HeightmapType;
|
||||
|
||||
/// The block queries the spawn searches make on full (decorated, lit) chunks.
|
||||
pub trait SpawnLevel {
|
||||
fn min_y(&self) -> i32;
|
||||
/// `chunk.getHeight(kind, x, z)`: one above the column's highest block
|
||||
/// matching the heightmap, or the minimum height.
|
||||
fn height(&self, kind: HeightmapType, x: i32, z: i32) -> i32;
|
||||
/// `!getBlockState(pos).getFluidState().isEmpty()`.
|
||||
fn has_fluid(&self, x: i32, y: i32, z: i32) -> bool;
|
||||
/// `Block.isFaceFull(state.getCollisionShape(level, pos), Direction.UP)`.
|
||||
fn top_face_full(&self, x: i32, y: i32, z: i32) -> bool;
|
||||
}
|
||||
|
||||
/// PlayerSpawnFinder.getLevelRespawnPos in a dimension without a ceiling:
|
||||
/// the block above the column's top full-topped collision, unless water,
|
||||
/// lava or only non-colliding blocks are on top.
|
||||
pub fn level_respawn_pos(level: &impl SpawnLevel, x: i32, z: i32) -> Option<[i32; 3]> {
|
||||
let top = level.height(HeightmapType::MotionBlocking, x, z);
|
||||
if top < level.min_y() {
|
||||
return None;
|
||||
}
|
||||
let surface = level.height(HeightmapType::WorldSurface, x, z);
|
||||
if surface <= top && surface > level.height(HeightmapType::OceanFloor, x, z) {
|
||||
return None;
|
||||
}
|
||||
for y in (level.min_y()..=top + 1).rev() {
|
||||
if level.has_fluid(x, y, z) {
|
||||
break;
|
||||
}
|
||||
if level.top_face_full(x, y, z) {
|
||||
return Some([x, y + 1, z]);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// PlayerSpawnFinder.getSpawnPosInChunk: the first valid column, x-major.
|
||||
pub fn spawn_pos_in_chunk(level: &impl SpawnLevel, cx: i32, cz: i32) -> Option<[i32; 3]> {
|
||||
for x in cx * 16..cx * 16 + 16 {
|
||||
for z in cz * 16..cz * 16 + 16 {
|
||||
if let Some(pos) = level_respawn_pos(level, x, z) {
|
||||
return Some(pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// setInitialSpawn's walk: Mth.square(11) steps of a square spiral around
|
||||
/// the origin chunk, testing the steps within 5 chunks of it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ChunkSpiral {
|
||||
step: i32,
|
||||
x: i32,
|
||||
z: i32,
|
||||
dx: i32,
|
||||
dz: i32,
|
||||
}
|
||||
impl Default for ChunkSpiral {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
impl ChunkSpiral {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
step: 0,
|
||||
x: 0,
|
||||
z: 0,
|
||||
dx: 0,
|
||||
dz: -1,
|
||||
}
|
||||
}
|
||||
/// Steps taken so far.
|
||||
pub fn steps(&self) -> i32 {
|
||||
self.step
|
||||
}
|
||||
/// The chunk offset to test now, or None once the walk is over.
|
||||
pub fn current(&self) -> Option<(i32, i32)> {
|
||||
(self.step < 11 * 11).then_some((self.x, self.z))
|
||||
}
|
||||
/// Whether `current` lies within the tested 11 by 11 chunks.
|
||||
pub fn tested(&self) -> bool {
|
||||
(-5..=5).contains(&self.x) && (-5..=5).contains(&self.z)
|
||||
}
|
||||
pub fn advance(&mut self) {
|
||||
if self.x == self.z
|
||||
|| (self.x < 0 && self.x == -self.z)
|
||||
|| (self.x > 0 && self.x == 1 - self.z)
|
||||
{
|
||||
(self.dx, self.dz) = (-self.dz, self.dx);
|
||||
}
|
||||
self.x += self.dx;
|
||||
self.z += self.dz;
|
||||
self.step += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// What PlayerSpawnFinder tries next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SpawnCandidate {
|
||||
/// A column to test with `level_respawn_pos` and a free player box.
|
||||
Column(i32, i32),
|
||||
/// Every column failed: the suggestion itself, height fixed up.
|
||||
Suggestion,
|
||||
}
|
||||
|
||||
/// PlayerSpawnFinder: the columns of the square of `radius` around the
|
||||
/// suggestion in a random coprime-stride order, then the suggestion.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PlayerSpawnFinder {
|
||||
pub suggestion: [i32; 3],
|
||||
radius: i32,
|
||||
count: i32,
|
||||
coprime: i32,
|
||||
offset: i32,
|
||||
next: i32,
|
||||
}
|
||||
impl PlayerSpawnFinder {
|
||||
/// `radius` is the respawn radius already clamped to the world border
|
||||
/// (findSpawn); `random(n)` draws the start offset in `0..n`.
|
||||
pub fn new(suggestion: [i32; 3], radius: i32, random: impl FnOnce(i32) -> i32) -> Self {
|
||||
let side = i64::from(radius) * 2 + 1;
|
||||
let count = (side * side).min(1024) as i32;
|
||||
Self {
|
||||
suggestion,
|
||||
radius,
|
||||
count,
|
||||
coprime: if count <= 16 { count - 1 } else { 17 },
|
||||
offset: random(count),
|
||||
next: 0,
|
||||
}
|
||||
}
|
||||
/// The next candidate, None once the suggestion was handed out.
|
||||
pub fn next_candidate(&mut self) -> Option<SpawnCandidate> {
|
||||
let index = self.next;
|
||||
if index > self.count {
|
||||
return None;
|
||||
}
|
||||
self.next += 1;
|
||||
if index == self.count {
|
||||
return Some(SpawnCandidate::Suggestion);
|
||||
}
|
||||
let value = (self.offset + self.coprime * index) % self.count;
|
||||
let side = self.radius * 2 + 1;
|
||||
Some(SpawnCandidate::Column(
|
||||
self.suggestion[0] + value % side - self.radius,
|
||||
self.suggestion[2] + value / side - self.radius,
|
||||
))
|
||||
}
|
||||
/// Hand the last candidate out again (its chunk was not loaded yet).
|
||||
pub fn retry(&mut self) {
|
||||
self.next -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn spiral_walks_out_from_the_origin_like_set_initial_spawn() {
|
||||
let mut spiral = ChunkSpiral::default();
|
||||
let mut seen = Vec::new();
|
||||
while let Some(at) = spiral.current() {
|
||||
if spiral.tested() {
|
||||
seen.push(at);
|
||||
}
|
||||
spiral.advance();
|
||||
}
|
||||
assert_eq!(
|
||||
&seen[..9],
|
||||
&[
|
||||
(0, 0),
|
||||
(1, 0),
|
||||
(1, 1),
|
||||
(0, 1),
|
||||
(-1, 1),
|
||||
(-1, 0),
|
||||
(-1, -1),
|
||||
(0, -1),
|
||||
(1, -1)
|
||||
]
|
||||
);
|
||||
seen.sort_unstable();
|
||||
seen.dedup();
|
||||
assert_eq!(seen.len(), 121);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finder_visits_every_column_once_then_the_suggestion() {
|
||||
let mut finder = PlayerSpawnFinder::new([100, 70, -40], 10, |n| n / 3);
|
||||
let mut columns = Vec::new();
|
||||
while let Some(c) = finder.next_candidate() {
|
||||
columns.push(c);
|
||||
}
|
||||
assert_eq!(columns.len(), 442);
|
||||
assert_eq!(columns.last(), Some(&SpawnCandidate::Suggestion));
|
||||
columns.sort_by_key(|c| format!("{c:?}"));
|
||||
columns.dedup();
|
||||
assert_eq!(columns.len(), 442);
|
||||
let mut zero = PlayerSpawnFinder::new([5, 64, 5], 0, |_| 0);
|
||||
assert_eq!(zero.next_candidate(), Some(SpawnCandidate::Column(5, 5)));
|
||||
assert_eq!(zero.next_candidate(), Some(SpawnCandidate::Suggestion));
|
||||
assert_eq!(zero.next_candidate(), None);
|
||||
}
|
||||
|
||||
struct Flat {
|
||||
top: i32,
|
||||
water: bool,
|
||||
}
|
||||
impl SpawnLevel for Flat {
|
||||
fn min_y(&self) -> i32 {
|
||||
-64
|
||||
}
|
||||
fn height(&self, kind: HeightmapType, _: i32, _: i32) -> i32 {
|
||||
match kind {
|
||||
HeightmapType::OceanFloor if self.water => self.top - 3,
|
||||
_ => self.top + 1,
|
||||
}
|
||||
}
|
||||
fn has_fluid(&self, _: i32, y: i32, _: i32) -> bool {
|
||||
self.water && y <= self.top && y > self.top - 3
|
||||
}
|
||||
fn top_face_full(&self, _: i32, y: i32, _: i32) -> bool {
|
||||
y <= self.top
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn respawn_column_stands_on_land_not_water() {
|
||||
assert_eq!(
|
||||
level_respawn_pos(
|
||||
&Flat {
|
||||
top: 70,
|
||||
water: false
|
||||
},
|
||||
3,
|
||||
4
|
||||
),
|
||||
Some([3, 71, 4])
|
||||
);
|
||||
assert_eq!(
|
||||
level_respawn_pos(
|
||||
&Flat {
|
||||
top: 62,
|
||||
water: true
|
||||
},
|
||||
3,
|
||||
4
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
spawn_pos_in_chunk(
|
||||
&Flat {
|
||||
top: 70,
|
||||
water: false
|
||||
},
|
||||
-2,
|
||||
1
|
||||
),
|
||||
Some([-32, 71, 16])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! NoiseSpawnFinder for tools/test_world_spawn_parity.py: for each seed, the
|
||||
//! column the overworld's spawn search starts from and its chunk
|
||||
//! (NoiseBasedChunkGenerator.getOrigin), as `seed x z chunk_x chunk_z` lines.
|
||||
//!
|
||||
//! usage: spawn_origin <client resource directory> <seed>...
|
||||
use horizon_world::{
|
||||
DATA_VERSION,
|
||||
nbt::Tag,
|
||||
registry::BlockRegistry,
|
||||
worldgen::generator::{GeneratorData, OverworldGenerator},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{fs, path::Path};
|
||||
|
||||
type Error = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
fn tag(v: &Value) -> Tag {
|
||||
match v {
|
||||
Value::String(s) => Tag::String(s.as_str().into()),
|
||||
Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32),
|
||||
Value::Array(a) => Tag::List(a.iter().map(tag).collect()),
|
||||
Value::Object(o) => {
|
||||
Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect())
|
||||
}
|
||||
_ => panic!("invalid registry metadata"),
|
||||
}
|
||||
}
|
||||
fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> {
|
||||
let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?;
|
||||
let states = facts["states"].as_array().ok_or("facts states")?;
|
||||
let registry = BlockRegistry::from_nbt(&Tag::compound([
|
||||
("DataVersion", Tag::Int(DATA_VERSION)),
|
||||
(
|
||||
"states",
|
||||
Tag::List(states.iter().map(|v| tag(&v[4])).collect()),
|
||||
),
|
||||
("defaults", tag(&facts["defaults"])),
|
||||
]))?;
|
||||
Ok(Box::leak(Box::new(registry)))
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Error> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?);
|
||||
let data = GeneratorData::load(&resources.join("worldgen"), registry(&resources)?)?;
|
||||
for seed in args {
|
||||
let seed: i64 = seed.parse()?;
|
||||
let generator = OverworldGenerator::new(data.clone(), seed)?;
|
||||
let [x, z] = generator.spawn_position()?;
|
||||
let origin = generator.origin()?;
|
||||
println!("{seed} {x} {z} {} {}", origin.x, origin.z);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -61,6 +61,7 @@ pub mod sculk;
|
||||
pub mod settings;
|
||||
pub mod simple_block;
|
||||
pub mod snow_freeze;
|
||||
pub mod spawn_finder;
|
||||
pub mod speleothem;
|
||||
pub mod spike;
|
||||
pub mod spring;
|
||||
|
||||
@@ -20,7 +20,7 @@ use super::{
|
||||
biome_temperature::{BiomeTemperature, BiomeTemperatureSettings},
|
||||
carver::{CarverCatalog, WorldCarver, generate_carving_mask},
|
||||
carving::{CarvingBlocks, apply_carving_mask},
|
||||
climate::{ClimateSampler, quantize},
|
||||
climate::{ClimateSampler, decode_parameter, quantize},
|
||||
decode_noise,
|
||||
density::DensityRegistry,
|
||||
material_condition::{
|
||||
@@ -31,6 +31,7 @@ use super::{
|
||||
material_stage::{SurfaceInputs, TopMaterialInputs, build_surface},
|
||||
material_surface::{ClayBandBlocks, MaterialSurface},
|
||||
router::{NoiseRouter, RouterField, RouterSamplers},
|
||||
spawn_finder::{SpawnTargetPoint, find_spawn_position},
|
||||
tags::TagDefinitions,
|
||||
terrain::{PreLightChunkStage, TerrainAquifer, TerrainBlockStates, TerrainChunk, fill_noise},
|
||||
};
|
||||
@@ -608,6 +609,9 @@ struct Pipeline<R: RandomSource> {
|
||||
carver_cache: Mutex<HashMap<(i32, i32), BiomeId>>,
|
||||
pub(super) decoration: Option<super::generator_decoration::Decoration>,
|
||||
pub(super) structures: Option<super::generator_structures::StructureState>,
|
||||
/// The noise settings' `spawn_target` points.
|
||||
spawn_target: Vec<SpawnTargetPoint>,
|
||||
spawn_position: std::sync::OnceLock<[i32; 2]>,
|
||||
}
|
||||
const CACHE_LIMIT: usize = 16384;
|
||||
type BiomeCache = Mutex<HashMap<(i32, i32), Arc<BiomeChunk<BiomeId>>>>;
|
||||
@@ -706,6 +710,27 @@ where
|
||||
.ok_or_else(|| resource("material_rule"))?;
|
||||
let rule = library.rule(rule_name)?;
|
||||
let preliminary = router.get(RouterField::ChunkSurfaceLevel).clone();
|
||||
let spawn_target = match settings_json.get("spawn_target") {
|
||||
Some(Value::Array(points)) => points
|
||||
.iter()
|
||||
.map(|point| {
|
||||
let Value::Object(fields) = point else {
|
||||
return Err(resource("spawn_target point"));
|
||||
};
|
||||
let parameters = fields
|
||||
.iter()
|
||||
.map(|(name, interval)| {
|
||||
Ok((
|
||||
library.named_density(name)?,
|
||||
decode_parameter(&interval.to_string())?,
|
||||
))
|
||||
})
|
||||
.collect::<Result<_, GeneratorError>>()?;
|
||||
Ok(SpawnTargetPoint { parameters })
|
||||
})
|
||||
.collect::<Result<_, GeneratorError>>()?,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let source = data
|
||||
.source_catalog
|
||||
.decode(&generator["biome_source"].to_string())?
|
||||
@@ -783,6 +808,8 @@ where
|
||||
carver_cache: Mutex::new(HashMap::new()),
|
||||
decoration: None,
|
||||
structures: None,
|
||||
spawn_target,
|
||||
spawn_position: std::sync::OnceLock::new(),
|
||||
};
|
||||
pipeline.decoration =
|
||||
super::generator_decoration::Decoration::new(&pipeline.data, &pipeline.source)?;
|
||||
@@ -1363,6 +1390,7 @@ trait SeededPipeline: Send + Sync {
|
||||
fn unsupported_features(&self) -> Vec<(String, String)>;
|
||||
fn forget_structure_starts(&self);
|
||||
fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>>;
|
||||
fn spawn_position(&self) -> Result<[i32; 2], GeneratorError>;
|
||||
fn locate(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
@@ -1462,6 +1490,19 @@ where
|
||||
fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
|
||||
self.structures.as_ref()?.cached_rings(set)
|
||||
}
|
||||
fn spawn_position(&self) -> Result<[i32; 2], GeneratorError> {
|
||||
if let Some(position) = self.spawn_position.get() {
|
||||
return Ok(*position);
|
||||
}
|
||||
// ChunkGenerator.getOrigin is 0 0 without a spawn target.
|
||||
let position = if self.spawn_target.is_empty() {
|
||||
[0, 0]
|
||||
} else {
|
||||
find_spawn_position(&self.spawn_target, &mut SamplerContext::cached())
|
||||
.map_err(|e| GeneratorError::Stage("spawn search", e.to_string()))?
|
||||
};
|
||||
Ok(*self.spawn_position.get_or_init(|| position))
|
||||
}
|
||||
fn locate(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
@@ -1745,6 +1786,16 @@ impl OverworldGenerator {
|
||||
pub fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
|
||||
self.pipeline.ring_positions(set)
|
||||
}
|
||||
/// NoiseBasedChunkGenerator.getOrigin: the chunk a new world's spawn
|
||||
/// search starts from (NoiseSpawnFinder over the `spawn_target` points).
|
||||
pub fn origin(&self) -> Result<ChunkPos, GeneratorError> {
|
||||
let [x, z] = self.spawn_position()?;
|
||||
Ok(ChunkPos::new(x >> 4, z >> 4))
|
||||
}
|
||||
/// NoiseSpawnFinder.findSpawnPosition: the column `origin` is the chunk of.
|
||||
pub fn spawn_position(&self) -> Result<[i32; 2], GeneratorError> {
|
||||
self.pipeline.spawn_position()
|
||||
}
|
||||
/// Create per-thread state. Workers are cheap; keep one per thread.
|
||||
pub fn worker(&self) -> GeneratorWorker {
|
||||
let data = self.pipeline.data();
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! NoiseSpawnFinder: where a new world's spawn search starts.
|
||||
//!
|
||||
//! NoiseBasedChunkGenerator.getOrigin samples the noise settings'
|
||||
//! `spawn_target` points (SpawnTargetPoint) around the world origin and keeps
|
||||
//! the block whose climate fits them best, biased towards 0 0. The world spawn
|
||||
//! search (MinecraftServer.setInitialSpawn) then spirals out from its chunk.
|
||||
use super::climate::{Parameter, quantize};
|
||||
use horizon_core::density::{DensitySampler, SampleError, SamplerContext};
|
||||
use horizon_core::jmath;
|
||||
use std::sync::Arc;
|
||||
|
||||
const MAX_RADIUS: f32 = 2048.0;
|
||||
|
||||
/// One `spawn_target` entry: climate intervals over named density functions.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SpawnTargetPoint {
|
||||
pub parameters: Vec<(Arc<dyn DensitySampler>, Parameter)>,
|
||||
}
|
||||
impl SpawnTargetPoint {
|
||||
/// SpawnTargetPoint.sampleFitness: the summed squared distances of the
|
||||
/// quantized samples to their intervals.
|
||||
pub fn sample_fitness(
|
||||
&self,
|
||||
context: &mut SamplerContext,
|
||||
position: [i32; 3],
|
||||
) -> Result<i64, SampleError> {
|
||||
let mut fitness = 0i64;
|
||||
for (function, parameter) in &self.parameters {
|
||||
let distance = parameter.distance(quantize(function.sample_value(context, position)?));
|
||||
fitness = fitness.wrapping_add(distance.wrapping_mul(distance));
|
||||
}
|
||||
Ok(fitness)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Candidate {
|
||||
x: i32,
|
||||
z: i32,
|
||||
fitness: i64,
|
||||
}
|
||||
|
||||
/// NoiseSpawnFinder.findSpawnPosition: the best block column (x, z) of a
|
||||
/// coarse then a fine radial search around the best of the two.
|
||||
pub fn find_spawn_position(
|
||||
targets: &[SpawnTargetPoint],
|
||||
context: &mut SamplerContext,
|
||||
) -> Result<[i32; 2], SampleError> {
|
||||
let mut best = fitness(targets, context, 0, 0)?;
|
||||
radial_search(targets, context, &mut best, MAX_RADIUS, 512.0)?;
|
||||
radial_search(targets, context, &mut best, 512.0, 32.0)?;
|
||||
Ok([best.x, best.z])
|
||||
}
|
||||
|
||||
/// NoiseSpawnFinder.radialSearch: rings `increment` apart around the best
|
||||
/// position so far, sampled every `increment` blocks along each ring.
|
||||
fn radial_search(
|
||||
targets: &[SpawnTargetPoint],
|
||||
context: &mut SamplerContext,
|
||||
best: &mut Candidate,
|
||||
max_radius: f32,
|
||||
increment: f32,
|
||||
) -> Result<(), SampleError> {
|
||||
let mut angle = 0f32;
|
||||
let mut radius = increment;
|
||||
let (origin_x, origin_z) = (best.x, best.z);
|
||||
while radius <= max_radius {
|
||||
let x = origin_x.wrapping_add((jmath::sin(f64::from(angle)) * f64::from(radius)) as i32);
|
||||
let z = origin_z.wrapping_add((jmath::cos(f64::from(angle)) * f64::from(radius)) as i32);
|
||||
let candidate = fitness(targets, context, x, z)?;
|
||||
if candidate.fitness < best.fitness {
|
||||
*best = candidate;
|
||||
}
|
||||
angle += increment / radius;
|
||||
if f64::from(angle) > std::f64::consts::PI * 2.0 {
|
||||
angle = 0.0;
|
||||
radius += increment;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// NoiseSpawnFinder.getSpawnPositionAndFitness: the best target's fitness at
|
||||
/// the column's quart corner, scaled so the squared distance to 0 0 only
|
||||
/// breaks ties between equally fitting columns.
|
||||
fn fitness(
|
||||
targets: &[SpawnTargetPoint],
|
||||
context: &mut SamplerContext,
|
||||
x: i32,
|
||||
z: i32,
|
||||
) -> Result<Candidate, SampleError> {
|
||||
let quart = [(x >> 2) << 2, 0, (z >> 2) << 2];
|
||||
let mut best = i64::MAX;
|
||||
for target in targets {
|
||||
best = best.min(target.sample_fitness(context, quart)?);
|
||||
}
|
||||
let bias = i64::from(x) * i64::from(x) + i64::from(z) * i64::from(z);
|
||||
Ok(Candidate {
|
||||
x,
|
||||
z,
|
||||
fitness: best.wrapping_mul(2048 * 2048).wrapping_add(bias),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Gradient;
|
||||
impl DensitySampler for Gradient {
|
||||
fn sample_value(&self, _: &mut SamplerContext, p: [i32; 3]) -> Result<f32, SampleError> {
|
||||
Ok(p[0] as f32 / 1000.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_fitting_column_wins() {
|
||||
// x / 1000 must reach 0.1: every column from x = 100 on fits equally,
|
||||
// so the distance bias picks the fitting column nearest to 0 0.
|
||||
let targets = [SpawnTargetPoint {
|
||||
parameters: vec![(Arc::new(Gradient), Parameter::new(1000, 10_000))],
|
||||
}];
|
||||
let [x, z] = find_spawn_position(&targets, &mut SamplerContext::default()).unwrap();
|
||||
assert!(x >= 100, "{x} {z}");
|
||||
assert!(x * x + z * z < 160 * 160, "{x} {z}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSource;
|
||||
import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists;
|
||||
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import net.minecraft.world.level.levelgen.NoiseSpawnFinder;
|
||||
import net.minecraft.world.level.levelgen.RandomState;
|
||||
import net.minecraft.world.level.levelgen.densityfunction.SamplerContext;
|
||||
|
||||
/**
|
||||
* The overworld's spawn origin for tools/test_world_spawn_parity.py: for each
|
||||
* seed, NoiseSpawnFinder.findSpawnPosition over the noise settings' spawn
|
||||
* target and NoiseBasedChunkGenerator.getOrigin, as `seed x z chunk_x chunk_z`.
|
||||
*
|
||||
* usage: VanillaWorldSpawnOracle <out> <seed>...
|
||||
*/
|
||||
public final class VanillaWorldSpawnOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
var world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
var settings = world.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD);
|
||||
var presets = world.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST);
|
||||
var biomeSource = MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD));
|
||||
var generator = new NoiseBasedChunkGenerator(biomeSource, settings);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0]), StandardCharsets.UTF_8))) {
|
||||
for (int i = 1; i < args.length; i++) {
|
||||
long seed = Long.parseLong(args[i]);
|
||||
var randomState = RandomState.create(world.lookupOrThrow(Registries.NOISE), seed, settings.value());
|
||||
BlockPos spawn = NoiseSpawnFinder.findSpawnPosition(
|
||||
settings.value().spawnTarget(), randomState.samplersWithContext(SamplerContext.builder().enableCaches().build()));
|
||||
ChunkPos origin = generator.getOrigin(randomState);
|
||||
out.println(seed + " " + spawn.getX() + " " + spawn.getZ() + " " + origin.x() + " " + origin.z());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare a new world's spawn with vanilla's, seed by seed.
|
||||
|
||||
A new overworld's spawn comes from two steps (MinecraftServer.setInitialSpawn):
|
||||
|
||||
1. the origin: NoiseBasedChunkGenerator.getOrigin runs NoiseSpawnFinder over
|
||||
the noise settings' `spawn_target` points (a coarse then a fine radial
|
||||
search of the climate fields) and takes the chunk of the best column;
|
||||
2. the spawn: an 11 by 11 chunk spiral around that chunk, the first chunk
|
||||
with a column PlayerSpawnFinder.getSpawnPosInChunk accepts (a full-topped
|
||||
block under open sky, no liquid on top) gives the world spawn.
|
||||
|
||||
Origins: VanillaWorldSpawnOracle calls NoiseSpawnFinder.findSpawnPosition and
|
||||
getOrigin for every seed; the spawn_origin example asks Horizon's generator.
|
||||
World spawns: the pinned vanilla dedicated server creates each world and
|
||||
stops; Horizon's (`horizon-client --dedicated --nogui`) creates its own from
|
||||
the same server.properties and stops; the `spawn` position of both
|
||||
level.dat files is compared.
|
||||
|
||||
Vanilla is not deterministic everywhere: trees of neighbouring chunks
|
||||
overlap on chunk corners, and which one is placed last depends on the order
|
||||
the server's worker threads decorate the chunks. A spawn column on such a
|
||||
corner can then stand on different leaves from one vanilla run to the next.
|
||||
When the spawns differ, vanilla creates the world up to RETRIES more times;
|
||||
Horizon's spawn passes if one of vanilla's runs gives it too, and the seed is
|
||||
reported as varying in vanilla.
|
||||
|
||||
Seeds: the player report's seed (1891623539983467248: Horizon spawned at
|
||||
-48 -48, vanilla at 152 145), the chunk generation harness's seeds and
|
||||
--random seeds from a fixed generator.
|
||||
|
||||
usage: test_world_spawn_parity.py [--random N] [--jobs N] [--origins-only]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from . import anvil_dump, lab, oracle_harness as oh, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server, free_port
|
||||
except ImportError:
|
||||
import anvil_dump
|
||||
import lab
|
||||
import oracle_harness as oh
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server, free_port
|
||||
|
||||
NAME = 'world-spawn-parity'
|
||||
REPORT = 1891623539983467248
|
||||
RETRIES = 3
|
||||
SEEDS = [REPORT, 12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777, 0]
|
||||
RESOURCES = lab.LOCAL / 'horizon-client/26.3'
|
||||
|
||||
|
||||
def seeds(count):
|
||||
rng = random.Random(20261014)
|
||||
return SEEDS + [rng.randrange(-2**63, 2**63) for _ in range(count)]
|
||||
|
||||
|
||||
def target_dir():
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
return Path(metadata['target_directory']) / 'release'
|
||||
|
||||
|
||||
def origins(build, classes, dependencies, all_seeds):
|
||||
vanilla_out = build / 'origins-vanilla.txt'
|
||||
oh.run_logged(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldSpawnOracle',
|
||||
vanilla_out, *all_seeds], build, 'origins-vanilla')
|
||||
rust = subprocess.run([target_dir() / 'examples/spawn_origin', RESOURCES, *map(str, all_seeds)],
|
||||
capture_output=True, text=True, check=True, cwd=lab.ROOT).stdout
|
||||
vanilla = vanilla_out.read_text()
|
||||
parse = lambda text: {int(l.split()[0]): tuple(map(int, l.split()[1:])) for l in text.splitlines() if l}
|
||||
return parse(vanilla), parse(rust)
|
||||
|
||||
|
||||
def world_spawn(command, directory, seed, log_name):
|
||||
"""Creates a world with `seed` in `directory`, stops, returns its level.dat spawn position."""
|
||||
if directory.exists():
|
||||
shutil.rmtree(directory)
|
||||
directory.mkdir(parents=True)
|
||||
props = {'online-mode': 'false', 'level-seed': str(seed), 'server-port': str(free_port()),
|
||||
'view-distance': '4', 'simulation-distance': '4', 'pause-when-empty-seconds': '-1'}
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()), encoding='iso-8859-1')
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
server = Server(command, directory, log_name)
|
||||
try:
|
||||
server.wait_for(r'Done \(', timeout=900)
|
||||
finally:
|
||||
server.stop()
|
||||
data = anvil_dump.read_dat(directory / 'world/level.dat')['Data']
|
||||
return tuple(data['spawn']['pos'][1])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--random', type=int, default=50, help='random seeds besides the fixed ones')
|
||||
parser.add_argument('--jobs', type=int, default=max(1, min(4, int(os.environ.get('FLEET_LOAD_JOBS', '4')) // 4)),
|
||||
help='worlds created at once (each side)')
|
||||
parser.add_argument('--origins-only', action='store_true', help='compare the spawn search origins only')
|
||||
parser.add_argument('--seed', type=int, action='append', help='only these seeds (repeatable)')
|
||||
args = parser.parse_args()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies,
|
||||
'-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'],
|
||||
build, 'compile-java')
|
||||
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'spawn_origin'], build, 'compile-probe')
|
||||
all_seeds = args.seed or seeds(args.random)
|
||||
started = time.time()
|
||||
|
||||
vanilla, rust = origins(build, classes, dependencies, all_seeds)
|
||||
origin_diffs = [s for s in all_seeds if vanilla.get(s) != rust.get(s)]
|
||||
for s in origin_diffs:
|
||||
print(f'origin {s}: vanilla column {vanilla.get(s)} / horizon {rust.get(s)}')
|
||||
print(f'Origins: {len(all_seeds) - len(origin_diffs)}/{len(all_seeds)} seeds match '
|
||||
f'(column x z, chunk x z) in {time.time() - started:.0f}s', flush=True)
|
||||
if args.origins_only:
|
||||
sys.exit(1 if origin_diffs else 0)
|
||||
|
||||
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
|
||||
'compile-rust', timeout=3600)
|
||||
binary = target_dir() / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
vanilla_server = ['java', '-Xmx2g', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui']
|
||||
os.environ['HORIZON_NO_AUDIO'] = '1'
|
||||
|
||||
def one(seed):
|
||||
t0 = time.time()
|
||||
a = world_spawn(vanilla_server, build / f'vanilla-{seed}', seed, f'vanilla-{seed}')
|
||||
b = world_spawn(horizon_server, build / f'horizon-{seed}', seed, f'horizon-{seed}')
|
||||
runs = [a]
|
||||
while b not in runs and len(runs) <= RETRIES:
|
||||
runs.append(world_spawn(vanilla_server, build / f'vanilla-{seed}-{len(runs)}', seed, f'vanilla-{seed}-{len(runs)}'))
|
||||
return seed, runs, b, time.time() - t0
|
||||
|
||||
spawn_diffs, varying = [], []
|
||||
with ThreadPoolExecutor(args.jobs) as pool:
|
||||
for seed, runs, b, took in pool.map(one, all_seeds):
|
||||
ok = b in runs
|
||||
if not ok:
|
||||
spawn_diffs.append(seed)
|
||||
elif len(set(runs)) > 1:
|
||||
varying.append(seed)
|
||||
seen = ', '.join(' '.join(map(str, r)) for r in dict.fromkeys(runs))
|
||||
print(f'{"ok " if ok else "DIFF"} {seed}: vanilla {seen} / horizon {b[0]} {b[1]} {b[2]} '
|
||||
f'(origin chunk {vanilla[seed][2]} {vanilla[seed][3]}; {took:.0f}s)', flush=True)
|
||||
if ok:
|
||||
for path in build.glob(f'*-{seed}*'):
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
print(f'World spawns: {len(all_seeds) - len(spawn_diffs)}/{len(all_seeds)} seeds match in {time.time() - started:.0f}s'
|
||||
+ (f'; vanilla itself gave several spawns for {len(varying)}: {varying}' if varying else ''))
|
||||
if origin_diffs or spawn_diffs:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user