Merge pull request #80 from ludovic111/fix/composters-70
Composters take compostable items by hand, from hoppers and from droppers
This commit is contained in:
@@ -19,6 +19,7 @@ mod chat;
|
||||
mod combat;
|
||||
mod command_harness;
|
||||
mod commands;
|
||||
mod composter;
|
||||
mod control;
|
||||
mod copper_golems;
|
||||
mod creaking;
|
||||
@@ -1551,6 +1552,11 @@ impl Game<'_> {
|
||||
data,
|
||||
} => self.sculk_charge_event(pos, data),
|
||||
LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos),
|
||||
LevelEvent::LevelEvent {
|
||||
id: 1500,
|
||||
pos,
|
||||
data,
|
||||
} => self.composter_fill_event(pos, data == 1),
|
||||
LevelEvent::LevelEvent { id, pos, .. } => {
|
||||
let c = Some([
|
||||
f64::from(pos.x) + 0.5,
|
||||
@@ -2023,6 +2029,10 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
return Ok(());
|
||||
}
|
||||
if self.use_composter(hit.pos, held.as_ref()) {
|
||||
self.swing_arm();
|
||||
return Ok(());
|
||||
}
|
||||
let face = match hit.face {
|
||||
[0, 1, 0] => Direction::Up,
|
||||
[0, -1, 0] => Direction::Down,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Command execution (the `execute` side of each vanilla command class):
|
||||
//! entity selectors resolved against the game, vanilla feedback and errors.
|
||||
mod compute;
|
||||
pub(super) mod compute;
|
||||
mod data;
|
||||
mod effects;
|
||||
pub(super) mod execute;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! `ComposterBlock`: compostable items go in by hand (`useItemOn`) or
|
||||
//! through its input container (hoppers, droppers, crafters above), and the
|
||||
//! fill feedback of level event 1500 (`handleFill`). Emptying a full
|
||||
//! composter by hand is `useWithoutItem` in horizon-world.
|
||||
use super::{Game, commands::compute::ComputeContext};
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
|
||||
impl Game<'_> {
|
||||
/// The composter's `level` at `pos`, None when it isn't a composter.
|
||||
pub(super) fn composter_level(&self, pos: [i32; 3]) -> Option<i32> {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let s = self.res.assets.registry.state(state)?;
|
||||
if &*s.name != "minecraft:composter" {
|
||||
return None;
|
||||
}
|
||||
s.properties.get("level")?.parse().ok()
|
||||
}
|
||||
/// The item's `compostable` layers provider.
|
||||
fn compostable(&self, stack: &ItemStack) -> Option<serde_json::Value> {
|
||||
self.res.items.get(&stack.item)?.compostable.clone()
|
||||
}
|
||||
/// `ComposterBlock.addLayer` and level event 1500: the provider is
|
||||
/// evaluated in the composter's block-interaction loot context (its
|
||||
/// state; the level random), then the layer is added. True when it was.
|
||||
fn composter_add(&mut self, pos: [i32; 3], layers: &serde_json::Value) -> bool {
|
||||
let context = ComputeContext {
|
||||
block: Some(pos),
|
||||
target: None,
|
||||
};
|
||||
let layers = self.provider_int(layers, &context, 0).unwrap_or(0);
|
||||
let before = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let at = BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
let after = self.with_level(|b, level, ticks| b.composter_insert(level, ticks, at, layers));
|
||||
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
|
||||
// The game event and level event 1500 happen here, before the caller goes on.
|
||||
let _ = self.process_level_events();
|
||||
after != before
|
||||
}
|
||||
/// `ComposterBlock.useItemOn` with the main-hand stack: true when it
|
||||
/// consumed the action (SUCCESS; a full composter falls through to
|
||||
/// `useWithoutItem`, which empties it).
|
||||
pub(super) fn use_composter(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool {
|
||||
let Some(level) = self.composter_level(pos) else {
|
||||
return false;
|
||||
};
|
||||
let Some(stack) = held else {
|
||||
return false;
|
||||
};
|
||||
let Some(layers) = self.compostable(stack) else {
|
||||
return false;
|
||||
};
|
||||
if level >= 8 {
|
||||
return false;
|
||||
}
|
||||
if level < 7 {
|
||||
self.composter_add(pos, &layers);
|
||||
self.stats.add("used", &stack.item, 1);
|
||||
self.consume_held();
|
||||
}
|
||||
// ServerPlayerGameMode.useItemOn: the action was consumed.
|
||||
self.trigger_block("minecraft:item_used_on_block", pos, stack);
|
||||
true
|
||||
}
|
||||
/// `HopperBlockEntity.addItem` into the composter's `InputContainer`
|
||||
/// (levels 0 to 6; one item, compostable, from above): the remainder.
|
||||
pub(super) fn composter_container_insert(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
mut stack: ItemStack,
|
||||
from_above: bool,
|
||||
) -> Option<ItemStack> {
|
||||
let level = self.composter_level(pos)?;
|
||||
if !from_above || level >= 7 {
|
||||
return Some(stack);
|
||||
}
|
||||
let Some(layers) = self.compostable(&stack) else {
|
||||
return Some(stack);
|
||||
};
|
||||
// InputContainer.getMaxStackSize is 1: one item goes in, and its
|
||||
// setChanged composts it at once.
|
||||
stack.count -= 1;
|
||||
self.composter_add(pos, &layers);
|
||||
(stack.count > 0).then_some(stack)
|
||||
}
|
||||
/// `ComposterBlock.handleFill` (level event 1500) on the client: the
|
||||
/// fill sound and ten composter particles above the compost.
|
||||
pub(super) fn composter_fill_event(&mut self, pos: BlockPos, success: bool) {
|
||||
let center = [
|
||||
f64::from(pos.x) + 0.5,
|
||||
f64::from(pos.y) + 0.5,
|
||||
f64::from(pos.z) + 0.5,
|
||||
];
|
||||
let sound = if success {
|
||||
"minecraft:block.composter.fill_success"
|
||||
} else {
|
||||
"minecraft:block.composter.fill"
|
||||
};
|
||||
self.audio.play(sound, Some(center), 1.0, 1.0);
|
||||
// getShape(..).max(Y, 0.5, 0.5): the compost surface (SHAPES[8] = SHAPES[7]).
|
||||
let level = self.composter_level([pos.x, pos.y, pos.z]).unwrap_or(0);
|
||||
let height = f64::from((1 + level.min(7) * 2).clamp(2, 16)) / 16.0 + 0.03125;
|
||||
let options = ParticleOptions::simple(ParticleType::Composter);
|
||||
for _ in 0..10 {
|
||||
let r = self.particles.random();
|
||||
let v = [
|
||||
r.next_gaussian() * 0.02,
|
||||
r.next_gaussian() * 0.02,
|
||||
r.next_gaussian() * 0.02,
|
||||
];
|
||||
let p = [
|
||||
f64::from(pos.x) + 0.1875 + 0.625 * f64::from(r.next_float()),
|
||||
f64::from(pos.y) + height + f64::from(r.next_float()) * (1.0 - height),
|
||||
f64::from(pos.z) + 0.1875 + 0.625 * f64::from(r.next_float()),
|
||||
];
|
||||
self.particles.add(&options, p, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,8 @@ impl Game<'_> {
|
||||
self.level_events.clear();
|
||||
self.orbs.clear();
|
||||
self.falling.clear();
|
||||
// Hopper cooldowns of an earlier case.
|
||||
self.hoppers.clear();
|
||||
self.ui.rules = Default::default();
|
||||
// The oracle level plays on normal difficulty.
|
||||
self.ui.difficulty = 2;
|
||||
@@ -260,8 +262,15 @@ impl Game<'_> {
|
||||
pos[2].as_i64().unwrap_or(0) as i32,
|
||||
);
|
||||
let state = self.world.block(origin.x, origin.y, origin.z);
|
||||
let mut used = Vec::new();
|
||||
if let Some(op) = case.get("remove") {
|
||||
self.fixture_remove(origin, op)?;
|
||||
} else if let Some(op) = case.get("use") {
|
||||
used = self.fixture_use(origin, op)?;
|
||||
} else if case.get("hopper").is_some() {
|
||||
// HopperBlockEntity.pushItemsTick, once.
|
||||
self.hopper_try_move_items((origin.x, origin.y, origin.z));
|
||||
self.process_level_events()?;
|
||||
} else {
|
||||
self.dispense_from(origin, state)?;
|
||||
// CrafterBlockEntity.serverTick, the crafting animation running down.
|
||||
@@ -335,10 +344,64 @@ impl Game<'_> {
|
||||
for (sound, at, _, _) in self.audio.capture.take().unwrap_or_default() {
|
||||
out.push(format!("S {} {sound}", floor_pos(at)));
|
||||
}
|
||||
out.extend(used);
|
||||
out.push(format!("rng {}", self.world.random.next_long()));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A player holding the case's item right-clicks the block at `pos`
|
||||
/// (`use_item_as_player`'s block steps): the statistics, the result
|
||||
/// and the held stack, as `VanillaDispenserOracle.use` prints them.
|
||||
fn fixture_use(&mut self, pos: BlockPos, op: &Value) -> Result<Vec<String>> {
|
||||
let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
|
||||
self.creative = op["creative"].as_bool().unwrap_or(false);
|
||||
self.inventory[self.selected] = stack.clone();
|
||||
let used_before = stack
|
||||
.as_ref()
|
||||
.map_or(0, |s| self.stats.get("used", &s.item));
|
||||
let at = [pos.x, pos.y, pos.z];
|
||||
let mut consumed = self.use_composter(at, stack.as_ref());
|
||||
if !consumed {
|
||||
let player = horizon_world::level::PlayerContext {
|
||||
yaw: 0.0,
|
||||
pitch: 90.0,
|
||||
may_build: true,
|
||||
can_eat: self.creative,
|
||||
game_master: false,
|
||||
};
|
||||
let hit = horizon_core::geometry::Vec3::new(
|
||||
f64::from(pos.x) + 0.5,
|
||||
f64::from(pos.y) + 1.0,
|
||||
f64::from(pos.z) + 0.5,
|
||||
);
|
||||
let result = self.with_level(|b, level, ticks| {
|
||||
b.use_without_item(
|
||||
level,
|
||||
ticks,
|
||||
pos,
|
||||
horizon_core::geometry::Direction::Up,
|
||||
hit,
|
||||
player,
|
||||
)
|
||||
});
|
||||
consumed = result.consumes_action();
|
||||
}
|
||||
self.process_level_events()?;
|
||||
let mut out = Vec::new();
|
||||
if let Some(s) = &stack {
|
||||
let used = self.stats.get("used", &s.item) - used_before;
|
||||
if used != 0 {
|
||||
out.push(format!("stat {} minecraft:used {used}", s.item));
|
||||
}
|
||||
}
|
||||
out.push(format!(
|
||||
"use {} held {}",
|
||||
if consumed { "consumed" } else { "pass" },
|
||||
canon_stack(self.inventory[self.selected].as_ref())
|
||||
));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A stack in a block entity's slot: a container's, a jukebox's record, a
|
||||
/// lectern's book, or the items of a block entity Horizon keeps as saved.
|
||||
fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
|
||||
|
||||
@@ -41,6 +41,9 @@ enum Kind {
|
||||
Crafter,
|
||||
/// `BrewingStandBlockEntity` (a `WorldlyContainer`).
|
||||
Brewing,
|
||||
/// `ComposterBlock.getContainer` at this level (a `WorldlyContainerHolder`
|
||||
/// without a block entity): input below 7, empty at 7, bone meal at 8.
|
||||
Composter(i32),
|
||||
}
|
||||
|
||||
/// A container: one block entity, or a double chest (`CompoundContainer`).
|
||||
@@ -71,6 +74,9 @@ impl View {
|
||||
(Kind::Brewing, Some(Direction::Up)) => vec![3],
|
||||
(Kind::Brewing, Some(Direction::Down)) => vec![0, 1, 2, 3],
|
||||
(Kind::Brewing, Some(_)) => vec![0, 1, 2, 4],
|
||||
(Kind::Composter(8), Some(Direction::Down)) => vec![0],
|
||||
(Kind::Composter(level), Some(Direction::Up)) if level < 7 => vec![0],
|
||||
(Kind::Composter(_), _) => vec![],
|
||||
_ => (0..self.len()).collect(),
|
||||
}
|
||||
}
|
||||
@@ -119,6 +125,8 @@ struct Containers<'a> {
|
||||
registry: &'static horizon_world::registry::BlockRegistry,
|
||||
/// Brewing recipes, for what a brewing stand accepts (not needed for signals).
|
||||
brewing: Option<&'a horizon_client::brewing::Brewing>,
|
||||
/// The stack of a full composter's `OutputContainer`.
|
||||
bone_meal: ItemStack,
|
||||
}
|
||||
impl Containers<'_> {
|
||||
fn prop(&self, state: BlockStateId, key: &str) -> Option<&str> {
|
||||
@@ -141,9 +149,16 @@ impl Containers<'_> {
|
||||
/// first). `blocked_chests`: `ChestBlock.getContainer(.., false)` returns
|
||||
/// nothing for a chest under a redstone conductor.
|
||||
fn view(&self, pos: Pos, blocked_chests: bool) -> Option<View> {
|
||||
let entity = self.world.block_entities.get(&pos)?;
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let name = self.name(state);
|
||||
if name == "minecraft:composter" {
|
||||
let level = self.prop(state, "level").and_then(|l| l.parse().ok())?;
|
||||
return Some(View {
|
||||
parts: vec![(pos, usize::from(level != 7))],
|
||||
kind: Kind::Composter(level),
|
||||
});
|
||||
}
|
||||
let entity = self.world.block_entities.get(&pos)?;
|
||||
let kind = match (entity, name) {
|
||||
(BlockEntity::Furnace(_), _) => Kind::Furnace,
|
||||
(BlockEntity::Crafter(_), _) => Kind::Crafter,
|
||||
@@ -202,6 +217,10 @@ impl Containers<'_> {
|
||||
})
|
||||
}
|
||||
fn get(&self, view: &View, slot: usize) -> Option<&ItemStack> {
|
||||
if let Kind::Composter(level) = view.kind {
|
||||
// OutputContainer holds one bone meal; InputContainer composts at once.
|
||||
return (level == 8 && slot == 0).then_some(&self.bone_meal);
|
||||
}
|
||||
let (pos, i) = view.locate(slot)?;
|
||||
self.world
|
||||
.block_entities
|
||||
@@ -264,6 +283,10 @@ impl Containers<'_> {
|
||||
}
|
||||
/// `canTakeItemThroughFace` (furnaces and brewing stands restrict it).
|
||||
fn can_take(&self, view: &View, slot: usize, stack: &ItemStack, face: Direction) -> bool {
|
||||
if let Kind::Composter(level) = view.kind {
|
||||
// OutputContainer.canTakeItemThroughFace.
|
||||
return level == 8 && face == Direction::Down && &*stack.item == "minecraft:bone_meal";
|
||||
}
|
||||
if view.kind == Kind::Brewing {
|
||||
return slot != 3 || &*stack.item == "minecraft:glass_bottle";
|
||||
}
|
||||
@@ -300,6 +323,15 @@ impl Containers<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn bone_meal() -> ItemStack {
|
||||
ItemStack {
|
||||
item: "minecraft:bone_meal".into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Comparator input from a container block entity (0 when there is none).
|
||||
pub(super) fn container_signal(
|
||||
world: &World,
|
||||
@@ -314,8 +346,10 @@ pub(super) fn container_signal(
|
||||
items,
|
||||
registry,
|
||||
brewing: None,
|
||||
bone_meal: bone_meal(),
|
||||
};
|
||||
c.view((pos.x, pos.y, pos.z), true)
|
||||
.filter(|v| !matches!(v.kind, Kind::Composter(_)))
|
||||
.map_or(0, |v| c.signal(&v))
|
||||
}
|
||||
|
||||
@@ -327,6 +361,7 @@ impl Game<'_> {
|
||||
items: &self.res.items,
|
||||
registry: self.res.assets.registry,
|
||||
brewing: Some(&self.res.stations.brewing),
|
||||
bone_meal: bone_meal(),
|
||||
}
|
||||
}
|
||||
fn slot_mut_at(&mut self, view: &View, slot: usize) -> Option<&mut Option<ItemStack>> {
|
||||
@@ -339,6 +374,10 @@ impl Game<'_> {
|
||||
}
|
||||
/// `BlockEntity.setChanged` for every block entity of a container.
|
||||
fn view_changed(&mut self, view: &View) {
|
||||
// A composter's containers change its block state instead.
|
||||
if let Kind::Composter(_) = view.kind {
|
||||
return;
|
||||
}
|
||||
for &(pos, _) in &view.parts {
|
||||
self.container_changed(pos);
|
||||
}
|
||||
@@ -415,6 +454,10 @@ impl Game<'_> {
|
||||
stack: ItemStack,
|
||||
face: Option<Direction>,
|
||||
) -> Option<ItemStack> {
|
||||
if let Kind::Composter(_) = view.kind {
|
||||
let (x, y, z) = view.parts[0].0;
|
||||
return self.composter_container_insert([x, y, z], stack, face == Some(Direction::Up));
|
||||
}
|
||||
let slots = if matches!(view.kind, Kind::Furnace | Kind::Brewing) && face.is_some() {
|
||||
view.slots_for_face(face)
|
||||
} else {
|
||||
@@ -482,7 +525,7 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
/// `HopperBlockEntity.tryMoveItems` with `suckInItems`.
|
||||
fn hopper_try_move_items(&mut self, pos: Pos) {
|
||||
pub(super) fn hopper_try_move_items(&mut self, pos: Pos) {
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let c = self.containers();
|
||||
let enabled = c.prop(state, "enabled") != Some("false");
|
||||
@@ -540,6 +583,23 @@ impl Game<'_> {
|
||||
let above = (pos.0, pos.1 + 1, pos.2);
|
||||
let c = self.containers();
|
||||
if let Some(source) = c.view(above, false) {
|
||||
if let Kind::Composter(level) = source.kind {
|
||||
if level != 8 {
|
||||
return false;
|
||||
}
|
||||
// tryTakeInItemFromSlot on the OutputContainer: removeItem calls
|
||||
// its setChanged, which empties the composter, and so does the
|
||||
// second setChanged after the move or, when the hopper has no
|
||||
// room, the setItem putting the bone meal back into the detached
|
||||
// container (whose bone meal is lost with it).
|
||||
let bone_meal = c.bone_meal.clone();
|
||||
let at = BlockPos::new(above.0, above.1, above.2);
|
||||
self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at));
|
||||
let moved = self.add_item(None, hopper, bone_meal, None).is_none();
|
||||
self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at));
|
||||
self.world.modified.insert((above.0 >> 4, above.2 >> 4));
|
||||
return moved;
|
||||
}
|
||||
let source_hopper = (source.kind == Kind::Hopper).then_some(above);
|
||||
for slot in source.slots_for_face(Some(Direction::Down)) {
|
||||
let c = self.containers();
|
||||
|
||||
@@ -35,6 +35,8 @@ pub struct ItemInfo {
|
||||
pub fuel: Option<(Value, Value)>,
|
||||
/// `brewing_fuel`: uses and speed-multiplier provider references.
|
||||
pub brewing_fuel: Option<(Value, Value)>,
|
||||
/// `compostable.layers`: the layers provider (`ComposterBlock.addLayer`).
|
||||
pub compostable: Option<Value>,
|
||||
/// Item left behind after crafting/fuel use (e.g. bucket).
|
||||
pub remainder: Option<String>,
|
||||
/// `equippable.slot` (head, chest, legs, feet, ...).
|
||||
@@ -442,6 +444,7 @@ impl Items {
|
||||
brewing_fuel: c
|
||||
.get("minecraft:brewing_fuel")
|
||||
.map(|f| (f["uses"].clone(), f["speed_multiplier"].clone())),
|
||||
compostable: c.get("minecraft:compostable").map(|f| f["layers"].clone()),
|
||||
remainder: c["minecraft:use_remainder"]["id"]
|
||||
.as_str()
|
||||
.or(c["minecraft:crafting_remainder"]["id"].as_str())
|
||||
|
||||
@@ -435,6 +435,25 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
InteractionResult::Success
|
||||
}
|
||||
|
||||
/// `ComposterBlock.addLayer` once its `compostable` provider gave
|
||||
/// `layers`: the new state (the old one when no layer is added).
|
||||
fn composter_add_layer(&mut self, pos: BlockPos, layers: i32) -> BlockStateId {
|
||||
let b = self.b;
|
||||
let state = self.state(pos);
|
||||
if layers <= 0 {
|
||||
return state;
|
||||
}
|
||||
let level = b.table.int(state, b.props.level);
|
||||
let next_level = (level + layers).clamp(0, 7);
|
||||
let next = b.table.set_int(state, b.props.level, next_level);
|
||||
self.set_block_and_update(pos, next);
|
||||
self.game_event_state(pos, "minecraft:block_change", next);
|
||||
if next_level == 7 {
|
||||
self.schedule_tick(pos, b.block(state), 20);
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
/// `DragonEggBlock.teleport`.
|
||||
fn dragon_egg_teleport(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
let b = self.b;
|
||||
@@ -462,6 +481,38 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
}
|
||||
|
||||
impl Behaviours {
|
||||
/// `ComposterBlock.addLayer` at `pos` with the layers its item's
|
||||
/// `compostable` provider gave, followed by level event 1500 (fill
|
||||
/// particles and sound; data 1 when a layer was added) as every caller
|
||||
/// does: `useItemOn` and the hopper input container. The new state.
|
||||
pub fn composter_insert<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
pos: BlockPos,
|
||||
layers: i32,
|
||||
) -> BlockStateId {
|
||||
let mut sim = self.sim(level, ticks);
|
||||
let state = sim.state(pos);
|
||||
let next = sim.composter_add_layer(pos, layers);
|
||||
sim.level_event(1500, pos, i32::from(next != state));
|
||||
next
|
||||
}
|
||||
|
||||
/// `ComposterBlock.empty`: the hopper output container took the bone meal.
|
||||
pub fn composter_empty<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
pos: BlockPos,
|
||||
) {
|
||||
let mut sim = self.sim(level, ticks);
|
||||
let state = sim.state(pos);
|
||||
let next = self.table.set_int(state, self.props.level, 0);
|
||||
sim.set_block_and_update(pos, next);
|
||||
sim.game_event_state(pos, "minecraft:block_change", next);
|
||||
}
|
||||
|
||||
/// `BlockState.useWithoutItem` for a right-click on `pos` (hit face and
|
||||
/// absolute hit location as in `BlockHitResult`).
|
||||
pub fn use_without_item<L: LevelAccess + ?Sized>(
|
||||
|
||||
@@ -432,6 +432,11 @@ public final class VanillaBlockUpdateOracle {
|
||||
world.emit("D " + id.identifier());
|
||||
return delegate != null ? delegate.getLootTable(id) : net.minecraft.world.level.storage.loot.LootTable.EMPTY;
|
||||
}
|
||||
/** The registries loot contexts resolve providers in (a composter's compostable layers). */
|
||||
@Override
|
||||
public net.minecraft.core.HolderLookup.Provider lookup() {
|
||||
return delegate != null ? delegate.lookup() : ParityData.lookup;
|
||||
}
|
||||
}
|
||||
|
||||
static final class Server extends net.minecraft.server.MinecraftServer {
|
||||
|
||||
@@ -51,6 +51,7 @@ public final class VanillaDispenserOracle {
|
||||
case 1051 -> "minecraft:entity.wind_charge.throw";
|
||||
case 1505 -> "minecraft:item.bone_meal.use";
|
||||
case 1501 -> "minecraft:block.lava.extinguish";
|
||||
case 1500 -> data == 1 ? "minecraft:block.composter.fill_success" : "minecraft:block.composter.fill";
|
||||
case 1009 -> data == 0 ? "minecraft:block.fire.extinguish" : data == 1 ? "minecraft:block.generic.extinguish_fire" : null;
|
||||
case 2001 -> {
|
||||
BlockState state = Block.stateById(data);
|
||||
@@ -289,8 +290,15 @@ public final class VanillaDispenserOracle {
|
||||
List<Entity> targets = List.copyOf(w.entities);
|
||||
BlockPos origin = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("pos"));
|
||||
BlockState state = w.getBlockState(origin);
|
||||
List<String> used = new ArrayList<>();
|
||||
if (f.has("remove")) {
|
||||
remove(w, origin, f.getAsJsonObject("remove"));
|
||||
} else if (f.has("use")) {
|
||||
used = use(w, origin, f.getAsJsonObject("use"));
|
||||
} else if (f.has("hopper")) {
|
||||
// HopperBlockEntity.pushItemsTick, once.
|
||||
var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin);
|
||||
net.minecraft.world.level.block.entity.HopperBlockEntity.pushItemsTick(w, origin, state, hopper);
|
||||
} else if (state.getBlock() instanceof CrafterBlock) {
|
||||
Method craft = CrafterBlock.class.getDeclaredMethod("dispenseFrom", BlockState.class, ServerLevel.class, BlockPos.class);
|
||||
craft.setAccessible(true);
|
||||
@@ -348,9 +356,60 @@ public final class VanillaDispenserOracle {
|
||||
}
|
||||
}
|
||||
result.addAll(w.blockEvents);
|
||||
result.addAll(used);
|
||||
result.add("rng " + w.rng.nextLong());
|
||||
}
|
||||
|
||||
/** The player of a "use" case: its main hand, game mode and the statistics it is awarded. */
|
||||
static final class User extends net.minecraft.server.level.ServerPlayer {
|
||||
VanillaBlockUpdateOracle.World world;
|
||||
boolean creative;
|
||||
ItemStack hand;
|
||||
List<String> stats;
|
||||
User() {
|
||||
super(null, null, null, null);
|
||||
}
|
||||
@Override public ServerLevel level() { return world; }
|
||||
@Override public boolean hasInfiniteMaterials() { return creative; }
|
||||
@Override public boolean isCreative() { return creative; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
@Override public EntityType<?> getType() { return EntityTypes.PLAYER; }
|
||||
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); }
|
||||
@Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) {
|
||||
return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY;
|
||||
}
|
||||
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) {
|
||||
stats.add("stat " + key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count);
|
||||
}
|
||||
static <T> String key(net.minecraft.stats.Stat<T> stat) {
|
||||
return String.valueOf(stat.getType().getRegistry().getKey(stat.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ServerPlayerGameMode.useItemOn by a player holding the case's item on the
|
||||
* block at `pos` (not sneaking): `useItemOn`, then `useWithoutItem` when the
|
||||
* block asks to try with an empty hand. The held stack and statistics follow.
|
||||
*/
|
||||
static List<String> use(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception {
|
||||
User player = (User) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, User.class);
|
||||
player.world = w;
|
||||
player.creative = use.has("creative") && use.get("creative").getAsBoolean();
|
||||
player.hand = stack(use.get("item").getAsString());
|
||||
player.stats = new ArrayList<>();
|
||||
var hit = new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(pos).add(0, 0.5, 0),
|
||||
net.minecraft.core.Direction.UP, pos, false);
|
||||
BlockState state = w.getBlockState(pos);
|
||||
var hand = net.minecraft.world.InteractionHand.MAIN_HAND;
|
||||
var result = state.useItemOn(player.getItemInHand(hand), w, player, hand, hit);
|
||||
if (result instanceof net.minecraft.world.InteractionResult.TryEmptyHandInteraction) {
|
||||
result = state.useWithoutItem(w, player, hit);
|
||||
}
|
||||
List<String> out = new ArrayList<>(player.stats);
|
||||
out.add("use " + (result.consumesAction() ? "consumed" : "pass") + " held " + ParityData.canon(player.hand));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The level's block entity positions by x, y, z. */
|
||||
static List<BlockPos> sortedEntities(VanillaBlockUpdateOracle.World w) {
|
||||
List<BlockPos> out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare vanilla composters with Horizon's: by hand, through hoppers and from droppers.
|
||||
|
||||
Every case has a composter at a random level and runs one action over the
|
||||
headless level of the dispenser harness (`VanillaDispenserOracle` against
|
||||
`HORIZON_DISPENSE_FIXTURE`):
|
||||
|
||||
- `use`: a player (survival or creative) right-clicks the composter holding a
|
||||
compostable item, another item or nothing (`ComposterBlock.useItemOn`, then
|
||||
`useWithoutItem`, which empties a full composter);
|
||||
- `hopper` above: a hopper facing down (or past it) pushes its items into the
|
||||
composter's input container;
|
||||
- `hopper` below: a hopper under the composter pulls the bone meal out of its
|
||||
output container (nothing from the other levels);
|
||||
- `dispense`: a dropper facing the composter puts one item in from above, or
|
||||
is refused from the side.
|
||||
|
||||
Both sides print block changes, container contents, spawned items, level
|
||||
events with the sounds the client plays for them, sounds, game events, the
|
||||
player's statistics and held stack, and the level random afterwards (the
|
||||
compostable providers draw from it).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
try:
|
||||
from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base
|
||||
except ImportError:
|
||||
import block_update_harness as h
|
||||
import lab
|
||||
import test_dispenser_parity as d
|
||||
import test_rust_parity as base
|
||||
|
||||
OTHERS = ['stick', 'stone', 'bone_meal', 'diamond_sword', 'water_bucket', 'cobblestone', 'egg']
|
||||
SIDES = ['north', 'south', 'west', 'east']
|
||||
|
||||
|
||||
def stack(rng, items, compostable, others_odds=0.25):
|
||||
if rng.random() < others_odds:
|
||||
name = rng.choice(OTHERS)
|
||||
else:
|
||||
name = rng.choice(compostable)
|
||||
top = items['minecraft:' + name].get('minecraft:max_stack_size', 64)
|
||||
return d.plain(name, min(top, rng.choice([1, 1, 2, 16, 64])))
|
||||
|
||||
|
||||
def composter(states, rng):
|
||||
level = rng.choice([0, 0, 1, 3, 5, 6, 6, 7, 8, 8])
|
||||
return states.get('composter', level=str(level))
|
||||
|
||||
|
||||
def cases(facts, items, count, seed):
|
||||
rng = random.Random(seed)
|
||||
states = d.States(facts)
|
||||
compostable = sorted(k.split(':')[1] for k, v in items.items() if 'minecraft:compostable' in v)
|
||||
modes = ['use', 'use', 'hopper_in', 'hopper_out', 'dispense']
|
||||
for n in range(count):
|
||||
mode = modes[n % len(modes)]
|
||||
case = {**h.environment(rng), 'pos': [0, 0, 0]}
|
||||
case.pop('raining', None)
|
||||
case.pop('thundering', None)
|
||||
cells = []
|
||||
items_in = []
|
||||
if mode == 'use':
|
||||
cells.append([0, 0, 0, composter(states, rng)])
|
||||
held = '-' if rng.random() < 0.1 else stack(rng, items, compostable)
|
||||
case['use'] = {'item': held, 'creative': rng.random() < 0.2}
|
||||
elif mode == 'hopper_in':
|
||||
facing = 'down' if rng.random() < 0.8 else rng.choice(SIDES)
|
||||
cells.append([0, 0, 0, states.get('hopper', facing=facing, enabled='true')])
|
||||
target = {'down': (0, -1, 0), 'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)}[facing]
|
||||
cells.append([*target, composter(states, rng)])
|
||||
for slot in rng.sample(range(5), rng.choice([1, 1, 2, 3, 5])):
|
||||
items_in.append([0, 0, 0, slot, stack(rng, items, compostable, 0.4)])
|
||||
case['hopper'] = True
|
||||
elif mode == 'hopper_out':
|
||||
facing = rng.choice(['down', 'down'] + SIDES)
|
||||
cells.append([0, 0, 0, states.get('hopper', facing=facing, enabled='true')])
|
||||
level = 8 if rng.random() < 0.7 else rng.choice([0, 3, 7])
|
||||
cells.append([0, 1, 0, states.get('composter', level=str(level))])
|
||||
roll = rng.random()
|
||||
if roll < 0.3:
|
||||
# Full of something else: the bone meal can't go in.
|
||||
for slot in range(5):
|
||||
items_in.append([0, 0, 0, slot, d.plain('stone', 64)])
|
||||
elif roll < 0.5:
|
||||
items_in.append([0, 0, 0, rng.randrange(5), d.plain('bone_meal', rng.choice([1, 63, 64]))])
|
||||
case['hopper'] = True
|
||||
else:
|
||||
facing = 'down' if rng.random() < 0.75 else rng.choice(SIDES + ['up'])
|
||||
cells.append([0, 0, 0, states.get('dropper', facing=facing, triggered='false')])
|
||||
dx, dy, dz = d.STEP[facing]
|
||||
cells.append([dx, dy, dz, composter(states, rng)])
|
||||
slots = rng.sample(range(9), rng.choice([1, 1, 2, 9]))
|
||||
for slot in slots:
|
||||
items_in.append([0, 0, 0, slot, stack(rng, items, compostable, 0.3)])
|
||||
case['cells'] = cells
|
||||
case['items'] = items_in
|
||||
case['mode'] = 'dispense'
|
||||
case['action'] = mode
|
||||
yield case
|
||||
|
||||
|
||||
def main():
|
||||
parser = h.argument_parser(__doc__)
|
||||
args = parser.parse_args()
|
||||
if args.count == 40000:
|
||||
args.count = 3000
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
facts = h.load_facts()
|
||||
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
|
||||
items = json.loads((resources / 'items.json').read_text())
|
||||
work = lab.LOCAL / 'composter-parity'
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
all_cases = list(cases(facts, items, args.count, args.seed))
|
||||
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases))
|
||||
classes = work / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
java_root = lab.ROOT / 'mods/horizon/src/test/java'
|
||||
d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
|
||||
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
|
||||
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
|
||||
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
|
||||
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
|
||||
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
|
||||
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
|
||||
native = h.split_cases((work / 'native.txt').read_text(), ignore)
|
||||
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
|
||||
assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
|
||||
groups, errors = {}, {}
|
||||
for case, a, b in zip(all_cases, native, rust):
|
||||
if a and a[0].startswith('error'):
|
||||
errors.setdefault(a[0], []).append(case)
|
||||
continue
|
||||
if not d.same(a, b):
|
||||
groups.setdefault(case['action'], []).append((case, a, b))
|
||||
for kind, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
|
||||
print(f'oracle error x{len(entries)}: {kind}')
|
||||
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
|
||||
print(f'{name}: {len(entries)} differing')
|
||||
for case, a, b in entries[:args.show]:
|
||||
print(' case ' + d.describe(case, facts) + (' use=' + json.dumps(case['use']) if 'use' in case else ''))
|
||||
print(' native ' + ' | '.join(sorted(a)))
|
||||
print(' rust ' + ' | '.join(sorted(b)))
|
||||
total = sum(len(v) for v in groups.values())
|
||||
skipped = sum(len(v) for v in errors.values())
|
||||
print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors)')
|
||||
h.finish(total + skipped)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user