Merge pull request #319 from ludovic111/feat/trial-spawners
Trial spawner state machine, checked against vanilla
This commit is contained in:
@@ -13,6 +13,10 @@
|
||||
//! `mobs::spawner::Spawner` loaded from the case's SNBT on the same world and
|
||||
//! print its events tick by tick.
|
||||
//!
|
||||
//! Trial spawner cases (`mode=trial`, tools/test_trial_spawner_parity.py) tick
|
||||
//! a `mobs::trial_spawner::TrialSpawner` with the game time advancing and
|
||||
//! print its states, events, spawns and ejected items.
|
||||
//!
|
||||
//! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT
|
||||
use horizon_client::{
|
||||
assets::Assets,
|
||||
@@ -31,6 +35,7 @@ use horizon_client::{
|
||||
},
|
||||
spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn},
|
||||
species::{self, Baby},
|
||||
trial_spawner::{TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState},
|
||||
},
|
||||
};
|
||||
use horizon_core::{
|
||||
@@ -38,11 +43,11 @@ use horizon_core::{
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::{
|
||||
block_collision::BlockCollisionRegistry, chunk::BlockState, registry::BlockStateId,
|
||||
block_collision::BlockCollisionRegistry, chunk::BlockState, nbt::Tag, registry::BlockStateId,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
cell::{Cell, RefCell},
|
||||
collections::{BTreeMap, HashMap, HashSet},
|
||||
fmt::Write as _,
|
||||
fs,
|
||||
@@ -106,6 +111,12 @@ struct World<'a> {
|
||||
spawners_work: bool,
|
||||
/// Types and boxes of living entities (case entities, then spawned mobs).
|
||||
entities: RefCell<Vec<(String, Aabb)>>,
|
||||
/// Blocks set since the case started (a trial spawner's states).
|
||||
placed: RefCell<Vec<([i32; 3], BlockStateId)>>,
|
||||
/// The game time (trial cases advance it).
|
||||
time: Cell<i64>,
|
||||
/// The mobs a trial spawner added: UUID, position and box.
|
||||
trial_mobs: RefCell<Vec<([i32; 4], [f64; 3], Aabb)>>,
|
||||
}
|
||||
impl World<'_> {
|
||||
fn biome_at(&self, x: i32, y: i32, z: i32) -> &str {
|
||||
@@ -129,6 +140,15 @@ impl World<'_> {
|
||||
}
|
||||
impl SpawnLevel for World<'_> {
|
||||
fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId {
|
||||
if let Some((_, s)) = self
|
||||
.placed
|
||||
.borrow()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(p, _)| *p == [x, y, z])
|
||||
{
|
||||
return *s;
|
||||
}
|
||||
self.blocks
|
||||
.iter()
|
||||
.rev()
|
||||
@@ -341,6 +361,50 @@ impl SpawnerLevel for World<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl TrialSpawnerLevel for World<'_> {
|
||||
fn game_time(&self) -> i64 {
|
||||
self.time.get()
|
||||
}
|
||||
fn mob_spawning(&self) -> bool {
|
||||
self.spawn_mobs
|
||||
}
|
||||
fn players(&self) -> Vec<TrialPlayer> {
|
||||
self.players
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (p, mode))| TrialPlayer {
|
||||
uuid: [0, 0, 0, i as i32 + 1],
|
||||
block: p.map(|v| v.floor() as i32),
|
||||
eye: [p[0], p[1] + f64::from(1.62f32), p[2]],
|
||||
creative: mode == "creative",
|
||||
spectator: mode == "spectator",
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]> {
|
||||
let lookup = |x: i32, y: i32, z: i32| self.state(x, y, z);
|
||||
let mut scene = LookupCollisions {
|
||||
block: &lookup,
|
||||
binding: self.s.collision,
|
||||
};
|
||||
let v = |p: [f64; 3]| horizon_core::geometry::Vec3::new(p[0], p[1], p[2]);
|
||||
horizon_client::mobs::visual_clip(
|
||||
self.s.facts,
|
||||
self.s.collision,
|
||||
&mut scene,
|
||||
&lookup,
|
||||
v(from),
|
||||
v(to),
|
||||
)
|
||||
.flatten()
|
||||
}
|
||||
fn entity_block(&self, uuid: [i32; 4]) -> Option<[i32; 3]> {
|
||||
let mobs = self.trial_mobs.borrow();
|
||||
let (_, p, _) = mobs.iter().find(|(u, ..)| *u == uuid)?;
|
||||
Some(p.map(|v| v.floor() as i32))
|
||||
}
|
||||
}
|
||||
|
||||
/// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random.
|
||||
fn neutral_box(l: &World, r: &SpawnRequest) -> Aabb {
|
||||
let t = &l.s.types.types[r.entity];
|
||||
@@ -407,6 +471,13 @@ fn main() -> horizon_client::Result<()> {
|
||||
let facts = BlockFacts::load(root, registry)?;
|
||||
let data = MobData::load(root, &facts);
|
||||
let items = Items::tags_only(root)?;
|
||||
// Trial spawner rewards: the loot tables and the configs.
|
||||
let loot = if input.contains("mode=trial") {
|
||||
horizon_client::mobs::trial_spawner::load_registry(root);
|
||||
horizon_client::structure_blocks::loot_data(root)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let types = MobTypes::load(root)?;
|
||||
let biomes = Biomes::load(root)?;
|
||||
let structures = StructureSpawns::load(root);
|
||||
@@ -593,6 +664,9 @@ fn main() -> horizon_client::Result<()> {
|
||||
unloaded,
|
||||
spawn_mobs: get("rules", "1") != "0",
|
||||
spawners_work: get("spawners", "1") != "0",
|
||||
placed: RefCell::new(Vec::new()),
|
||||
time: Cell::new(0),
|
||||
trial_mobs: RefCell::new(Vec::new()),
|
||||
entities: RefCell::new(
|
||||
case_entities
|
||||
.iter()
|
||||
@@ -629,6 +703,9 @@ fn main() -> horizon_client::Result<()> {
|
||||
let mode = get("mode", "chunk");
|
||||
if mode == "spawner" {
|
||||
spawner_case(&world, &get, &mut random, &mut log)?;
|
||||
} else if mode == "trial" {
|
||||
let loot = loot.as_ref().ok_or("no loot tables")?;
|
||||
trial_case(&world, registry, loot, &get, &mut random, &mut log)?;
|
||||
} else if mode == "gen" {
|
||||
let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?);
|
||||
// The level random of the spawn predicates: no creature's predicate
|
||||
@@ -831,3 +908,196 @@ fn spawner_case(
|
||||
log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `TrialSpawner.tickServer` `ticks` times from game time `t0` at `spos` on a
|
||||
/// trial spawner block in state `state` (ominous with `ominous=1`) loaded from
|
||||
/// `snbt` (base64 SNBT), as the oracle logs it. Every `kill` ticks the mobs it
|
||||
/// spawned die.
|
||||
fn trial_case(
|
||||
world: &World,
|
||||
registry: &horizon_world::registry::BlockRegistry,
|
||||
loot: &horizon_world::loot::LootData,
|
||||
get: &dyn Fn(&str, &'static str) -> String,
|
||||
random: &mut LegacyRandom,
|
||||
log: &mut Vec<String>,
|
||||
) -> horizon_client::Result<()> {
|
||||
let v: Vec<i32> = get("spos", "0,0,0")
|
||||
.split(',')
|
||||
.map(|n| n.parse().unwrap_or(0))
|
||||
.collect();
|
||||
let pos = [v[0], v[1], v[2]];
|
||||
let block_state = |state: TrialState, ominous: bool| {
|
||||
parse_state(&format!(
|
||||
"minecraft:trial_spawner[trial_spawner_state={},ominous={ominous}]",
|
||||
state.name()
|
||||
))
|
||||
};
|
||||
let mut state =
|
||||
TrialState::from_name(&get("state", "waiting_for_players")).ok_or("bad state")?;
|
||||
let mut ominous = get("ominous", "0") == "1";
|
||||
world
|
||||
.placed
|
||||
.borrow_mut()
|
||||
.push((pos, registry.resolve(&block_state(state, ominous))?));
|
||||
let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?;
|
||||
let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0;
|
||||
let mut spawner = TrialSpawner::load(&tag);
|
||||
let ticks: i64 = get("ticks", "1").parse()?;
|
||||
let t0: i64 = get("t0", "0").parse()?;
|
||||
let kill: i64 = get("kill", "0").parse()?;
|
||||
let seed = world.seed;
|
||||
let mut sequences = horizon_client::random_sequences::RandomSequences::default();
|
||||
let center = pos.map(|v| f64::from(v) + 0.5);
|
||||
for tick in 0..ticks {
|
||||
world.time.set(t0 + tick);
|
||||
let mut events = Vec::new();
|
||||
let mut spawned = std::collections::VecDeque::new();
|
||||
let mut items = Vec::new();
|
||||
let mut spawn = |l: &World, r: &SpawnerSpawn| {
|
||||
let t = l.s.types.types.get(r.id)?;
|
||||
// Slime.readAdditionalSaveData: size Size + 1, clamped to 1..=127.
|
||||
let size = match r.entity.get(&horizon_world::nbt::JavaString::from("Size")) {
|
||||
Some(Tag::Byte(v)) => i32::from(*v),
|
||||
Some(Tag::Short(v)) => i32::from(*v),
|
||||
Some(Tag::Int(v)) => *v,
|
||||
Some(Tag::Long(v)) => *v as i32,
|
||||
_ => 0,
|
||||
};
|
||||
let size = if matches!(r.id, "minecraft:slime" | "minecraft:magma_cube") {
|
||||
size.saturating_add(1).clamp(1, 127)
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let [x, y, z] = r.position;
|
||||
let scale = size as f32;
|
||||
let bounds = spawn_box(x, y, z, t.width as f32 * scale, t.height as f32 * scale);
|
||||
l.entities.borrow_mut().push((r.id.to_owned(), bounds));
|
||||
let uuid = [1, 0, 0, l.trial_mobs.borrow().len() as i32];
|
||||
l.trial_mobs.borrow_mut().push((uuid, r.position, bounds));
|
||||
spawned.push_back(format!(
|
||||
"{tick} spawn {} {} {} {} {}",
|
||||
r.id,
|
||||
bits(x),
|
||||
bits(y),
|
||||
bits(z),
|
||||
if size == 1 {
|
||||
yaw_text(r.id, r.yaw)
|
||||
} else {
|
||||
"head".to_owned()
|
||||
}
|
||||
));
|
||||
Some(uuid)
|
||||
};
|
||||
let mut eject = |table: &str, random: &mut LegacyRandom| {
|
||||
let drops = match loot.random_sequence(table) {
|
||||
Some(s) => loot.roll_split(table, sequences.get(s, seed)),
|
||||
None => loot.roll_split(table, random),
|
||||
};
|
||||
for stack in &drops {
|
||||
random.next_double();
|
||||
let spread = 0.017_227_5 * 2.0;
|
||||
let v = [
|
||||
random.triangle(0.0, spread),
|
||||
random.triangle(0.2, spread),
|
||||
random.triangle(0.0, spread),
|
||||
];
|
||||
items.push(format!(
|
||||
"{tick} item {} {} {} {} {} {} {} {}",
|
||||
stack.item,
|
||||
stack.count,
|
||||
bits(center[0]),
|
||||
bits(center[1] + 0.7 - 0.125),
|
||||
bits(center[2]),
|
||||
bits(v[0]),
|
||||
bits(v[1]),
|
||||
bits(v[2])
|
||||
));
|
||||
}
|
||||
!drops.is_empty()
|
||||
};
|
||||
let next = spawner.server_tick(
|
||||
world,
|
||||
random,
|
||||
pos,
|
||||
state,
|
||||
ominous,
|
||||
&mut spawn,
|
||||
&mut eject,
|
||||
&mut events,
|
||||
);
|
||||
for e in events {
|
||||
match e {
|
||||
TrialEvent::BlockUpdated => log.push(format!("{tick} update")),
|
||||
TrialEvent::LevelEvent(id, _, data) => {
|
||||
// A spawn's events follow its tryAddFreshEntityWithPassengers,
|
||||
// a reward's its items.
|
||||
match id {
|
||||
3011 => log.extend(spawned.pop_front()),
|
||||
3014 => log.append(&mut items),
|
||||
_ => {}
|
||||
}
|
||||
log.push(format!("{tick} levent {id} {data}"));
|
||||
}
|
||||
TrialEvent::Sound(name) => log.push(format!(
|
||||
"{tick} sound minecraft:{name} {} {} {} 1.0 1.0",
|
||||
bits(center[0]),
|
||||
bits(center[1]),
|
||||
bits(center[2])
|
||||
)),
|
||||
TrialEvent::EntityPlace(_, p) => log.push(format!(
|
||||
"{tick} gevent minecraft:entity_place {} {} {}",
|
||||
p[0], p[1], p[2]
|
||||
)),
|
||||
TrialEvent::OminousSet(set) => {
|
||||
ominous = set;
|
||||
world
|
||||
.placed
|
||||
.borrow_mut()
|
||||
.push((pos, registry.resolve(&block_state(state, ominous))?));
|
||||
log.push(format!("{tick} state {} {ominous}", state.name()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if next != state || spawner.is_ominous != ominous {
|
||||
state = next;
|
||||
ominous = spawner.is_ominous;
|
||||
world
|
||||
.placed
|
||||
.borrow_mut()
|
||||
.push((pos, registry.resolve(&block_state(state, ominous))?));
|
||||
log.push(format!("{tick} state {} {ominous}", state.name()));
|
||||
}
|
||||
if kill > 0 && tick % kill == kill - 1 {
|
||||
let dead: Vec<Aabb> = world
|
||||
.trial_mobs
|
||||
.borrow_mut()
|
||||
.drain(..)
|
||||
.map(|(.., b)| b)
|
||||
.collect();
|
||||
world
|
||||
.entities
|
||||
.borrow_mut()
|
||||
.retain(|(_, b)| !dead.iter().any(|d| d == b));
|
||||
if !dead.is_empty() {
|
||||
log.push(format!("{tick} kill {}", dead.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
log.push(format!(
|
||||
"end state={} players={} mobs={} cooldown={} next_spawn={} total={} data={} eject={}",
|
||||
state.name(),
|
||||
spawner.detected_players.len(),
|
||||
spawner.current_mobs.len(),
|
||||
spawner.cooldown_ends_at,
|
||||
spawner.next_mob_spawns_at,
|
||||
spawner.total_mobs_spawned,
|
||||
spawner
|
||||
.next_spawn_data
|
||||
.as_ref()
|
||||
.and_then(|d| d.id())
|
||||
.unwrap_or_else(|| "-".into()),
|
||||
spawner.ejecting_loot_table.as_deref().unwrap_or("-")
|
||||
));
|
||||
log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ pub mod sulfur_cube;
|
||||
pub mod tame;
|
||||
pub mod trader;
|
||||
pub mod transport_items;
|
||||
pub mod trial_spawner;
|
||||
pub mod undead;
|
||||
pub mod vex;
|
||||
pub mod villager;
|
||||
@@ -74,6 +75,7 @@ pub mod warden_brain;
|
||||
pub mod witch;
|
||||
pub mod wither;
|
||||
mod world;
|
||||
pub use world::visual_clip;
|
||||
pub mod zombie_villager;
|
||||
|
||||
use crate::{blocks::BlockFacts, mesher::Vertex, world::World};
|
||||
|
||||
@@ -107,11 +107,17 @@ impl SpawnData {
|
||||
}
|
||||
/// The entity compound is only its `id` (`hasNoConfiguration`): the
|
||||
/// spawned mob is finalized.
|
||||
fn unconfigured(&self) -> bool {
|
||||
pub(crate) fn unconfigured(&self) -> bool {
|
||||
self.entity.len() == 1 && self.id().is_some()
|
||||
}
|
||||
/// `CustomSpawnRules.isValidPosition`.
|
||||
fn valid_position<L: SpawnerLevel>(r: CustomSpawnRules, l: &L, x: i32, y: i32, z: i32) -> bool {
|
||||
pub(crate) fn valid_position<L: SpawnerLevel>(
|
||||
r: CustomSpawnRules,
|
||||
l: &L,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
) -> bool {
|
||||
let block = l.block_light(x, y, z);
|
||||
let sky = (l.sky_light(x, y, z) - l.sky_darken()).max(0);
|
||||
(r.block.0..=r.block.1).contains(&block) && (r.sky.0..=r.sky.1).contains(&sky)
|
||||
@@ -135,8 +141,19 @@ pub fn normalize_id(s: &str) -> Option<String> {
|
||||
.then(|| format!("{ns}:{path}"))
|
||||
}
|
||||
|
||||
/// How much a slime's or magma cube's box is scaled by the size its data
|
||||
/// loads (`Slime.readAdditionalSaveData`: Size + 1, kept in 1..=127), which
|
||||
/// the obstruction test sees before `finalizeSpawn` picks one.
|
||||
pub(crate) fn cube_scale(id: &str, entity: &Compound) -> f32 {
|
||||
if !matches!(id, "minecraft:slime" | "minecraft:magma_cube") {
|
||||
return 1.0;
|
||||
}
|
||||
number(entity.get(&JavaString::from("Size")))
|
||||
.map_or(1, |size| (size as i32).saturating_add(1).clamp(1, 127)) as f32
|
||||
}
|
||||
|
||||
/// A whole number from any numeric tag (`NumericTag.intValue`: floats floor).
|
||||
fn number(tag: Option<&Tag>) -> Option<i64> {
|
||||
pub(crate) fn number(tag: Option<&Tag>) -> Option<i64> {
|
||||
Some(match tag? {
|
||||
Tag::Byte(v) => i64::from(*v),
|
||||
Tag::Short(v) => i64::from(*v),
|
||||
@@ -255,6 +272,9 @@ pub struct SpawnerSpawn<'a> {
|
||||
/// `finalizeSpawn(SPAWNER)` runs (the data is just an id).
|
||||
pub finalize: bool,
|
||||
pub equipment: Option<&'a Tag>,
|
||||
/// A trial spawner's mob (`EntitySpawnReason.TRIAL_SPAWNER`): it is
|
||||
/// always persistent.
|
||||
pub trial: bool,
|
||||
}
|
||||
/// An entity the level added: its id, box and whether it is a mob.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -370,25 +390,8 @@ impl Spawner {
|
||||
Next::Potential(i) => self.potentials.get_mut(*i).map(|(d, _)| d),
|
||||
}
|
||||
}
|
||||
/// `WeightedList.getRandom`: one draw over the total weight, none when
|
||||
/// the list weighs nothing.
|
||||
fn random_potential(&self, random: &mut impl RandomSource) -> Option<usize> {
|
||||
let total: i64 = self.potentials.iter().map(|(_, w)| i64::from(*w)).sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut pick = i64::from(
|
||||
random
|
||||
.next_int_bound(total.min(i64::from(i32::MAX)) as i32)
|
||||
.unwrap_or(0),
|
||||
);
|
||||
for (i, (_, w)) in self.potentials.iter().enumerate() {
|
||||
pick -= i64::from(*w);
|
||||
if pick < 0 {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
weighted_index(self.potentials.iter().map(|(_, w)| *w), random)
|
||||
}
|
||||
/// `getOrCreateNextSpawnData`: a potential at random, or empty data.
|
||||
fn next_or_create(&mut self, random: &mut impl RandomSource, events: &mut Vec<SpawnerEvent>) {
|
||||
@@ -555,7 +558,14 @@ impl Spawner {
|
||||
placed[1].floor() as i32,
|
||||
placed[2].floor() as i32,
|
||||
];
|
||||
let bounds = spawn_selection::spawn_box(placed[0], placed[1], placed[2], width, height);
|
||||
let scale = cube_scale(&id, &data.entity);
|
||||
let bounds = spawn_selection::spawn_box(
|
||||
placed[0],
|
||||
placed[1],
|
||||
placed[2],
|
||||
width * scale,
|
||||
height * scale,
|
||||
);
|
||||
let rules_ok = data.custom_spawn_rules.is_some()
|
||||
|| spawn_selection::mob_spawn_rules(s, l, own[0], own[1], own[2]);
|
||||
if !rules_ok
|
||||
@@ -570,6 +580,7 @@ impl Spawner {
|
||||
yaw,
|
||||
finalize: data.unconfigured(),
|
||||
equipment: data.equipment.as_ref(),
|
||||
trial: false,
|
||||
};
|
||||
let Some(result) = spawn(l, &request) else {
|
||||
self.delay(random, events);
|
||||
@@ -643,6 +654,30 @@ impl Spawner {
|
||||
}
|
||||
}
|
||||
|
||||
/// `WeightedList.getRandom`: one draw over the total weight, none when the
|
||||
/// list weighs nothing.
|
||||
pub fn weighted_index(
|
||||
weights: impl Iterator<Item = i32> + Clone,
|
||||
random: &mut impl RandomSource,
|
||||
) -> Option<usize> {
|
||||
let total: i64 = weights.clone().map(i64::from).sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut pick = i64::from(
|
||||
random
|
||||
.next_int_bound(total.min(i64::from(i32::MAX)) as i32)
|
||||
.unwrap_or(0),
|
||||
);
|
||||
for (i, w) in weights.enumerate() {
|
||||
pick -= i64::from(w);
|
||||
if pick < 0 {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `Entity.setPos` of a fresh mob: a shulker sits at the centre of its block.
|
||||
pub fn entity_position(s: Species, at: [f64; 3]) -> [f64; 3] {
|
||||
if s == Species::Shulker {
|
||||
@@ -657,7 +692,7 @@ pub fn entity_position(s: Species, at: [f64; 3]) -> [f64; 3] {
|
||||
}
|
||||
|
||||
/// `Vec3.CODEC`: a list of three doubles.
|
||||
fn read_pos(tag: Option<&Tag>) -> Option<[f64; 3]> {
|
||||
pub(crate) fn read_pos(tag: Option<&Tag>) -> Option<[f64; 3]> {
|
||||
let Tag::List(v) = tag? else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,886 @@
|
||||
//! The trial spawner (`TrialSpawner` as `TrialSpawnerBlockEntity` runs it):
|
||||
//! its configs, saved state (`TrialSpawnerStateData`) and the server tick that
|
||||
//! walks `TrialSpawnerState`: waiting for players, spawning its waves while
|
||||
//! they fight, ejecting a reward per player, then cooling down.
|
||||
//!
|
||||
//! The state lives in the block (`trial_spawner_state`); the tick reads it and
|
||||
//! reports the next one. The level's random drives the tick in vanilla's draw
|
||||
//! order; what the spawner asks of the level goes through
|
||||
//! [`TrialSpawnerLevel`], so the game and a differential test world answer the
|
||||
//! same questions.
|
||||
use super::{
|
||||
spawn_rules::{self, Reason},
|
||||
spawn_selection,
|
||||
spawner::{self, SpawnData, SpawnerLevel, SpawnerSpawn},
|
||||
};
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag};
|
||||
use std::{collections::HashMap, path::Path, sync::OnceLock};
|
||||
|
||||
/// An entity's UUID as its four ints (`UUIDUtil.CODEC`).
|
||||
pub type Uuid = [i32; 4];
|
||||
|
||||
/// `MAX_MOB_TRACKING_DISTANCE`: a spawned mob further than this stops
|
||||
/// counting as one of the spawner's.
|
||||
const MAX_MOB_TRACKING_DISTANCE: i64 = 47;
|
||||
/// `DELAY_BEFORE_EJECT_AFTER_KILLING_LAST_MOB` and `TIME_BETWEEN_EACH_EJECTION`.
|
||||
const DELAY_BEFORE_EJECT: f32 = 40.0;
|
||||
const TIME_BETWEEN_EJECTIONS: f32 = 30.0;
|
||||
|
||||
/// `TrialSpawnerConfig`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TrialConfig {
|
||||
pub spawn_range: i32,
|
||||
pub total_mobs: f32,
|
||||
pub simultaneous_mobs: f32,
|
||||
pub total_mobs_added_per_player: f32,
|
||||
pub simultaneous_mobs_added_per_player: f32,
|
||||
pub ticks_between_spawn: i32,
|
||||
pub spawn_potentials: Vec<(SpawnData, i32)>,
|
||||
pub loot_tables_to_eject: Vec<(String, i32)>,
|
||||
pub items_to_drop_when_ominous: String,
|
||||
}
|
||||
impl Default for TrialConfig {
|
||||
/// `TrialSpawnerConfig.Builder`'s defaults.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
spawn_range: 4,
|
||||
total_mobs: 6.0,
|
||||
simultaneous_mobs: 2.0,
|
||||
total_mobs_added_per_player: 2.0,
|
||||
simultaneous_mobs_added_per_player: 1.0,
|
||||
ticks_between_spawn: 40,
|
||||
spawn_potentials: Vec::new(),
|
||||
loot_tables_to_eject: vec![
|
||||
("minecraft:spawners/trial_chamber/consumables".into(), 1),
|
||||
("minecraft:spawners/trial_chamber/key".into(), 1),
|
||||
],
|
||||
items_to_drop_when_ominous:
|
||||
"minecraft:spawners/trial_chamber/items_to_drop_when_ominous".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl TrialConfig {
|
||||
/// `TrialSpawnerConfig.DIRECT_CODEC`; None when the tag is not a
|
||||
/// compound. Read as `TagValueInput` does, keeping the partial result:
|
||||
/// a field that fails to decode takes its default, and the list entries
|
||||
/// that fail are dropped.
|
||||
pub fn decode(tag: &Tag) -> Option<Self> {
|
||||
let Tag::Compound(_) = tag else {
|
||||
return None;
|
||||
};
|
||||
let d = Self::default();
|
||||
let float = |k: &str, default: f32| {
|
||||
tag.get(k)
|
||||
.and_then(float)
|
||||
.filter(|v| *v >= 0.0)
|
||||
.unwrap_or(default)
|
||||
};
|
||||
let int = |k: &str, default: i32, lo: i32, hi: i32| {
|
||||
spawner::number(tag.get(k))
|
||||
.filter(|v| (i64::from(lo)..=i64::from(hi)).contains(v))
|
||||
.map_or(default, |v| v as i32)
|
||||
};
|
||||
let list = |k: &str| match tag.get(k) {
|
||||
Some(Tag::List(list)) => Some(list.iter()),
|
||||
_ => None,
|
||||
};
|
||||
let spawn_potentials = list("spawn_potentials").map_or_else(Vec::new, |l| {
|
||||
l.filter_map(|e| Some((SpawnData::decode(e.get("data")?)?, weight(e.get("weight"))?)))
|
||||
.collect()
|
||||
});
|
||||
let loot_tables_to_eject =
|
||||
list("loot_tables_to_eject").map_or(d.loot_tables_to_eject, |l| {
|
||||
l.filter_map(|e| Some((identifier(e.get("data"))?, weight(e.get("weight"))?)))
|
||||
.collect()
|
||||
});
|
||||
Some(Self {
|
||||
spawn_range: int("spawn_range", d.spawn_range, 1, 128),
|
||||
total_mobs: float("total_mobs", d.total_mobs),
|
||||
simultaneous_mobs: float("simultaneous_mobs", d.simultaneous_mobs),
|
||||
total_mobs_added_per_player: float(
|
||||
"total_mobs_added_per_player",
|
||||
d.total_mobs_added_per_player,
|
||||
),
|
||||
simultaneous_mobs_added_per_player: float(
|
||||
"simultaneous_mobs_added_per_player",
|
||||
d.simultaneous_mobs_added_per_player,
|
||||
),
|
||||
ticks_between_spawn: int("ticks_between_spawn", d.ticks_between_spawn, 0, i32::MAX),
|
||||
spawn_potentials,
|
||||
loot_tables_to_eject,
|
||||
items_to_drop_when_ominous: identifier(tag.get("items_to_drop_when_ominous"))
|
||||
.unwrap_or(d.items_to_drop_when_ominous),
|
||||
})
|
||||
}
|
||||
/// `calculateTargetTotalMobs`.
|
||||
pub fn target_total_mobs(&self, additional_players: i32) -> i32 {
|
||||
(self.total_mobs + self.total_mobs_added_per_player * additional_players as f32).floor()
|
||||
as i32
|
||||
}
|
||||
/// `calculateTargetSimultaneousMobs`.
|
||||
pub fn target_simultaneous_mobs(&self, additional_players: i32) -> i32 {
|
||||
(self.simultaneous_mobs
|
||||
+ self.simultaneous_mobs_added_per_player * additional_players as f32)
|
||||
.floor() as i32
|
||||
}
|
||||
}
|
||||
|
||||
static REGISTRY: OnceLock<HashMap<String, TrialConfig>> = OnceLock::new();
|
||||
|
||||
/// `Registries.TRIAL_SPAWNER_CONFIG`: the configs under the resources'
|
||||
/// `data/<namespace>/trial_spawner`, read once per process.
|
||||
pub fn load_registry(root: &Path) {
|
||||
REGISTRY.get_or_init(|| {
|
||||
let mut out = HashMap::new();
|
||||
let Ok(namespaces) = std::fs::read_dir(root.join("data")) else {
|
||||
return out;
|
||||
};
|
||||
for ns in namespaces.flatten() {
|
||||
let base = ns.path().join("trial_spawner");
|
||||
let mut stack = vec![base.clone()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
continue;
|
||||
}
|
||||
let (Ok(rel), Some(ns)) = (
|
||||
path.with_extension("")
|
||||
.strip_prefix(&base)
|
||||
.map(Path::to_path_buf),
|
||||
ns.file_name().to_str().map(str::to_owned),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let config = std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.and_then(|v| TrialConfig::decode(&crate::scoreboard::json_to_tag(&v)));
|
||||
match config {
|
||||
Some(c) => {
|
||||
let id = rel.to_string_lossy().replace('\\', "/");
|
||||
out.insert(format!("{ns}:{id}"), c);
|
||||
}
|
||||
None => log::warn!("Horizon: bad trial spawner config {}", path.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
});
|
||||
}
|
||||
/// A config of the registry by id.
|
||||
pub fn registry_config(id: &str) -> Option<TrialConfig> {
|
||||
REGISTRY.get()?.get(id).cloned()
|
||||
}
|
||||
|
||||
fn float(t: &Tag) -> Option<f32> {
|
||||
Some(match t {
|
||||
Tag::Float(b) => f32::from_bits(*b),
|
||||
Tag::Double(b) => f64::from_bits(*b) as f32,
|
||||
t => spawner::number(Some(t))? as f32,
|
||||
})
|
||||
}
|
||||
/// `Weighted.CODEC`'s weight: a non-negative int.
|
||||
fn weight(t: Option<&Tag>) -> Option<i32> {
|
||||
spawner::number(t)
|
||||
.filter(|w| (0..=i64::from(i32::MAX)).contains(w))
|
||||
.map(|w| w as i32)
|
||||
}
|
||||
/// An `Identifier` (`minecraft` when the namespace is left out).
|
||||
fn identifier(t: Option<&Tag>) -> Option<String> {
|
||||
match t? {
|
||||
Tag::String(s) => spawner::normalize_id(&s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Holder<TrialSpawnerConfig>` as saved: a registry id
|
||||
/// (`minecraft:trial_chamber/breeze/normal`) or an inline config.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ConfigSlot {
|
||||
/// The value as loaded, written back as is; None for the default.
|
||||
pub saved: Option<Tag>,
|
||||
pub config: TrialConfig,
|
||||
}
|
||||
|
||||
/// `TrialSpawnerState`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum TrialState {
|
||||
#[default]
|
||||
Inactive,
|
||||
WaitingForPlayers,
|
||||
Active,
|
||||
WaitingForRewardEjection,
|
||||
EjectingReward,
|
||||
Cooldown,
|
||||
}
|
||||
impl TrialState {
|
||||
pub const ALL: [Self; 6] = [
|
||||
Self::Inactive,
|
||||
Self::WaitingForPlayers,
|
||||
Self::Active,
|
||||
Self::WaitingForRewardEjection,
|
||||
Self::EjectingReward,
|
||||
Self::Cooldown,
|
||||
];
|
||||
/// The `trial_spawner_state` block property.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Inactive => "inactive",
|
||||
Self::WaitingForPlayers => "waiting_for_players",
|
||||
Self::Active => "active",
|
||||
Self::WaitingForRewardEjection => "waiting_for_reward_ejection",
|
||||
Self::EjectingReward => "ejecting_reward",
|
||||
Self::Cooldown => "cooldown",
|
||||
}
|
||||
}
|
||||
pub fn from_name(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|s| s.name() == name)
|
||||
}
|
||||
/// The spin speed of the mob shown inside, None when it shows none.
|
||||
pub fn spinning_mob_speed(self) -> Option<f64> {
|
||||
match self {
|
||||
Self::WaitingForPlayers => Some(200.0),
|
||||
Self::Active => Some(1000.0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn capable_of_spawning(self) -> bool {
|
||||
matches!(self, Self::WaitingForPlayers | Self::Active)
|
||||
}
|
||||
}
|
||||
|
||||
/// A player the spawner can detect (`PlayerDetector.NO_CREATIVE_PLAYERS`).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TrialPlayer {
|
||||
pub uuid: Uuid,
|
||||
pub block: [i32; 3],
|
||||
pub eye: [f64; 3],
|
||||
pub creative: bool,
|
||||
pub spectator: bool,
|
||||
}
|
||||
|
||||
/// What a trial spawner did that the level shows or sends.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TrialEvent {
|
||||
/// `markUpdated`: `sendBlockUpdated` with the new update tag.
|
||||
BlockUpdated,
|
||||
/// `levelEvent(id, pos, data)`.
|
||||
LevelEvent(i32, [i32; 3], i32),
|
||||
/// `playSound(null, spawner, sound, BLOCKS)` at volume and pitch 1.
|
||||
Sound(&'static str),
|
||||
/// `gameEvent(entity, ENTITY_PLACE, block)` for the mob just added.
|
||||
EntityPlace(Uuid, [i32; 3]),
|
||||
/// `setBlockAndUpdate` of the `ominous` property alone, even when it
|
||||
/// does not change (`removeOminous`).
|
||||
OminousSet(bool),
|
||||
}
|
||||
|
||||
/// What a trial spawner reads from the level besides the spawn rules.
|
||||
pub trait TrialSpawnerLevel: SpawnerLevel {
|
||||
fn game_time(&self) -> i64;
|
||||
/// `canSpawnInLevel`'s `spawn_mobs` game rule.
|
||||
fn mob_spawning(&self) -> bool;
|
||||
/// `level.getPlayers()`, in the server's order.
|
||||
fn players(&self) -> Vec<TrialPlayer>;
|
||||
/// The block a VISUAL clip from `from` to `to` (no fluids) first hits.
|
||||
fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]>;
|
||||
/// The block position of a living entity of this dimension, if any.
|
||||
fn entity_block(&self, uuid: Uuid) -> Option<[i32; 3]>;
|
||||
}
|
||||
|
||||
/// `TrialSpawner` with its `TrialSpawnerStateData`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TrialSpawner {
|
||||
pub normal: ConfigSlot,
|
||||
pub ominous: ConfigSlot,
|
||||
pub target_cooldown_length: i32,
|
||||
pub required_player_range: i32,
|
||||
pub detected_players: Vec<Uuid>,
|
||||
pub current_mobs: Vec<Uuid>,
|
||||
pub cooldown_ends_at: i64,
|
||||
pub next_mob_spawns_at: i64,
|
||||
pub total_mobs_spawned: i32,
|
||||
pub next_spawn_data: Option<SpawnData>,
|
||||
pub ejecting_loot_table: Option<String>,
|
||||
/// `isOminous`, set from the block on every server tick.
|
||||
pub is_ominous: bool,
|
||||
/// The server's display entity exists (`getOrCreateDisplayEntity`): it is
|
||||
/// made once per loaded block entity and kept.
|
||||
pub has_display: bool,
|
||||
pub spin: f64,
|
||||
pub o_spin: f64,
|
||||
}
|
||||
impl Default for TrialSpawner {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
normal: ConfigSlot::default(),
|
||||
ominous: ConfigSlot::default(),
|
||||
target_cooldown_length: 36000,
|
||||
required_player_range: 14,
|
||||
detected_players: Vec::new(),
|
||||
current_mobs: Vec::new(),
|
||||
cooldown_ends_at: 0,
|
||||
next_mob_spawns_at: 0,
|
||||
total_mobs_spawned: 0,
|
||||
next_spawn_data: None,
|
||||
ejecting_loot_table: None,
|
||||
is_ominous: false,
|
||||
has_display: false,
|
||||
spin: 0.0,
|
||||
o_spin: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn uuids(tag: Option<&Tag>) -> Vec<Uuid> {
|
||||
let Some(Tag::List(list)) = tag else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out: Vec<Uuid> = Vec::new();
|
||||
for t in list {
|
||||
if let Tag::IntArray(v) = t
|
||||
&& let Ok(u) = <Uuid>::try_from(v.as_slice())
|
||||
&& !out.contains(&u)
|
||||
{
|
||||
out.push(u);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn encode_uuids(list: &[Uuid]) -> Tag {
|
||||
Tag::List(list.iter().map(|u| Tag::IntArray(u.to_vec())).collect())
|
||||
}
|
||||
|
||||
impl TrialSpawner {
|
||||
/// `TrialSpawner.load`, with the configs of [`load_registry`].
|
||||
pub fn load(tag: &Tag) -> Self {
|
||||
Self::load_with(tag, ®istry_config)
|
||||
}
|
||||
/// `TrialSpawner.load`. `registry` resolves a config id.
|
||||
pub fn load_with(tag: &Tag, registry: &dyn Fn(&str) -> Option<TrialConfig>) -> Self {
|
||||
let long = |k: &str| match tag.get(k) {
|
||||
Some(Tag::Long(v)) => *v,
|
||||
t => spawner::number(t).unwrap_or(0),
|
||||
};
|
||||
let mut s = Self {
|
||||
detected_players: uuids(tag.get("registered_players")),
|
||||
current_mobs: uuids(tag.get("current_mobs")),
|
||||
cooldown_ends_at: long("cooldown_ends_at"),
|
||||
next_mob_spawns_at: long("next_mob_spawns_at"),
|
||||
total_mobs_spawned: spawner::number(tag.get("total_mobs_spawned"))
|
||||
.filter(|v| (0..=i64::from(i32::MAX)).contains(v))
|
||||
.map_or(0, |v| v as i32),
|
||||
next_spawn_data: tag.get("spawn_data").and_then(SpawnData::decode),
|
||||
ejecting_loot_table: identifier(tag.get("ejecting_loot_table")),
|
||||
..Self::default()
|
||||
};
|
||||
// FullConfig.MAP_CODEC, partial result kept: a field that fails to
|
||||
// decode takes its default.
|
||||
let slot = |k: &str| -> ConfigSlot {
|
||||
let config = match tag.get(k) {
|
||||
Some(Tag::String(id)) => {
|
||||
spawner::normalize_id(&id.to_string_lossy()).and_then(|id| registry(&id))
|
||||
}
|
||||
Some(t) => TrialConfig::decode(t),
|
||||
None => None,
|
||||
};
|
||||
config.map_or_else(ConfigSlot::default, |config| ConfigSlot {
|
||||
saved: tag.get(k).cloned(),
|
||||
config,
|
||||
})
|
||||
};
|
||||
let int = |k: &str, default: i32, lo: i32, hi: i32| {
|
||||
spawner::number(tag.get(k))
|
||||
.filter(|v| (i64::from(lo)..=i64::from(hi)).contains(v))
|
||||
.map_or(default, |v| v as i32)
|
||||
};
|
||||
s.normal = slot("normal_config");
|
||||
s.ominous = slot("ominous_config");
|
||||
s.target_cooldown_length = int("target_cooldown_length", 36000, 0, i32::MAX);
|
||||
s.required_player_range = int("required_player_range", 14, 1, 128);
|
||||
s
|
||||
}
|
||||
/// `TrialSpawner.store`: the state data's fields that differ from their
|
||||
/// defaults, then the configs.
|
||||
pub fn save(&self) -> Vec<(&'static str, Tag)> {
|
||||
let mut out = Vec::new();
|
||||
if !self.detected_players.is_empty() {
|
||||
out.push(("registered_players", encode_uuids(&self.detected_players)));
|
||||
}
|
||||
if !self.current_mobs.is_empty() {
|
||||
out.push(("current_mobs", encode_uuids(&self.current_mobs)));
|
||||
}
|
||||
if self.cooldown_ends_at != 0 {
|
||||
out.push(("cooldown_ends_at", Tag::Long(self.cooldown_ends_at)));
|
||||
}
|
||||
if self.next_mob_spawns_at != 0 {
|
||||
out.push(("next_mob_spawns_at", Tag::Long(self.next_mob_spawns_at)));
|
||||
}
|
||||
if self.total_mobs_spawned != 0 {
|
||||
out.push(("total_mobs_spawned", Tag::Int(self.total_mobs_spawned)));
|
||||
}
|
||||
if let Some(d) = &self.next_spawn_data {
|
||||
out.push(("spawn_data", d.encode()));
|
||||
}
|
||||
if let Some(t) = &self.ejecting_loot_table {
|
||||
out.push(("ejecting_loot_table", Tag::String(t.as_str().into())));
|
||||
}
|
||||
for (key, slot) in [
|
||||
("normal_config", &self.normal),
|
||||
("ominous_config", &self.ominous),
|
||||
] {
|
||||
if let Some(t) = &slot.saved {
|
||||
out.push((key, t.clone()));
|
||||
}
|
||||
}
|
||||
if self.target_cooldown_length != 36000 {
|
||||
out.push((
|
||||
"target_cooldown_length",
|
||||
Tag::Int(self.target_cooldown_length),
|
||||
));
|
||||
}
|
||||
if self.required_player_range != 14 {
|
||||
out.push((
|
||||
"required_player_range",
|
||||
Tag::Int(self.required_player_range),
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `TrialSpawnerStateData.getUpdateTag`.
|
||||
pub fn update_tag(&self, state: TrialState) -> Tag {
|
||||
let mut out = Compound::new();
|
||||
if state == TrialState::Active {
|
||||
out.insert(
|
||||
"next_mob_spawns_at".into(),
|
||||
Tag::Long(self.next_mob_spawns_at),
|
||||
);
|
||||
}
|
||||
if let Some(d) = &self.next_spawn_data {
|
||||
out.insert("spawn_data".into(), d.encode());
|
||||
}
|
||||
Tag::Compound(out)
|
||||
}
|
||||
/// `activeConfig`.
|
||||
pub fn active_config(&self) -> &TrialConfig {
|
||||
if self.is_ominous {
|
||||
&self.ominous.config
|
||||
} else {
|
||||
&self.normal.config
|
||||
}
|
||||
}
|
||||
/// `resetStatistics`.
|
||||
fn reset_statistics(&mut self) {
|
||||
self.detected_players.clear();
|
||||
self.total_mobs_spawned = 0;
|
||||
self.next_mob_spawns_at = 0;
|
||||
self.cooldown_ends_at = 0;
|
||||
}
|
||||
/// `reset`.
|
||||
fn reset(&mut self) {
|
||||
self.current_mobs.clear();
|
||||
self.next_spawn_data = None;
|
||||
self.reset_statistics();
|
||||
}
|
||||
/// `getOrCreateNextSpawnData`: a potential at random, else empty data.
|
||||
fn next_or_create(
|
||||
&mut self,
|
||||
random: &mut impl RandomSource,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> &SpawnData {
|
||||
if self.next_spawn_data.is_none() {
|
||||
let potentials = &self.active_config().spawn_potentials;
|
||||
let picked = spawner::weighted_index(potentials.iter().map(|(_, w)| *w), random)
|
||||
.map(|i| potentials[i].0.clone());
|
||||
self.next_spawn_data = Some(picked.unwrap_or_default());
|
||||
events.push(TrialEvent::BlockUpdated);
|
||||
}
|
||||
self.next_spawn_data.get_or_insert_default()
|
||||
}
|
||||
/// `hasMobToSpawn`.
|
||||
fn has_mob_to_spawn(
|
||||
&mut self,
|
||||
random: &mut impl RandomSource,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> bool {
|
||||
self.next_or_create(random, events).id().is_some()
|
||||
// WeightedList.isEmpty: a total weight of 0.
|
||||
|| self.active_config().spawn_potentials.iter().any(|(_, w)| *w > 0)
|
||||
}
|
||||
/// `canSpawnInLevel`.
|
||||
fn can_spawn_in_level<L: TrialSpawnerLevel>(l: &L) -> bool {
|
||||
l.spawner_blocks_work() && !l.peaceful() && l.mob_spawning()
|
||||
}
|
||||
/// `PlayerDetector.NO_CREATIVE_PLAYERS.detect`.
|
||||
fn detect<L: TrialSpawnerLevel>(&self, l: &L, pos: [i32; 3], line_of_sight: bool) -> Vec<Uuid> {
|
||||
let range = f64::from(self.required_player_range);
|
||||
l.players()
|
||||
.into_iter()
|
||||
.filter(|p| {
|
||||
let d = [0, 1, 2].map(|i| f64::from(p.block[i] - pos[i]));
|
||||
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range
|
||||
&& !p.creative
|
||||
&& !p.spectator
|
||||
})
|
||||
.filter(|p| !line_of_sight || in_line_of_sight(l, center(pos), p.eye))
|
||||
.map(|p| p.uuid)
|
||||
.collect()
|
||||
}
|
||||
/// `tryDetectPlayers`, every 20 ticks.
|
||||
fn try_detect_players<L: TrialSpawnerLevel>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
pos: [i32; 3],
|
||||
state: TrialState,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) {
|
||||
let packed = BlockPos::new(pos[0], pos[1], pos[2]).pack();
|
||||
if packed.wrapping_add(l.game_time()) % 20 != 0 {
|
||||
return;
|
||||
}
|
||||
if state == TrialState::Cooldown {
|
||||
return;
|
||||
}
|
||||
let in_sight = self.detect(l, pos, true);
|
||||
let found = if self.detected_players.is_empty() {
|
||||
in_sight
|
||||
} else {
|
||||
self.detect(l, pos, false)
|
||||
};
|
||||
let mut added = false;
|
||||
for uuid in found {
|
||||
if !self.detected_players.contains(&uuid) {
|
||||
self.detected_players.push(uuid);
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
if added {
|
||||
self.next_mob_spawns_at = (l.game_time() + 40).max(self.next_mob_spawns_at);
|
||||
let id = if self.is_ominous { 3019 } else { 3013 };
|
||||
events.push(TrialEvent::LevelEvent(
|
||||
id,
|
||||
pos,
|
||||
self.detected_players.len() as i32,
|
||||
));
|
||||
}
|
||||
}
|
||||
/// `TrialSpawner.tickServer`: the next state of the block.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn server_tick<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
random: &mut R,
|
||||
pos: [i32; 3],
|
||||
state: TrialState,
|
||||
ominous: bool,
|
||||
spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option<Uuid>,
|
||||
eject: &mut dyn FnMut(&str, &mut R) -> bool,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> TrialState {
|
||||
self.is_ominous = ominous;
|
||||
let before = self.current_mobs.len();
|
||||
let max = MAX_MOB_TRACKING_DISTANCE * MAX_MOB_TRACKING_DISTANCE;
|
||||
self.current_mobs.retain(|id| {
|
||||
l.entity_block(*id).is_some_and(|b| {
|
||||
let d = [0, 1, 2].map(|i| i64::from(b[i] - pos[i]));
|
||||
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= max
|
||||
})
|
||||
});
|
||||
if self.current_mobs.len() != before {
|
||||
self.next_mob_spawns_at =
|
||||
l.game_time() + i64::from(self.active_config().ticks_between_spawn);
|
||||
}
|
||||
self.tick_and_get_next(l, random, pos, state, spawn, eject, events)
|
||||
}
|
||||
/// `TrialSpawnerState.tickAndGetNext`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn tick_and_get_next<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
random: &mut R,
|
||||
pos: [i32; 3],
|
||||
state: TrialState,
|
||||
spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option<Uuid>,
|
||||
eject: &mut dyn FnMut(&str, &mut R) -> bool,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> TrialState {
|
||||
use TrialState as S;
|
||||
let now = l.game_time();
|
||||
match state {
|
||||
S::Inactive => {
|
||||
// getOrCreateDisplayEntity: made once, from the next data's id.
|
||||
if !self.has_display {
|
||||
let id = self.next_or_create(random, events).id();
|
||||
self.has_display = id.is_some_and(|id| l.entity_exists(&id));
|
||||
}
|
||||
if self.has_display {
|
||||
S::WaitingForPlayers
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
S::WaitingForPlayers => {
|
||||
if !Self::can_spawn_in_level(l) {
|
||||
self.reset_statistics();
|
||||
state
|
||||
} else if !self.has_mob_to_spawn(random, events) {
|
||||
S::Inactive
|
||||
} else {
|
||||
self.try_detect_players(l, pos, state, events);
|
||||
if self.detected_players.is_empty() {
|
||||
state
|
||||
} else {
|
||||
S::Active
|
||||
}
|
||||
}
|
||||
}
|
||||
S::Active => {
|
||||
if !Self::can_spawn_in_level(l) {
|
||||
self.reset_statistics();
|
||||
return S::WaitingForPlayers;
|
||||
}
|
||||
if !self.has_mob_to_spawn(random, events) {
|
||||
return S::Inactive;
|
||||
}
|
||||
let config = self.active_config().clone();
|
||||
let additional = (self.detected_players.len() as i32 - 1).max(0);
|
||||
self.try_detect_players(l, pos, state, events);
|
||||
if self.total_mobs_spawned >= config.target_total_mobs(additional) {
|
||||
if self.current_mobs.is_empty() {
|
||||
self.cooldown_ends_at = now + i64::from(self.target_cooldown_length);
|
||||
self.total_mobs_spawned = 0;
|
||||
self.next_mob_spawns_at = 0;
|
||||
return S::WaitingForRewardEjection;
|
||||
}
|
||||
} else if now >= self.next_mob_spawns_at
|
||||
&& (self.current_mobs.len() as i32)
|
||||
< config.target_simultaneous_mobs(additional)
|
||||
&& let Some(uuid) = self.spawn_mob(l, random, pos, spawn, events)
|
||||
{
|
||||
self.current_mobs.push(uuid);
|
||||
self.total_mobs_spawned += 1;
|
||||
self.next_mob_spawns_at = now + i64::from(config.ticks_between_spawn);
|
||||
let potentials = &config.spawn_potentials;
|
||||
if let Some(i) =
|
||||
spawner::weighted_index(potentials.iter().map(|(_, w)| *w), random)
|
||||
{
|
||||
self.next_spawn_data = Some(potentials[i].0.clone());
|
||||
events.push(TrialEvent::BlockUpdated);
|
||||
}
|
||||
}
|
||||
state
|
||||
}
|
||||
S::WaitingForRewardEjection => {
|
||||
let started = self.cooldown_ends_at - i64::from(self.target_cooldown_length);
|
||||
if now as f32 >= started as f32 + DELAY_BEFORE_EJECT {
|
||||
events.push(TrialEvent::Sound("block.trial_spawner.open_shutter"));
|
||||
S::EjectingReward
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
S::EjectingReward => {
|
||||
let started = self.cooldown_ends_at - i64::from(self.target_cooldown_length);
|
||||
if (now - started) as f32 % TIME_BETWEEN_EJECTIONS != 0.0 {
|
||||
return state;
|
||||
}
|
||||
if self.detected_players.is_empty() {
|
||||
events.push(TrialEvent::Sound("block.trial_spawner.close_shutter"));
|
||||
self.ejecting_loot_table = None;
|
||||
return S::Cooldown;
|
||||
}
|
||||
if self.ejecting_loot_table.is_none() {
|
||||
let tables = &self.active_config().loot_tables_to_eject;
|
||||
self.ejecting_loot_table =
|
||||
spawner::weighted_index(tables.iter().map(|(_, w)| *w), random)
|
||||
.map(|i| tables[i].0.clone());
|
||||
}
|
||||
if let Some(table) = self.ejecting_loot_table.clone()
|
||||
&& eject(&table, random)
|
||||
{
|
||||
events.push(TrialEvent::LevelEvent(3014, pos, 0));
|
||||
}
|
||||
self.detected_players.remove(0);
|
||||
state
|
||||
}
|
||||
S::Cooldown => {
|
||||
self.try_detect_players(l, pos, state, events);
|
||||
if !self.detected_players.is_empty() {
|
||||
self.total_mobs_spawned = 0;
|
||||
self.next_mob_spawns_at = 0;
|
||||
S::Active
|
||||
} else if now >= self.cooldown_ends_at {
|
||||
self.is_ominous = false;
|
||||
events.push(TrialEvent::OminousSet(false));
|
||||
self.reset();
|
||||
S::WaitingForPlayers
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `TrialSpawner.spawnMob`: the UUID of the mob added, if one was.
|
||||
fn spawn_mob<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
random: &mut R,
|
||||
pos: [i32; 3],
|
||||
spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option<Uuid>,
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) -> Option<Uuid> {
|
||||
let data = self.next_or_create(random, events).clone();
|
||||
// EntityType.by: an unknown type spawns nothing.
|
||||
let id = data.id().filter(|id| l.entity_exists(id))?;
|
||||
let at = match spawner::read_pos(data.entity.get(&JavaString::from("Pos"))) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
let range = f64::from(self.active_config().spawn_range);
|
||||
let x =
|
||||
f64::from(pos[0]) + (random.next_double() - random.next_double()) * range + 0.5;
|
||||
let y = f64::from(pos[1] + random.next_int_bound(3).unwrap_or(0) - 1);
|
||||
let z =
|
||||
f64::from(pos[2]) + (random.next_double() - random.next_double()) * range + 0.5;
|
||||
[x, y, z]
|
||||
}
|
||||
};
|
||||
// Entity types Horizon cannot create spawn nothing.
|
||||
let (species, width, height, _) = l.mob_type(&id)?;
|
||||
let spawn_box = spawn_selection::spawn_aabb(species, at[0], at[1], at[2], width, height);
|
||||
if !l.no_collision(spawn_box) || !in_line_of_sight(l, center(pos), at) {
|
||||
return None;
|
||||
}
|
||||
let block = at.map(|v| v.floor() as i32);
|
||||
if !spawn_rules::check_spawn_rules(
|
||||
species,
|
||||
l,
|
||||
Reason::TrialSpawner,
|
||||
random,
|
||||
block[0],
|
||||
block[1],
|
||||
block[2],
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
if let Some(rules) = data.custom_spawn_rules
|
||||
&& !SpawnData::valid_position(rules, l, block[0], block[1], block[2])
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let yaw = random.next_float() * 360.0;
|
||||
let placed = spawner::entity_position(species, at);
|
||||
let own = placed.map(|v| v.floor() as i32);
|
||||
let scale = spawner::cube_scale(&id, &data.entity);
|
||||
let bounds = spawn_selection::spawn_box(
|
||||
placed[0],
|
||||
placed[1],
|
||||
placed[2],
|
||||
width * scale,
|
||||
height * scale,
|
||||
);
|
||||
if !spawn_selection::spawn_obstruction(species, l, bounds, &[], own[0], own[1], own[2]) {
|
||||
return None;
|
||||
}
|
||||
let request = SpawnerSpawn {
|
||||
entity: &data.entity,
|
||||
id: &id,
|
||||
position: placed,
|
||||
yaw,
|
||||
finalize: data.unconfigured(),
|
||||
equipment: data.equipment.as_ref(),
|
||||
trial: true,
|
||||
};
|
||||
let uuid = spawn(l, &request)?;
|
||||
let flame = i32::from(self.is_ominous);
|
||||
events.push(TrialEvent::LevelEvent(3011, pos, flame));
|
||||
events.push(TrialEvent::LevelEvent(3012, block, flame));
|
||||
events.push(TrialEvent::EntityPlace(uuid, block));
|
||||
Some(uuid)
|
||||
}
|
||||
}
|
||||
|
||||
/// `Vec3.atCenterOf`.
|
||||
fn center(pos: [i32; 3]) -> [f64; 3] {
|
||||
pos.map(|v| f64::from(v) + 0.5)
|
||||
}
|
||||
/// `TrialSpawner.inLineOfSight`: a VISUAL clip from `to` back to the spawner
|
||||
/// hits nothing, or the spawner's own block.
|
||||
fn in_line_of_sight<L: TrialSpawnerLevel>(l: &L, origin: [f64; 3], to: [f64; 3]) -> bool {
|
||||
match l.visual_hit(to, origin) {
|
||||
None => true,
|
||||
Some(b) => b == origin.map(|v| v.floor() as i32),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tag(snbt: &str) -> Tag {
|
||||
horizon_world::nbt::parse_snbt(snbt).expect("snbt").0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_load_and_save_to_nothing() {
|
||||
let s = TrialSpawner::load_with(&tag("{}"), &|_| None);
|
||||
assert_eq!(s, TrialSpawner::default());
|
||||
assert!(s.save().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_configs_resolve_and_are_saved_by_id() {
|
||||
let breeze = TrialConfig {
|
||||
total_mobs: 2.0,
|
||||
..TrialConfig::default()
|
||||
};
|
||||
let registry =
|
||||
|id: &str| (id == "minecraft:trial_chamber/breeze/normal").then(|| breeze.clone());
|
||||
let s = TrialSpawner::load_with(
|
||||
&tag(
|
||||
r#"{normal_config:"minecraft:trial_chamber/breeze/normal",required_player_range:10}"#,
|
||||
),
|
||||
®istry,
|
||||
);
|
||||
assert_eq!(s.normal.config.total_mobs, 2.0);
|
||||
assert_eq!(s.required_player_range, 10);
|
||||
let saved: Vec<_> = s.save().into_iter().map(|(k, _)| k).collect();
|
||||
assert_eq!(saved, ["normal_config", "required_player_range"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_field_takes_its_default_alone() {
|
||||
let s = TrialSpawner::load_with(
|
||||
&tag(
|
||||
r#"{normal_config:"minecraft:nope",required_player_range:200,target_cooldown_length:5}"#,
|
||||
),
|
||||
&|_| None,
|
||||
);
|
||||
assert_eq!(s.normal, ConfigSlot::default());
|
||||
assert_eq!(s.required_player_range, 14);
|
||||
assert_eq!(s.target_cooldown_length, 5);
|
||||
let c = TrialConfig::decode(&tag(
|
||||
r#"{spawn_range:0,total_mobs:3.0f,spawn_potentials:[{data:{entity:{id:"minecraft:zombie"}},weight:-1},{data:{entity:{id:"minecraft:husk"}},weight:2}]}"#,
|
||||
))
|
||||
.expect("config");
|
||||
assert_eq!(c.spawn_range, 4);
|
||||
assert_eq!(c.total_mobs, 3.0);
|
||||
assert_eq!(c.spawn_potentials.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_floor_the_per_player_additions() {
|
||||
let c = TrialConfig {
|
||||
simultaneous_mobs: 1.0,
|
||||
simultaneous_mobs_added_per_player: 0.5,
|
||||
..TrialConfig::default()
|
||||
};
|
||||
assert_eq!(c.target_simultaneous_mobs(0), 1);
|
||||
assert_eq!(c.target_simultaneous_mobs(1), 1);
|
||||
assert_eq!(c.target_simultaneous_mobs(2), 2);
|
||||
assert_eq!(c.target_total_mobs(3), 12);
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,18 @@
|
||||
//! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent
|
||||
//! values and the positions of other entities.
|
||||
use super::{MobWorld, Seen, Species, Who, data};
|
||||
use crate::{blocks::Fluid, collisions::SceneCollisions};
|
||||
use crate::{
|
||||
blocks::{BlockFacts, Fluid},
|
||||
collisions::SceneCollisions,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3, traverse_blocks},
|
||||
position::BlockPos,
|
||||
};
|
||||
use horizon_world::{
|
||||
block_collision::{BlockCollisionRegistry, DynamicCollisionWorld},
|
||||
registry::BlockStateId,
|
||||
};
|
||||
|
||||
/// Where a target entity is this tick.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -81,38 +88,23 @@ impl MobWorld<'_> {
|
||||
});
|
||||
matches!(result, Ok(None))
|
||||
}
|
||||
/// Level.clip with VISUAL shapes and no fluids: true on a miss. Glass
|
||||
/// (`TransparentBlock`) and bars and panes (`IronBarsBlock`) have no
|
||||
/// visual shape; mud, soul sand and powder snow look like full blocks.
|
||||
/// Level.clip with VISUAL shapes and no fluids: true on a miss.
|
||||
pub fn visual_clear_between(&self, from: Vec3, to: Vec3) -> bool {
|
||||
self.visual_clip(from, to) == Some(None)
|
||||
}
|
||||
/// Level.clip with VISUAL shapes and no fluids: the block the segment
|
||||
/// first hits, if it does.
|
||||
pub fn visual_hit(&self, from: Vec3, to: Vec3) -> Option<[i32; 3]> {
|
||||
self.visual_clip(from, to).flatten()
|
||||
}
|
||||
fn visual_clip(&self, from: Vec3, to: Vec3) -> Option<Option<[i32; 3]>> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
subject: None,
|
||||
};
|
||||
let full = horizon_core::geometry::Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0));
|
||||
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let state = self.world.block(p.x, p.y, p.z);
|
||||
if self.facts.is_air(state) {
|
||||
return None;
|
||||
}
|
||||
let name = self.facts.get(state).name.trim_start_matches("minecraft:");
|
||||
if name.ends_with("glass") || name.ends_with("glass_pane") || name.ends_with("_bars") {
|
||||
return None;
|
||||
}
|
||||
if matches!(name, "mud" | "soul_sand" | "powder_snow") {
|
||||
return full
|
||||
.move_by(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)))
|
||||
.clip(from, to)
|
||||
.map(|_| ());
|
||||
}
|
||||
let shape = self
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.ok()?;
|
||||
shape.clip(from, to, p).map(|_| ())
|
||||
});
|
||||
matches!(result, Ok(None))
|
||||
let state = |x, y, z| self.world.block(x, y, z);
|
||||
visual_clip(self.facts, self.collision, &mut scene, &state, from, to)
|
||||
}
|
||||
/// Level.clip with COLLIDER shapes and no fluids: where the segment
|
||||
/// first hits a block, if it does.
|
||||
@@ -260,3 +252,42 @@ impl MobWorld<'_> {
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Level.clip with VISUAL shapes and no fluids: the block the segment first
|
||||
/// hits, None inside when it hits nothing and outside when the segment is
|
||||
/// too long to walk. Glass and copper grates (`TransparentBlock`) and bars and panes
|
||||
/// (`IronBarsBlock`) have no visual shape; mud, soul sand and powder snow
|
||||
/// look like full blocks.
|
||||
pub fn visual_clip<W: DynamicCollisionWorld>(
|
||||
facts: &BlockFacts,
|
||||
collision: &BlockCollisionRegistry,
|
||||
scene: &mut W,
|
||||
state: &dyn Fn(i32, i32, i32) -> BlockStateId,
|
||||
from: Vec3,
|
||||
to: Vec3,
|
||||
) -> Option<Option<[i32; 3]>> {
|
||||
let full = Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0));
|
||||
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let id = state(p.x, p.y, p.z);
|
||||
if facts.is_air(id) {
|
||||
return None;
|
||||
}
|
||||
let name = facts.get(id).name.trim_start_matches("minecraft:");
|
||||
if name.ends_with("glass")
|
||||
|| name.ends_with("glass_pane")
|
||||
|| name.ends_with("_bars")
|
||||
|| name.ends_with("copper_grate")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if matches!(name, "mud" | "soul_sand" | "powder_snow") {
|
||||
return full
|
||||
.move_by(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)))
|
||||
.clip(from, to)
|
||||
.map(|_| [p.x, p.y, p.z]);
|
||||
}
|
||||
let shape = collision.collision_shape(scene, id, [p.x, p.y, p.z]).ok()?;
|
||||
shape.clip(from, to, p).map(|_| [p.x, p.y, p.z])
|
||||
});
|
||||
result.ok()
|
||||
}
|
||||
|
||||
@@ -552,6 +552,31 @@ impl LootData {
|
||||
*random = c.random;
|
||||
items
|
||||
}
|
||||
/// LootTable.getRandomItems with an empty context (a trial spawner's
|
||||
/// reward): the stacks after the stack splitter. `random` is the table's
|
||||
/// random sequence (or the level random) and is advanced.
|
||||
pub fn roll_split<R: RandomSource + Clone>(
|
||||
&self,
|
||||
table: &str,
|
||||
random: &mut R,
|
||||
) -> Vec<LootStack> {
|
||||
let Some(json) = self.tables.get(table) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut c = Context {
|
||||
data: self,
|
||||
random: random.clone(),
|
||||
biome: None,
|
||||
visited: Vec::new(),
|
||||
luck: 0.0,
|
||||
open_water: None,
|
||||
entity: None,
|
||||
};
|
||||
let mut items = Vec::new();
|
||||
c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items));
|
||||
*random = c.random;
|
||||
items
|
||||
}
|
||||
/// LootTable.createStackSplitter (every item is enabled).
|
||||
fn split(&self, stack: LootStack, items: &mut Vec<LootStack>) {
|
||||
let max = self.facts(&stack.item).max_stack.max(1);
|
||||
|
||||
@@ -77,6 +77,11 @@ import net.minecraft.world.phys.Vec3;
|
||||
* here is a fixed "neutral" source (nextInt 0, nextFloat and nextDouble 0.75),
|
||||
* so finalizeSpawn's own outcomes stay out of scope while its effect on later
|
||||
* attempts (the finalized mob's box obstructs them) is deterministic.
|
||||
*
|
||||
* Spawner cases tick a SpawnerBlockEntity; trial cases tick a
|
||||
* TrialSpawnerBlockEntity with the game time advancing, its block's state
|
||||
* changes, sounds, ejected items (loot tables and random sequences of the
|
||||
* vanilla data) and, when asked, the death of every mob it spawned.
|
||||
*/
|
||||
public final class VanillaNaturalSpawnOracle {
|
||||
static Object unsafe;
|
||||
@@ -167,7 +172,10 @@ public final class VanillaNaturalSpawnOracle {
|
||||
int next = 1;
|
||||
@Override public RegistryAccess registryAccess() { return registries; }
|
||||
@Override public Difficulty getDifficulty() { return difficulty; }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
/** The game time (trial cases advance it). */
|
||||
long time;
|
||||
net.minecraft.world.level.block.entity.BlockEntity trial;
|
||||
@Override public long getGameTime() { return time; }
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
@Override public BlockState getBlockState(BlockPos pos) {
|
||||
@@ -215,6 +223,23 @@ public final class VanillaNaturalSpawnOracle {
|
||||
log.add(tick + " spawn " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()) + " " + bits(entity.getX()) + " " + bits(entity.getY()) + " " + bits(entity.getZ()) + " " + yaw(entity));
|
||||
return true;
|
||||
}
|
||||
@Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int recursionLeft) {
|
||||
blocks.add(Map.entry(new Box(pos.getX(), pos.getY(), pos.getZ(), pos.getX(), pos.getY(), pos.getZ()), state));
|
||||
if (trial != null && trial.getBlockPos().equals(pos)) trial.setBlockState(state);
|
||||
if (tick >= 0) log.add(tick + " state " + state.getOptionalValue(net.minecraft.world.level.block.TrialSpawnerBlock.STATE).map(v -> v.getSerializedName()).orElse("-")
|
||||
+ " " + state.getOptionalValue(net.minecraft.world.level.block.TrialSpawnerBlock.OMINOUS).orElse(false));
|
||||
return true;
|
||||
}
|
||||
@Override public void blockEntityChanged(BlockPos pos) {}
|
||||
@Override public void updateNeighbourForOutputSignal(BlockPos pos, net.minecraft.world.level.block.Block block) {}
|
||||
@Override public Entity getEntity(UUID uuid) {
|
||||
for (Entity e : entities) if (e.getUUID().equals(uuid)) return e;
|
||||
for (Entity e : playerList) if (e.getUUID().equals(uuid)) return e;
|
||||
return null;
|
||||
}
|
||||
@Override public void playSound(Entity except, double x, double y, double z, net.minecraft.sounds.SoundEvent sound, net.minecraft.sounds.SoundSource source, float volume, float pitch) {
|
||||
if (tick >= 0) log.add(tick + " sound " + sound.location() + " " + bits(x) + " " + bits(y) + " " + bits(z) + " " + volume + " " + pitch);
|
||||
}
|
||||
@Override public void blockEvent(BlockPos pos, net.minecraft.world.level.block.Block block, int b0, int b1) { if (tick >= 0) log.add(tick + " bevent " + b0 + " " + b1); }
|
||||
@Override public void sendBlockUpdated(BlockPos pos, BlockState old, BlockState current, int flags) { if (tick >= 0) log.add(tick + " update"); }
|
||||
@Override public void levelEvent(Entity source, int type, BlockPos pos, int data) { if (tick >= 0) log.add(tick + " levent " + type + " " + data); }
|
||||
@@ -249,7 +274,14 @@ public final class VanillaNaturalSpawnOracle {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@Override public boolean addFreshEntity(Entity entity) { entities.add(entity); return true; }
|
||||
@Override public boolean addFreshEntity(Entity entity) {
|
||||
if (entity instanceof net.minecraft.world.entity.item.ItemEntity item && tick >= 0) {
|
||||
Vec3 v = item.getDeltaMovement();
|
||||
log.add(tick + " item " + BuiltInRegistries.ITEM.getKey(item.getItem().getItem()) + " " + item.getItem().getCount() + " " + bits(item.getX()) + " " + bits(item.getY()) + " " + bits(item.getZ()) + " " + bits(v.x) + " " + bits(v.y) + " " + bits(v.z));
|
||||
}
|
||||
entities.add(entity);
|
||||
return true;
|
||||
}
|
||||
@Override public void addFreshEntityWithPassengers(Entity entity) { entity.getSelfAndPassengers().forEach(this::addFreshEntity); }
|
||||
@Override public Player getNearestPlayer(double x, double y, double z, double maxDist, boolean filter) {
|
||||
if (maxDist == -1.0 && !filter) log.add("try " + (int) Math.floor(x) + " " + (int) Math.floor(z));
|
||||
@@ -257,6 +289,16 @@ public final class VanillaNaturalSpawnOracle {
|
||||
}
|
||||
}
|
||||
|
||||
/** The server: loot tables and random sequences for trial spawner rewards. */
|
||||
static final class OracleServer extends net.minecraft.server.dedicated.DedicatedServer {
|
||||
OracleServer() { super(null, null, null, null, null, null, null, null, null, null); }
|
||||
net.minecraft.server.ReloadableServerRegistries.Holder registries;
|
||||
net.minecraft.world.RandomSequences sequences;
|
||||
long seed;
|
||||
@Override public net.minecraft.server.ReloadableServerRegistries.Holder reloadableRegistries() { return registries; }
|
||||
@Override public RandomSource getRandomSequence(Identifier key) { return sequences.get(key, seed); }
|
||||
}
|
||||
|
||||
static final class Chunk extends LevelChunk {
|
||||
Chunk() { super((Level) null, (ChunkPos) null); }
|
||||
Lvl level;
|
||||
@@ -352,6 +394,58 @@ public final class VanillaNaturalSpawnOracle {
|
||||
}
|
||||
static String bits(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
|
||||
|
||||
/**
|
||||
* TrialSpawner.tickServer `ticks` times from game time `t0` at `spos`, on a
|
||||
* trial spawner block in state `state` (ominous when `ominous=1`) loaded
|
||||
* from `snbt` (base64 SNBT). Every `kill` ticks the mobs it spawned die.
|
||||
*/
|
||||
static void trialCase(Lvl level, Map<String, String> c, RegistryAccess access, HolderLookup<net.minecraft.world.level.block.Block> blockLookup,
|
||||
RandomSource mainRandom, List<String> log) throws Exception {
|
||||
level.spawnerRandom = mainRandom;
|
||||
level.tick = -1;
|
||||
String[] sp = c.get("spos").split(",");
|
||||
BlockPos at = new BlockPos(Integer.parseInt(sp[0]), Integer.parseInt(sp[1]), Integer.parseInt(sp[2]));
|
||||
BlockState block = net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup,
|
||||
"minecraft:trial_spawner[trial_spawner_state=" + c.getOrDefault("state", "waiting_for_players") + ",ominous=" + c.getOrDefault("ominous", "0").equals("1") + "]", false).blockState();
|
||||
level.blocks.add(Map.entry(new Box(at.getX(), at.getY(), at.getZ(), at.getX(), at.getY(), at.getZ()), block));
|
||||
var nbt = net.minecraft.nbt.TagParser.parseCompoundFully(new String(Base64.getDecoder().decode(c.get("snbt")), StandardCharsets.UTF_8));
|
||||
var entity = new net.minecraft.world.level.block.entity.TrialSpawnerBlockEntity(at, block);
|
||||
entity.setLevel(level);
|
||||
level.trial = entity;
|
||||
entity.getTrialSpawner().load(net.minecraft.world.level.storage.TagValueInput.create(net.minecraft.util.ProblemReporter.DISCARDING, access, nbt));
|
||||
int ticks = Integer.parseInt(c.getOrDefault("ticks", "1"));
|
||||
long t0 = Long.parseLong(c.getOrDefault("t0", "0"));
|
||||
int kill = Integer.parseInt(c.getOrDefault("kill", "0"));
|
||||
int before = level.entities.size();
|
||||
try {
|
||||
for (int t = 0; t < ticks; t++) {
|
||||
level.tick = t;
|
||||
level.time = t0 + t;
|
||||
BlockState state = level.getBlockState(at);
|
||||
entity.getTrialSpawner().tickServer(level, at, state.getValue(net.minecraft.world.level.block.TrialSpawnerBlock.OMINOUS));
|
||||
if (kill > 0 && t % kill == kill - 1) {
|
||||
int n = 0;
|
||||
for (Iterator<Entity> it = level.entities.subList(before, level.entities.size()).iterator(); it.hasNext(); ) {
|
||||
if (it.next() instanceof Mob) { it.remove(); n++; }
|
||||
}
|
||||
if (n > 0) log.add(t + " kill " + n);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
level.tick = -1;
|
||||
level.spawnerRandom = null;
|
||||
}
|
||||
var out = net.minecraft.world.level.storage.TagValueOutput.createWithContext(net.minecraft.util.ProblemReporter.DISCARDING, access);
|
||||
entity.getTrialSpawner().store(out);
|
||||
CompoundTag saved = out.buildResult();
|
||||
String next = saved.getCompound("spawn_data").flatMap(d -> d.getCompound("entity")).flatMap(e -> e.getString("id")).orElse("-");
|
||||
log.add("end state=" + level.getBlockState(at).getValue(net.minecraft.world.level.block.TrialSpawnerBlock.STATE).getSerializedName()
|
||||
+ " players=" + saved.getListOrEmpty("registered_players").size() + " mobs=" + saved.getListOrEmpty("current_mobs").size()
|
||||
+ " cooldown=" + saved.getLongOr("cooldown_ends_at", 0L) + " next_spawn=" + saved.getLongOr("next_mob_spawns_at", 0L)
|
||||
+ " total=" + saved.getIntOr("total_mobs_spawned", 0) + " data=" + next + " eject=" + saved.getString("ejecting_loot_table").orElse("-"));
|
||||
log.add("next " + mainRandom.nextInt(1000));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
@@ -382,7 +476,8 @@ public final class VanillaNaturalSpawnOracle {
|
||||
var structureLookup = access.lookupOrThrow(Registries.STRUCTURE);
|
||||
|
||||
// A server that only answers debug subscribers (path navigation asks).
|
||||
var server = (net.minecraft.server.MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class);
|
||||
var server = (OracleServer) alloc(OracleServer.class);
|
||||
server.registries = new net.minecraft.server.ReloadableServerRegistries.Holder(lookup);
|
||||
put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class));
|
||||
Lvl level = (Lvl) alloc(Lvl.class);
|
||||
level.fake = server;
|
||||
@@ -423,6 +518,8 @@ public final class VanillaNaturalSpawnOracle {
|
||||
randomPos.setAccessible(true);
|
||||
Field entityId = Entity.class.getDeclaredField("id");
|
||||
entityId.setAccessible(true);
|
||||
Field eyeHeight = Entity.class.getDeclaredField("eyeHeight");
|
||||
eyeHeight.setAccessible(true);
|
||||
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]));
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
@@ -497,7 +594,12 @@ public final class VanillaNaturalSpawnOracle {
|
||||
OraclePlayer player = (OraclePlayer) alloc(OraclePlayer.class);
|
||||
player.mode = GameType.byName(p.length > 1 ? p[1] : "survival");
|
||||
entityId.setInt(player, 100000 + i);
|
||||
put(player, Entity.class, "position", new Vec3(Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2])));
|
||||
Vec3 at = new Vec3(Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2]));
|
||||
put(player, Entity.class, "position", at);
|
||||
put(player, Entity.class, "blockPosition", BlockPos.containing(at));
|
||||
put(player, Entity.class, "uuid", new UUID(0L, i + 1));
|
||||
eyeHeight.setFloat(player, 1.62F);
|
||||
put(player, LivingEntity.class, "activeEffects", new HashMap<>());
|
||||
level.playerList.add(player);
|
||||
}
|
||||
level.entities.clear();
|
||||
@@ -510,6 +612,11 @@ public final class VanillaNaturalSpawnOracle {
|
||||
if (p.length > 2 && p[2].equals("p") && e instanceof Mob mob) mob.setPersistenceRequired();
|
||||
level.entities.add(e);
|
||||
}
|
||||
put(level, ServerLevel.class, "players", level.playerList);
|
||||
server.sequences = new net.minecraft.world.RandomSequences();
|
||||
server.seed = level.seed;
|
||||
level.time = 0L;
|
||||
level.trial = null;
|
||||
RandomSource mainRandom = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
|
||||
put(level, Level.class, "random", mainRandom);
|
||||
String mode = c.getOrDefault("mode", "chunk");
|
||||
@@ -547,6 +654,8 @@ public final class VanillaNaturalSpawnOracle {
|
||||
}
|
||||
log.add("end delay=" + saved.getShortOr("Delay", (short) 0) + " next=" + next + " pots=" + pots);
|
||||
log.add("next " + mainRandom.nextInt(1000));
|
||||
} else if (mode.equals("trial")) {
|
||||
trialCase(level, c, access, blockLookup, mainRandom, log);
|
||||
} else if (mode.equals("gen")) {
|
||||
level.logColumns = true;
|
||||
int n = level.entities.size();
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare trial spawners (TrialSpawner.tickServer and TrialSpawnerState) with vanilla.
|
||||
|
||||
Java (VanillaNaturalSpawnOracle, mode=trial) loads a TrialSpawnerBlockEntity
|
||||
from each case's NBT on the oracle's stand-in ServerLevel, on a trial spawner
|
||||
block in the case's state, and runs `TrialSpawner.tickServer` tick by tick
|
||||
with the game time advancing. Rust (natural_spawn_fixture, mode=trial) loads
|
||||
`mobs::trial_spawner::TrialSpawner` from the same NBT and ticks it on the same
|
||||
world. Both log, tick by tick, the block's state changes, the player
|
||||
detection events, every spawn (type, exact position and yaw bits) with its
|
||||
level and game events, the next spawn data updates, the shutter sounds, each
|
||||
ejected item (type, count, position and velocity bits), and at the end the
|
||||
saved state data and the next draw of the level random, which pins every draw
|
||||
in between.
|
||||
|
||||
Rooms are tuff halls around the spawner with pillars, glass and bars between
|
||||
it and the players (line of sight), players inside and outside the required
|
||||
range in every game mode, configs from the trial chamber registry and inline
|
||||
ones from the edge values up, saved state data (registered players, tracked
|
||||
mobs that are gone, cooldowns, spawn data, a loot table being ejected), every
|
||||
state of the block, every difficulty and both game rules. Every so many ticks
|
||||
the case kills the mobs the spawner added, so waves finish, rewards are
|
||||
ejected and cooldowns run out.
|
||||
|
||||
finalizeSpawn runs with a fixed random in the oracle; its own outcomes are not
|
||||
compared. Ominous spawners (which also drop ominous item spawners) are not in
|
||||
the corpus yet.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import subprocess
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_natural_spawn_parity as natural
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
import test_natural_spawn_parity as natural
|
||||
|
||||
box = natural.box
|
||||
REGISTRY = ['breeze', 'melee/husk', 'melee/spider', 'melee/zombie', 'ranged/poison_skeleton', 'ranged/skeleton',
|
||||
'ranged/stray', 'slow_ranged/poison_skeleton', 'slow_ranged/skeleton', 'slow_ranged/stray',
|
||||
'small_melee/baby_zombie', 'small_melee/cave_spider', 'small_melee/silverfish', 'small_melee/slime']
|
||||
MOBS = ['zombie', 'husk', 'spider', 'cave_spider', 'skeleton', 'stray', 'bogged', 'breeze', 'slime', 'silverfish',
|
||||
'creeper', 'witch', 'pig', 'blaze']
|
||||
STATES = ['inactive', 'waiting_for_players', 'active', 'waiting_for_reward_ejection', 'ejecting_reward', 'cooldown']
|
||||
TABLES = ['minecraft:spawners/trial_chamber/consumables', 'minecraft:spawners/trial_chamber/key',
|
||||
'minecraft:chests/trial_chambers/reward', 'minecraft:spawners/ominous/trial_chamber/key']
|
||||
|
||||
|
||||
def uuid(rng):
|
||||
return '[I;' + ','.join(str(rng.randrange(-2**31, 2**31)) for _ in range(4)) + ']'
|
||||
|
||||
|
||||
def inline_config(rng):
|
||||
fields = []
|
||||
if rng.random() < 0.6:
|
||||
fields.append(f'spawn_range:{rng.choice([1, 2, 4, 4, 6, 10])}')
|
||||
for key, values in [('total_mobs', [0.0, 1.0, 2.0, 3.5, 6.0]), ('simultaneous_mobs', [0.0, 1.0, 2.0, 3.0]),
|
||||
('total_mobs_added_per_player', [0.0, 0.5, 1.0, 2.0]),
|
||||
('simultaneous_mobs_added_per_player', [0.0, 0.5, 1.0])]:
|
||||
if rng.random() < 0.6:
|
||||
fields.append(f'{key}:{rng.choice(values)}f')
|
||||
if rng.random() < 0.6:
|
||||
fields.append(f'ticks_between_spawn:{rng.choice([0, 1, 5, 20, 40, 160])}')
|
||||
if rng.random() < 0.9:
|
||||
entries = []
|
||||
for _ in range(rng.choice([1, 1, 2, 3])):
|
||||
mob = rng.choice(MOBS)
|
||||
entity = rng.choice([f'{{id:"minecraft:{mob}"}}', f'{{id:"{mob}"}}', f'{{id:"minecraft:{mob}",PersistenceRequired:1b}}',
|
||||
'{id:"minecraft:not_an_entity"}', '{}'] if rng.random() < 0.2 else [f'{{id:"minecraft:{mob}"}}'])
|
||||
entries.append(f'{{data:{{entity:{entity}}},weight:{rng.choice([1, 1, 2, 5, 0])}}}')
|
||||
fields.append('spawn_potentials:[' + ','.join(entries) + ']')
|
||||
if rng.random() < 0.4:
|
||||
entries = [f'{{data:"{rng.choice(TABLES)}",weight:{rng.choice([1, 1, 3, 0])}}}' for _ in range(rng.choice([1, 2, 3]))]
|
||||
fields.append('loot_tables_to_eject:[' + ','.join(entries) + ']')
|
||||
return '{' + ','.join(fields) + '}'
|
||||
|
||||
|
||||
def trial_snbt(rng, now):
|
||||
fields = []
|
||||
r = rng.random()
|
||||
if r < 0.6:
|
||||
name = rng.choice(REGISTRY)
|
||||
fields.append(f'normal_config:"minecraft:trial_chamber/{name}/normal"')
|
||||
fields.append(f'ominous_config:"minecraft:trial_chamber/{name}/ominous"')
|
||||
elif r < 0.9:
|
||||
fields.append(f'normal_config:{inline_config(rng)}')
|
||||
elif r < 0.95:
|
||||
fields.append('normal_config:"minecraft:trial_chamber/not_a_config"')
|
||||
if rng.random() < 0.5:
|
||||
fields.append(f'target_cooldown_length:{rng.choice([0, 1, 20, 45, 100, 200, 36000])}')
|
||||
if rng.random() < 0.4:
|
||||
fields.append(f'required_player_range:{rng.choice([1, 4, 8, 14, 20, 0, 200])}')
|
||||
if rng.random() < 0.15:
|
||||
fields.append('registered_players:[' + ','.join(rng.choice(['[I;0,0,0,1]', uuid(rng)]) for _ in range(rng.randrange(1, 3))) + ']')
|
||||
if rng.random() < 0.15:
|
||||
fields.append('current_mobs:[' + ','.join(uuid(rng) for _ in range(rng.randrange(1, 3))) + ']')
|
||||
if rng.random() < 0.2:
|
||||
fields.append(f'cooldown_ends_at:{now + rng.choice([-50, 0, 30, 100, 300])}L')
|
||||
if rng.random() < 0.2:
|
||||
fields.append(f'next_mob_spawns_at:{now + rng.choice([-5, 0, 10, 60])}L')
|
||||
if rng.random() < 0.15:
|
||||
fields.append(f'total_mobs_spawned:{rng.choice([0, 1, 3, 6, 20])}')
|
||||
if rng.random() < 0.15:
|
||||
fields.append(f'spawn_data:{{entity:{{id:"minecraft:{rng.choice(MOBS)}"}}}}')
|
||||
if rng.random() < 0.08:
|
||||
fields.append(f'ejecting_loot_table:"{rng.choice(TABLES)}"')
|
||||
return '{' + ','.join(fields) + '}'
|
||||
|
||||
|
||||
def room(rng):
|
||||
"""A trial chamber hall around the spawner; returns (world, spawner position)."""
|
||||
w = natural.World(rng)
|
||||
w.dim = 'minecraft:overworld'
|
||||
w.kv['dim'] = w.dim
|
||||
w.kv['biome'] = rng.choice(['minecraft:plains', 'minecraft:dripstone_caves', 'minecraft:deep_dark', 'minecraft:lush_caves'])
|
||||
sx, sy, sz = rng.randrange(-8, 9), rng.randrange(-40, 20), rng.randrange(-8, 9)
|
||||
w.surface = sy
|
||||
half, height = rng.choice([4, 5, 6, 8]), rng.choice([4, 5, 7])
|
||||
w.block(box(sx - 24, sy - 6, sz - 24, sx + 24, sy + 12, sz + 24), rng.choice(['minecraft:tuff_bricks', 'minecraft:stone']))
|
||||
w.block(box(sx - half, sy - 1, sz - half, sx + half, sy - 1, sz + half), rng.choice(['minecraft:chiseled_tuff', 'minecraft:waxed_copper_block']))
|
||||
w.block(box(sx - half, sy, sz - half, sx + half, sy + height - 1, sz + half), 'minecraft:air')
|
||||
if rng.random() < 0.3:
|
||||
# A corridor out of the hall, past the range.
|
||||
w.block(box(sx + half, sy, sz - 1, sx + 22, sy + 2, sz + 1), 'minecraft:air')
|
||||
for _ in range(rng.choice([0, 0, 1, 3, 6])):
|
||||
px, pz = sx + rng.randrange(-half, half + 1), sz + rng.randrange(-half, half + 1)
|
||||
if (px, pz) != (sx, sz):
|
||||
w.block(box(px, sy, pz, px, sy + rng.randrange(0, height), pz),
|
||||
rng.choice(['minecraft:tuff_bricks', 'minecraft:glass', 'minecraft:iron_bars', 'minecraft:oak_slab', 'minecraft:copper_grate']))
|
||||
w.light(box(sx - 24, sy - 2, sz - 24, sx + 24, sy + 12, sz + 24), 0, rng.choice([0, 0, 4, 8, 15]))
|
||||
return w, (sx, sy, sz), half, height
|
||||
|
||||
|
||||
def players(w, rng, spos, half, height):
|
||||
for _ in range(rng.choice([0, 1, 1, 1, 2, 3])):
|
||||
r = rng.random()
|
||||
if r < 0.75:
|
||||
x, y, z = spos[0] + rng.uniform(-half, half + 1), spos[1] + rng.choice([0, 0, 0, 1, height - 2]), spos[2] + rng.uniform(-half, half + 1)
|
||||
else:
|
||||
x, y, z = spos[0] + rng.uniform(-20, 21), spos[1] + rng.choice([0, 0, -8, 10]), spos[2] + rng.uniform(-20, 21)
|
||||
mode = rng.choice(['survival'] * 7 + ['creative', 'adventure', 'spectator'])
|
||||
w.players.append(f'{x:.3f},{y:.3f},{z:.3f}/{mode}')
|
||||
|
||||
|
||||
def corpus():
|
||||
rng = random.Random(0x54524941)
|
||||
cases = []
|
||||
for k in range(2500):
|
||||
w, spos, half, height = room(rng)
|
||||
players(w, rng, spos, half, height)
|
||||
natural.common(w, rng, rng.randrange(-2**47, 2**47))
|
||||
w.kv.pop('unloaded', None)
|
||||
w.kv.pop('respawn', None)
|
||||
if rng.random() < 0.05:
|
||||
w.kv['spawners'] = 0
|
||||
if rng.random() < 0.05:
|
||||
w.kv['rules'] = 0
|
||||
t0 = rng.choice([0, 1, 19, 1000, rng.randrange(0, 10**6), rng.randrange(10**9, 10**12)])
|
||||
w.kv['spos'] = f'{spos[0]},{spos[1]},{spos[2]}'
|
||||
w.kv['state'] = rng.choices(STATES, [2, 6, 4, 1, 1, 1])[0]
|
||||
w.kv['snbt'] = base64.b64encode(trial_snbt(rng, t0).encode()).decode()
|
||||
w.kv['t0'] = t0
|
||||
w.kv['ticks'] = rng.choice([1, 2, 20, 41, 100, 200, 400, 600])
|
||||
w.kv['kill'] = rng.choice([0, 1, 7, 20, 60, 60])
|
||||
cases.append(f'trial/{k} mode=trial {w.tokens()}')
|
||||
return cases
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--prepare', action='store_true')
|
||||
args = parser.parse_args()
|
||||
build = lab.LOCAL / 'rust-trial-spawner-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
if args.prepare:
|
||||
lab.prepare()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
resources = lab.LOCAL / 'horizon-client/26.3'
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java'
|
||||
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/mobs/trial_spawner.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs']
|
||||
tested = base.source_hashes(sources)
|
||||
inputs = build / 'inputs.txt'
|
||||
cases = corpus()
|
||||
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
deps = os.pathsep.join(map(str, libraries))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
|
||||
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
|
||||
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
|
||||
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
|
||||
'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server')
|
||||
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust')
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture'
|
||||
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
|
||||
vanilla = (build / 'server.txt').read_text().splitlines()
|
||||
errors = [l for l in vanilla if ' error ' in l]
|
||||
if errors:
|
||||
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
|
||||
rust = (build / 'rust.txt').read_text().splitlines()
|
||||
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
|
||||
if bad or len(vanilla) != len(rust):
|
||||
report = '\n'.join(f' vanilla {a[:2000]}\n rust {b[:2000]}' for a, b in bad[:12])
|
||||
raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}')
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
count = lambda text: sum(line.count(text) for line in vanilla)
|
||||
stats = {'spawns': count(' spawn minecraft:'), 'items': count(' item minecraft:'), 'states': count(' state '),
|
||||
'detections': count(' levent 3013 '), 'rewards': count(' levent 3014 '), 'kills': count(' kill ')}
|
||||
for state in STATES:
|
||||
stats[f'reached_{state}'] = sum(f' state {state} ' in line for line in vanilla)
|
||||
lab.write_json(build / 'report.json', {
|
||||
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
|
||||
**stats, 'sources_sha256': tested,
|
||||
'scope': 'TrialSpawner: load (state data, FullConfig with registry and inline configs), tickServer (mob '
|
||||
'tracking), TrialSpawnerState.tickAndGetNext for every state (display entity, canSpawnInLevel, '
|
||||
'tryDetectPlayers with line of sight, waves and their targets per player, spawnMob with its '
|
||||
'collision, line of sight, spawn rules, yaw and obstruction checks, next spawn data, reward '
|
||||
'ejection with the loot tables and spawnItem, shutter sounds, cooldown) with every level random '
|
||||
'draw. finalizeSpawn runs with a fixed random in the oracle; its own outcomes are not compared.'})
|
||||
print(f'{len(cases):,} trial spawner cases match vanilla (' + ', '.join(f'{v:,} {k}' for k, v in stats.items()) + ')')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user