Merge worktree-agent-a12e061d400abc3f6

This commit is contained in:
Ludovic Marie
2026-10-10 08:46:23 +02:00
40 changed files with 6156 additions and 524 deletions
@@ -0,0 +1,97 @@
//! Block transformer lookups for tools/test_block_transformer_parity.py: reads
//! "transformer TAB face TAB clicked TAB above" lines (states as
//! "name|prop=value,...") and prints the oracle's result lines.
//!
//! usage: block_transform_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
assets::Assets,
block_transform::{Around, Transformers},
items::Items,
};
use horizon_world::chunk::BlockState;
use std::{fs, path::Path};
fn parse(text: &str) -> BlockState {
let (name, props) = text.split_once('|').unwrap_or((text, ""));
BlockState {
name: name.to_owned(),
properties: props
.split(',')
.filter(|p| !p.is_empty())
.filter_map(|p| p.split_once('='))
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
}
}
fn describe(state: &BlockState) -> String {
let props: Vec<String> = state
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}|{}", state.name, props.join(","))
}
struct Column {
clicked: BlockState,
above: BlockState,
}
impl Around for Column {
fn state(&self, offset: [i32; 3]) -> BlockState {
match offset {
[0, 0, 0] => self.clicked.clone(),
[0, 1, 0] => self.above.clone(),
_ => BlockState {
name: "minecraft:stone".into(),
properties: Default::default(),
},
}
}
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let assets = Assets::load(root)?;
let transformers = Transformers::load(root, assets.registry)?;
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split('\t').collect();
let around = Column {
clicked: parse(f[2]),
above: parse(f[3]),
};
if f[0] == "honeycomb" {
let waxed = transformers.waxed(assets.registry, &around.clicked);
out += &format!("{}\n", waxed.map_or("none".to_owned(), |s| describe(&s)));
continue;
}
let id = format!("minecraft:{}", f[0]);
match transformers.apply(&items, assets.registry, &id, f[1], &around) {
None => out += "none\n",
Some((index, t, state)) => {
out += &format!(
"{index}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
describe(&state),
t.sound,
t.particle,
t.loot.as_deref().unwrap_or("-"),
t.drop_strategy,
t.update_from_neighbors,
t.transform_type,
t.consume_on_use,
t.damage
);
}
}
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,145 @@
//! Cauldron interactions for tools/test_cauldron_parity.py: reads one JSON
//! case per line and prints "result TAB events TAB inventory".
//!
//! usage: cauldron_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
cauldron::{Outcome, Player, interact, removes_dye},
crafting::Recipes,
item_data::{canon_stack, parse_stack},
items::{ItemStack, Items},
menu::{Env, Kind, Menu},
};
use horizon_world::chunk::BlockState;
use serde_json::Value;
use std::{fs, path::Path};
struct Stand<'a> {
menu: Menu,
env: &'a Env<'a>,
events: Vec<String>,
hand: Option<ItemStack>,
}
impl Player for Stand<'_> {
fn creative(&self) -> bool {
self.menu.creative
}
fn hand(&mut self) -> &mut Option<ItemStack> {
&mut self.hand
}
fn add(&mut self, stack: &mut ItemStack) -> bool {
// The held stack lives in inventory slot 0 for Inventory.add.
self.menu.set_player_item(0, self.hand.take());
let added = self.menu.give(self.env, stack);
self.hand = self.menu.player_item(0).cloned();
self.menu.set_player_item(0, None);
added
}
fn contains(&self, stack: &ItemStack) -> bool {
self.menu.player_contains(stack)
|| self
.hand
.as_ref()
.is_some_and(|h| h.same_item_same_components(stack))
}
fn drop_stack(&mut self, stack: ItemStack) {
self.events
.push(format!("drop {}", canon_stack(Some(&stack))));
}
}
fn parse(text: &str) -> BlockState {
let (name, props) = text.split_once('|').unwrap_or((text, ""));
BlockState {
name: name.to_owned(),
properties: props
.split(',')
.filter(|p| !p.is_empty())
.filter_map(|p| p.split_once('='))
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
}
}
fn describe(state: &BlockState) -> String {
let props: Vec<String> = state
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}|{}", state.name, props.join(","))
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
};
let mut out = String::new();
for line in input.lines() {
let case: Value = serde_json::from_str(line)?;
let mut menu = Menu::new(Kind::Inventory);
menu.creative = case["creative"].as_bool().unwrap_or(false);
for pair in case["inventory"].as_array().ok_or("inventory")? {
menu.set_player_item(
pair[0].as_u64().unwrap_or(0) as usize,
parse_stack(pair[1].as_str().unwrap_or("-"))?,
);
}
let held = parse_stack(case["held"].as_str().unwrap_or("-"))?;
let mut stand = Stand {
menu,
env: &env,
events: Vec::new(),
hand: held,
};
let cauldron = parse(case["state"].as_str().unwrap_or_default());
let dye = stand
.hand
.as_ref()
.is_some_and(|h| removes_dye(&items, &h.item));
let result = interact(
&cauldron,
case["under_water"].as_bool().unwrap_or(false),
dye,
&mut stand,
);
if let Some(block) = &result.block {
stand.events.push(format!("set {}", describe(block)));
}
if let Some(sound) = result.sound {
stand.events.push(format!("sound {sound}"));
}
let kind = match result.outcome {
Outcome::Success => "success",
Outcome::Consume => "consume",
Outcome::Pass => "pass",
};
stand.menu.set_player_item(0, stand.hand.take());
let inventory: Vec<String> = (0..41)
.filter_map(|i| {
stand
.menu
.player_item(i)
.map(|s| format!("{i}={}", canon_stack(Some(s))))
})
.collect();
out += &format!(
"{kind}\t{}\t{}\n",
stand.events.join(";"),
inventory.join(" ")
);
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,71 @@
//! Menu clicks for tools/test_menu_click_parity.py: reads one JSON case per
//! line (menu, creative, slots, carried, data, ops) and prints the oracle's
//! state lines after every click.
//!
//! usage: menu_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
crafting::Recipes,
item_data::{canon_stack, parse_stack},
items::Items,
menu::{Env, Input, Kind, Menu},
};
use serde_json::Value;
use std::{fs, path::Path};
fn state(menu: &Menu) -> String {
let slots: Vec<String> = (0..menu.slot_count())
.map(|i| canon_stack(menu.slot(i)))
.collect();
let data: String = menu.data.iter().map(|d| format!(" {d}")).collect();
format!(
"{} | {} |{data} | {}",
slots.join(" "),
canon_stack(menu.carried.as_ref()),
menu.drops.join(";")
)
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: menu_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
};
let mut out = String::new();
for line in input.lines() {
let case: Value = serde_json::from_str(line)?;
let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?;
let mut menu = Menu::new(kind);
menu.creative = case["creative"].as_bool().unwrap_or(false);
for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() {
menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?);
}
menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?;
for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() {
menu.data[i] = v.as_i64().unwrap_or(0) as i32;
}
menu.drops.clear();
out += &format!("init {}\n", state(&menu));
for op in case["ops"].as_array().ok_or("ops")? {
let slot = op[0].as_i64().unwrap_or(0) as i32;
let button = op[1].as_i64().unwrap_or(0) as i32;
let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?;
match menu.click(&env, slot, button, kind) {
Ok(()) => out += &format!("{}\n", state(&menu)),
Err(name) => out += &format!("error {name}\n"),
}
}
out += "end\n";
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,91 @@
//! Recipe lookups for tools/test_recipe_parity.py: reads the oracle's
//! tab-separated commands (craft, cook, stonecut, smith) and prints one line
//! per command in the oracle's format.
//!
//! usage: recipe_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
crafting::Recipes,
enchant::Enchantments,
item_data::{canon_stack, parse_stack},
items::Items,
stations::StationRecipes,
};
use std::{fs, path::Path};
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let stations = StationRecipes::load(root, &items);
let enchantments = Enchantments::load(root);
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split('\t').collect();
let stack = |i: usize| parse_stack(f[i]);
let text = match f[0] {
"craft" => {
let n: usize = f[1].parse()?;
let mut grid = Vec::new();
for i in 0..n * n {
grid.push(stack(2 + i)?);
}
match recipes.find(&grid, n) {
None => "none".to_owned(),
Some((id, result)) => {
let rest = recipes.remainders(id, &grid, n);
let rest: Vec<String> = rest
.iter()
.enumerate()
.filter_map(|(i, s)| {
Some(format!("{i}={}", canon_stack(Some(s.as_ref()?))))
})
.collect();
format!("{id}\t{}\t{}", canon_stack(Some(&result)), rest.join(";"))
}
}
}
"cook" => match stack(2)?.and_then(|s| {
recipes
.cook(&format!("minecraft:{}", f[1]), &s)
.map(|c| (c.id.clone(), c.result.clone(), c.experience, c.time))
}) {
None => "none".to_owned(),
Some((id, result, xp, time)) => {
format!("{id}\t{}\t{xp:?}\t{time}", canon_stack(Some(&result)))
}
},
"stonecut" => match stack(1)? {
None => String::new(),
Some(s) => stations
.stonecutter(&s)
.iter()
.map(|r| {
format!(
"{}={}",
r.id.trim_start_matches("minecraft:"),
canon_stack(Some(&r.result))
)
})
.collect::<Vec<_>>()
.join(";"),
},
"smith" => {
let (t, b, a) = (stack(1)?, stack(2)?, stack(3)?);
match stations.smithing_result(&enchantments, t.as_ref(), b.as_ref(), a.as_ref()) {
None => "none".to_owned(),
Some(r) => canon_stack(Some(&r)),
}
}
other => return Err(format!("unknown command {other}").into()),
};
out.push_str(&text);
out.push('\n');
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,269 @@
//! The `minecraft:block_transformer` registry (axe, hoe, shovel) that
//! `BlockTransformer.transformBlock` reads: each transform's rule based state
//! provider is evaluated against the clicked block and the block above.
//! `tools/test_block_transformer_parity.py` compares every block state with
//! vanilla.
use crate::{Result, items::Items};
use horizon_world::{chunk::BlockState, registry::BlockRegistry};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
enum Predicate {
Blocks(Vec<String>),
Tag { tag: String, offset: [i32; 3] },
AllOf(Vec<Predicate>),
AnyOf(Vec<Predicate>),
}
enum Provider {
Rules(Vec<(Predicate, Provider)>),
State(BlockState),
/// `CopyPropertiesProvider`: the source with the clicked block's properties.
Copy(Box<Provider>),
}
/// One `BlockTransformData`.
pub struct Transform {
provider: Provider,
pub disallowed_faces: Vec<String>,
pub sound: String,
pub particle: String,
pub loot: Option<String>,
pub drop_strategy: String,
pub update_from_neighbors: bool,
pub transform_type: String,
pub consume_on_use: bool,
pub damage: u32,
}
pub struct Transformers {
transformers: HashMap<String, Vec<Transform>>,
}
/// What the transformer reads of the world: the block state at an offset from
/// the clicked position.
pub trait Around {
fn state(&self, offset: [i32; 3]) -> BlockState;
}
fn state_of(value: &Value, registry: &BlockRegistry) -> Option<BlockState> {
let name = value["id"].as_str().or_else(|| value["Name"].as_str())?;
let default = registry.default_state(name)?;
let mut state = registry.state(default)?.clone();
for (k, v) in value["properties"].as_object().into_iter().flatten() {
state.properties.insert(k.clone(), v.as_str()?.to_owned());
}
Some(state)
}
fn predicate(value: &Value) -> Option<Predicate> {
Some(match value["type"].as_str()? {
"minecraft:matching_blocks" => Predicate::Blocks(match &value["blocks"] {
Value::String(s) => vec![s.clone()],
Value::Array(a) => a
.iter()
.filter_map(|b| b.as_str().map(str::to_owned))
.collect(),
_ => return None,
}),
"minecraft:matching_block_tag" => {
let o = value["offset"].as_array();
let at = |i: usize| {
o.and_then(|o| o.get(i))
.and_then(Value::as_i64)
.unwrap_or(0) as i32
};
Predicate::Tag {
tag: value["tag"].as_str()?.to_owned(),
offset: [at(0), at(1), at(2)],
}
}
"minecraft:all_of" => Predicate::AllOf(
value["predicates"]
.as_array()?
.iter()
.map(predicate)
.collect::<Option<_>>()?,
),
"minecraft:any_of" => Predicate::AnyOf(
value["predicates"]
.as_array()?
.iter()
.map(predicate)
.collect::<Option<_>>()?,
),
_ => return None,
})
}
fn provider(value: &Value, registry: &BlockRegistry) -> Option<Provider> {
match value["type"].as_str() {
Some("minecraft:rule_based") => {
let mut rules = Vec::new();
for rule in value["rules"].as_array()? {
rules.push((
predicate(&rule["if_true"])?,
provider(&rule["then"], registry)?,
));
}
Some(Provider::Rules(rules))
}
Some("minecraft:copy_properties") => Some(Provider::Copy(Box::new(provider(
&value["source"],
registry,
)?))),
_ => state_of(value, registry).map(Provider::State),
}
}
/// `BlockState.withPropertiesOf`: the properties both blocks have.
fn with_properties_of(
registry: &BlockRegistry,
mut state: BlockState,
old: &BlockState,
) -> Option<BlockState> {
let defaults = registry
.default_state(&state.name)
.and_then(|id| registry.state(id))?;
for (k, v) in &old.properties {
if defaults.properties.contains_key(k) {
let mut candidate = state.clone();
candidate.properties.insert(k.clone(), v.clone());
if registry.resolve(&candidate).is_ok() {
state = candidate;
}
}
}
Some(state)
}
impl Predicate {
fn test(&self, items: &Items, around: &dyn Around) -> bool {
match self {
Self::Blocks(names) => {
let state = around.state([0, 0, 0]);
names.contains(&state.name)
}
Self::Tag { tag, offset } => {
let state = around.state(*offset);
items
.block_tags
.get(tag)
.is_some_and(|members| members.contains(&state.name))
}
Self::AllOf(all) => all.iter().all(|p| p.test(items, around)),
Self::AnyOf(any) => any.iter().any(|p| p.test(items, around)),
}
}
}
impl Provider {
fn state(
&self,
items: &Items,
registry: &BlockRegistry,
around: &dyn Around,
) -> Option<BlockState> {
match self {
Self::Rules(rules) => rules
.iter()
.find(|(p, _)| p.test(items, around))
.and_then(|(_, then)| then.state(items, registry, around)),
Self::State(state) => Some(state.clone()),
Self::Copy(source) => {
let state = source.state(items, registry, around)?;
with_properties_of(registry, state, &around.state([0, 0, 0]))
}
}
}
}
impl Transformers {
/// Reads `data/minecraft/block_transformer/*.json`.
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
let mut transformers = HashMap::new();
let dir = root.join("data/minecraft/block_transformer");
if dir.exists() {
for entry in fs::read_dir(&dir)?.flatten() {
let path = entry.path();
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
let list: Value = serde_json::from_slice(&fs::read(&path)?)?;
let mut transforms = Vec::new();
for t in list.as_array().into_iter().flatten() {
let text = |k: &str, d: &str| t[k].as_str().unwrap_or(d).to_owned();
let Some(provider) = provider(&t["block_state_provider"], registry) else {
continue;
};
transforms.push(Transform {
provider,
disallowed_faces: t["disallowed_faces"]
.as_array()
.into_iter()
.flatten()
.filter_map(|f| f.as_str().map(str::to_owned))
.collect(),
sound: text("sound", "minecraft:empty"),
particle: text("particle", "none"),
loot: t["loot"].as_str().map(str::to_owned),
drop_strategy: text("drop_strategy", "from_middle"),
update_from_neighbors: t["update_from_neighbors"].as_bool().unwrap_or(true),
transform_type: text("transform_type", "single_block"),
consume_on_use: t["consume_on_use"].as_bool().unwrap_or(true),
damage: t["item_damage_per_use"].as_u64().unwrap_or(0) as u32,
});
}
transformers.insert(format!("minecraft:{stem}"), transforms);
}
}
Ok(Self { transformers })
}
/// `BlockTransformer.transformBlock` without the world writes: the first
/// transform that allows the clicked face and provides a state, with its
/// index.
pub fn apply<'a>(
&'a self,
items: &Items,
registry: &BlockRegistry,
id: &str,
face: &str,
around: &dyn Around,
) -> Option<(usize, &'a Transform, BlockState)> {
self.transformers
.get(id)?
.iter()
.enumerate()
.filter(|(_, t)| !t.disallowed_faces.iter().any(|f| f == face))
.find_map(|(i, t)| Some((i, t, t.provider.state(items, registry, around)?)))
}
/// `HoneycombItem.getWaxed`: the waxed twin of a copper block, found from
/// the axe's wax-off transforms (`WAX_OFF_BY_BLOCK` is the inverse of
/// `WAXABLES`).
pub fn waxed(&self, registry: &BlockRegistry, old: &BlockState) -> Option<BlockState> {
for transform in self.transformers.get("minecraft:axe")? {
if transform.particle != "wax_off" {
continue;
}
let Provider::Rules(rules) = &transform.provider else {
continue;
};
for (predicate, then) in rules {
if let (Predicate::Blocks(names), Provider::Copy(source)) = (predicate, then)
&& let Provider::State(unwaxed) = &**source
&& unwaxed.name == old.name
&& let Some(waxed) = names.first()
{
let target = registry
.default_state(waxed)
.and_then(|id| registry.state(id))?
.clone();
return with_properties_of(registry, target, old);
}
}
}
None
}
}
+298
View File
@@ -0,0 +1,298 @@
//! `CauldronInteractions`: what an item does to an empty, water, lava or
//! powder snow cauldron. `tools/test_cauldron_parity.py` compares every item
//! with vanilla's `useItemOn`.
use crate::items::{ItemStack, Items};
/// `ItemTags.CAULDRON_CAN_REMOVE_DYE` membership.
pub fn removes_dye(items: &Items, item: &str) -> bool {
items
.item_tags
.get("minecraft:cauldron_can_remove_dye")
.is_some_and(|members| members.contains(item))
}
use horizon_world::chunk::BlockState;
/// The player side of an interaction.
pub trait Player {
fn creative(&self) -> bool;
/// The stack in the interacting hand.
fn hand(&mut self) -> &mut Option<ItemStack>;
/// `Inventory.add`; the leftover stays in `stack`.
fn add(&mut self, stack: &mut ItemStack) -> bool;
/// `Inventory.contains`.
fn contains(&self, stack: &ItemStack) -> bool;
fn drop_stack(&mut self, stack: ItemStack);
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Outcome {
/// `InteractionResult.SUCCESS`
Success,
/// `InteractionResult.CONSUME`
Consume,
/// `TRY_WITH_EMPTY_HAND`
Pass,
}
#[derive(Debug)]
pub struct Interaction {
pub outcome: Outcome,
/// The cauldron's new state.
pub block: Option<BlockState>,
pub sound: Option<&'static str>,
}
fn state(name: &str, level: Option<u8>) -> BlockState {
BlockState {
name: name.to_owned(),
properties: level
.map(|l| ("level".to_owned(), l.to_string()))
.into_iter()
.collect(),
}
}
fn pass() -> Interaction {
Interaction {
outcome: Outcome::Pass,
block: None,
sound: None,
}
}
/// `ItemUtils.createFilledResult`.
fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) {
let creative = player.creative();
if limit_creative && creative {
if !player.contains(&new) {
let mut new = new;
player.add(&mut new);
}
return;
}
let hand = player.hand();
if !creative && let Some(held) = hand.as_mut() {
held.count -= 1;
if held.count == 0 {
*hand = None;
}
}
if hand.is_none() {
*hand = Some(new);
return;
}
let mut new = new;
if !player.add(&mut new) {
player.drop_stack(new);
}
}
/// `LayeredCauldronBlock.lowerFillLevel`.
fn lowered(cauldron: &BlockState) -> BlockState {
let level: u8 = cauldron
.properties
.get("level")
.and_then(|l| l.parse().ok())
.unwrap_or(1);
if level <= 1 {
state("minecraft:cauldron", None)
} else {
let mut next = cauldron.clone();
next.properties
.insert("level".into(), (level - 1).to_string());
next
}
}
fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction {
Interaction {
outcome: Outcome::Success,
block: Some(block),
sound,
}
}
const COLORS: [&str; 16] = [
"white",
"orange",
"magenta",
"light_blue",
"yellow",
"lime",
"pink",
"gray",
"light_gray",
"cyan",
"purple",
"blue",
"brown",
"green",
"red",
"black",
];
/// The cauldron interaction of the held item (`useItemOn`); the hand stack is
/// changed through `player`. `removes_dye` is whether the held item is in the
/// `cauldron_can_remove_dye` tag.
pub fn interact(
cauldron: &BlockState,
under_water: bool,
removes_dye: bool,
player: &mut dyn Player,
) -> Interaction {
let Some(held) = player.hand().clone() else {
return pass();
};
let kind = match cauldron.name.as_str() {
"minecraft:cauldron" => "empty",
"minecraft:water_cauldron" => "water",
"minecraft:lava_cauldron" => "lava",
"minecraft:powder_snow_cauldron" => "powder_snow",
_ => return pass(),
};
let level: u8 = cauldron
.properties
.get("level")
.and_then(|l| l.parse().ok())
.unwrap_or(0);
let item = &*held.item;
let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water");
// Dispatcher.get: tags first, then the item map.
if kind == "water" && removes_dye {
if held.data().and_then(|d| d.dyed_color).is_none() {
return pass();
}
if let Some(stack) = player.hand().as_mut() {
stack.data_mut().dyed_color = None;
stack.tidy();
}
return changed(lowered(cauldron), None);
}
let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| {
if !can_fill {
return pass();
}
filled(player, ItemStack::new(new, 1), true);
changed(state("minecraft:cauldron", None), Some(sound))
};
let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| {
filled(player, ItemStack::new("minecraft:bucket", 1), true);
changed(block, Some(sound))
};
match item {
"minecraft:lava_bucket" => {
return if under_water {
Interaction {
outcome: Outcome::Consume,
block: None,
sound: None,
}
} else {
empty_bucket(
player,
state("minecraft:lava_cauldron", None),
"minecraft:item.bucket.empty_lava",
)
};
}
"minecraft:water_bucket" => {
return empty_bucket(
player,
state("minecraft:water_cauldron", Some(3)),
"minecraft:item.bucket.empty",
);
}
"minecraft:powder_snow_bucket" => {
return if under_water {
Interaction {
outcome: Outcome::Consume,
block: None,
sound: None,
}
} else {
empty_bucket(
player,
state("minecraft:powder_snow_cauldron", Some(3)),
"minecraft:item.bucket.empty_powder_snow",
)
};
}
_ => {}
}
match (kind, item) {
("empty", "minecraft:potion") => {
if !water_potion {
return pass();
}
filled(player, ItemStack::new("minecraft:glass_bottle", 1), true);
changed(
state("minecraft:water_cauldron", Some(1)),
Some("minecraft:item.bottle.empty"),
)
}
("water", "minecraft:bucket") => fill_bucket(
player,
"minecraft:water_bucket",
level == 3,
"minecraft:item.bucket.fill",
),
("water", "minecraft:glass_bottle") => {
filled(
player,
ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"),
true,
);
changed(lowered(cauldron), Some("minecraft:item.bottle.fill"))
}
("water", "minecraft:potion") => {
if level == 3 || !water_potion {
return pass();
}
filled(player, ItemStack::new("minecraft:glass_bottle", 1), true);
let mut next = cauldron.clone();
// BlockState.cycle on a 1..=3 property
next.properties
.insert("level".into(), (level % 3 + 1).to_string());
changed(next, Some("minecraft:item.bottle.empty"))
}
("water", name)
if name
.strip_prefix("minecraft:")
.and_then(|n| n.strip_suffix("_banner"))
.is_some_and(|c| COLORS.contains(&c)) =>
{
let layers = held.data().map_or(0, |d| d.banner_patterns.len());
if layers == 0 {
return pass();
}
let mut cleaned = held.clone();
cleaned.count = 1;
cleaned.data_mut().banner_patterns.pop();
cleaned.tidy();
filled(player, cleaned, false);
changed(lowered(cauldron), None)
}
("water", name)
if name
.strip_prefix("minecraft:")
.and_then(|n| n.strip_suffix("_shulker_box"))
.is_some_and(|c| COLORS.contains(&c)) =>
{
filled(player, held.transmute("minecraft:shulker_box", 1), false);
changed(lowered(cauldron), None)
}
("lava", "minecraft:bucket") => fill_bucket(
player,
"minecraft:lava_bucket",
true,
"minecraft:item.bucket.fill_lava",
),
("powder_snow", "minecraft:bucket") => fill_bucket(
player,
"minecraft:powder_snow_bucket",
level == 3,
"minecraft:item.bucket.fill_powder_snow",
),
_ => pass(),
}
}
+3
View File
@@ -107,6 +107,8 @@ pub struct Chunk {
pub fresh: bool,
/// Block entities read from a save, moved into the world on arrival.
pub block_entities: Vec<((i32, i32, i32), crate::containers::BlockEntity)>,
/// `CustomName` of the container block entities (shown as the screen title).
pub block_names: Vec<((i32, i32, i32), String)>,
/// Generation postprocessing marks (ProtoChunk.postProcessing) as world
/// positions, applied once by LevelChunk.postProcessGeneration.
pub postprocess: Vec<[i32; 3]>,
@@ -131,6 +133,7 @@ impl Chunk {
light_loaded: false,
fresh: false,
block_entities: Vec::new(),
block_names: Vec::new(),
structure_refs: Vec::new(),
postprocess: Vec::new(),
saved: None,
File diff suppressed because it is too large Load Diff
+17 -13
View File
@@ -239,11 +239,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.remove(&"Items".into());
}
let mut equipment = Vec::new();
if m.extra.saddled {
equipment.push((
"saddle",
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
));
if let Some(saddle) = m.saddle_item() {
equipment.push(("saddle", crate::save::item_to_nbt(&saddle)));
}
if let Some(armor) = &m.extra.head {
equipment.push((
@@ -273,11 +270,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
Some(Tag::Compound(c)) => c.clone(),
_ => Compound::new(),
};
if m.extra.saddled {
equipment.insert(
"saddle".into(),
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
);
if let Some(saddle) = m.saddle_item() {
equipment.insert("saddle".into(), crate::save::item_to_nbt(&saddle));
} else {
equipment.remove(&"saddle".into());
}
@@ -571,8 +565,15 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.species(),
crate::mobs::Species::Pig | crate::mobs::Species::Strider
) {
m.extra.saddled =
tag.get("equipment").and_then(|e| e.get("saddle")).is_some() || flag(tag, "Saddle");
let saddle = tag
.get("equipment")
.and_then(|e| e.get("saddle"))
.and_then(crate::save::item_from_nbt);
if saddle.is_some() || flag(tag, "Saddle") {
m.set_saddle(Some(saddle.unwrap_or_else(|| {
crate::items::ItemStack::new("minecraft:saddle", 1)
})));
}
}
if crate::mobs::equine::is_equine(m.species()) {
m.extra.tame = flag(tag, "Tame");
@@ -589,7 +590,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.items = crate::save::decode_items(tag.get("Items"), 15);
}
let eq = tag.get("equipment");
m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some();
m.set_saddle(
eq.and_then(|e| e.get("saddle"))
.and_then(crate::save::item_from_nbt),
);
m.extra.head = eq
.and_then(|e| e.get("body"))
.and_then(|b| text(b.get("id")))
+560 -136
View File
@@ -468,6 +468,7 @@ pub struct Resources {
facts: BlockFacts,
items: Items,
recipes: Recipes,
transformers: horizon_client::block_transform::Transformers,
biomes: Arc<Biomes>,
environment: Environment,
atlas: HudAtlas,
@@ -517,6 +518,10 @@ struct Game<'a> {
carried: Option<ItemStack>,
craft_grid: Vec<Option<ItemStack>>,
craft_size: usize,
/// A quick craft drag over inventory slots: (button, game slots so far).
inv_drag: Option<(i32, Vec<usize>)>,
/// The last inventory click, for the double click that gathers a stack.
last_inv_click: Option<(std::time::Instant, usize, bool)>,
/// Open container block entity, if any.
container: Option<(i32, i32, i32)>,
/// Open workstation menu (enchanting table, anvil, ...).
@@ -674,6 +679,8 @@ struct Game<'a> {
pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>,
/// Layers of broken banners waiting for their dropped item.
pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>,
/// Custom names of broken containers, for the dropped item (`copy_components`).
pending_names: HashMap<[i32; 3], (String, String)>,
/// The recipe book of the open screen (game/recipe_book.rs).
recipe_ui: recipe_book::RecipeUi,
/// The horse inventory (game/mount_menu.rs).
@@ -1076,6 +1083,7 @@ impl Game<'_> {
/// Block.popResource
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
self.attach_shulker_contents(pos, &mut stack);
self.attach_container_name(pos, &mut stack);
self.attach_banner_layers(pos, &mut stack);
let r = &mut self.world.random;
let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25;
@@ -1093,9 +1101,9 @@ impl Game<'_> {
}
/// Player.drop: thrown from the eyes along the view direction.
fn drop_held(&mut self, all: bool) {
let Some(eye) = self.eye_position() else {
if self.eye_position().is_none() {
return;
};
}
let Some(stack) = self.inventory[self.selected].as_mut() else {
return;
};
@@ -1104,13 +1112,20 @@ impl Game<'_> {
count,
..stack.clone()
};
// Player.drop: the drop statistics.
self.stats.add("dropped", &thrown.item, count as i32);
self.stats.custom("drop", 1);
stack.count -= count;
if stack.count == 0 {
self.inventory[self.selected] = None;
}
self.player_drop(thrown);
}
/// `Player.drop`: the statistics and a thrown item entity in front of the player.
fn player_drop(&mut self, thrown: ItemStack) {
let Some(eye) = self.eye_position() else {
return;
};
// Player.drop: the drop statistics.
self.stats.add("dropped", &thrown.item, thrown.count as i32);
self.stats.custom("drop", 1);
let (yaw, pitch) = (
f64::from(self.yaw).to_radians(),
f64::from(self.pitch).to_radians(),
@@ -1946,6 +1961,7 @@ impl Game<'_> {
.block_entities
.insert((target[0], target[1], target[2]), entity);
self.fill_placed_box(target, &stack);
self.name_placed_container(target, &stack);
self.fill_placed_banner(target, &stack);
if sign {
self.open_sign_editor((target[0], target[1], target[2]), true);
@@ -3397,9 +3413,17 @@ impl Game<'_> {
}
}
fn craft_result(&self) -> Option<ItemStack> {
self.craft_recipe().map(|(_, result)| result)
}
/// The recipe id and result of the crafting grid.
fn craft_recipe(&self) -> Option<(String, ItemStack)> {
let n = self.craft_size;
let grid: Vec<Option<ItemStack>> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect();
self.res.recipes.craft(&grid, n)
let scale = |id: i32| self.maps.data.get(&id).map(|m| m.scale);
self.res
.recipes
.find_with(&grid, n, &scale)
.map(|(name, result)| (name.to_owned(), result))
}
fn draw_inventory(&mut self, batch: &mut HudBatch) {
if self.draw_station(batch) {
@@ -3453,6 +3477,7 @@ impl Game<'_> {
}
};
part(batch, tex, 0.0, 0.0, 176.0, 166.0, ox, oy);
let title = &self.container_title(title.to_owned());
let tw = HudBatch::text_width(atlas, title);
batch.text(atlas, title, ox + (176.0 - tw) / 2.0, oy + 6.0, grey, false);
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
@@ -3625,6 +3650,319 @@ impl Game<'_> {
self.close_ender_chest();
self.close_cart_container();
}
/// `quickMoveStack` of the open plain menu for a shift-click.
fn inventory_quick_move(&mut self, slot: usize) -> bool {
self.menu_click(Some(slot), 0, horizon_client::menu::Input::QuickMove)
}
/// `AbstractContainerMenu.clicked` on the open inventory, crafting table,
/// chest, hopper, dispenser or furnace menu, run by the verified menu
/// engine (`horizon_client::menu`). `slot` None is outside the window.
/// False when the open screen is not one the engine models.
fn menu_click(
&mut self,
slot: Option<usize>,
button: i32,
input: horizon_client::menu::Input,
) -> bool {
self.menu_ops(&[(slot, button, input)])
}
/// Several clicks on one menu instance (a quick craft drag is three).
fn menu_ops(&mut self, ops: &[(Option<usize>, i32, horizon_client::menu::Input)]) -> bool {
use horizon_client::menu::{Env, Kind, Menu};
#[derive(Clone, Copy)]
struct Map {
container: usize,
table: bool,
cells: usize,
plain: bool,
}
impl Map {
fn main(&self) -> usize {
match (self.plain, self.table) {
(false, _) => self.container,
(true, true) => 10,
(true, false) => 9,
}
}
fn to_menu(self, g: usize) -> Option<usize> {
let main = self.main();
if self.plain {
match g {
200 => Some(0),
100..109 if g - 100 < self.cells => Some(1 + g - 100),
500..504 if !self.table => Some(5 + g - 500),
504 if !self.table => Some(45),
9..36 => Some(main + g - 9),
0..9 => Some(main + 27 + g),
_ => None,
}
} else {
match g {
300.. if g < 300 + self.container => Some(g - 300),
9..36 => Some(main + g - 9),
0..9 => Some(main + 27 + g),
_ => None,
}
}
}
fn to_game(self, i: usize) -> Option<usize> {
let main = self.main();
if self.plain {
match i {
0 => None,
1..=9 if i - 1 < self.cells => Some(100 + i - 1),
5..9 if !self.table => Some(500 + i - 5),
45 if !self.table => Some(504),
_ if i >= main && i < main + 27 => Some(9 + i - main),
_ if i >= main + 27 && i < main + 36 => Some(i - main - 27),
_ => None,
}
} else if i < self.container {
Some(300 + i)
} else if i < self.container + 27 {
Some(9 + i - self.container)
} else {
Some(i - self.container - 27)
}
}
}
let (kind, map) = if self.container.is_some() {
let size = self.container_size();
let (kind, count) = match self.container_kind() {
Some(BlockEntity::Chest(_)) => {
let shulker = self.container.is_some_and(|k| {
let id = self.world.block(k.0, k.1, k.2);
storage::is_shulker_box(&self.res.facts.get(id).name)
});
let kind = match size {
5 => Kind::Hopper,
9 => Kind::Dispenser,
27 if shulker => Kind::Shulker,
n => Kind::Chest((n / 9).clamp(1, 6)),
};
(kind, size)
}
Some(BlockEntity::Furnace(f)) => (
Kind::Furnace(
match f.kind.recipe_type().trim_start_matches("minecraft:") {
"blasting" => "blasting",
"smoking" => "smoking",
_ => "smelting",
},
),
3,
),
_ => return false,
};
let map = Map {
container: count,
table: false,
cells: 0,
plain: false,
};
(kind, map)
} else if self.station.is_none() && !self.mount_active() && self.remote.is_none() {
let table = self.craft_size == 3;
let map = Map {
container: 0,
table,
cells: self.craft_size * self.craft_size,
plain: true,
};
(
if table {
Kind::Crafting
} else {
Kind::Inventory
},
map,
)
} else {
return false;
};
let mut clicks = Vec::new();
for &(slot, button, input) in ops {
let menu_slot = match slot {
Some(g) => {
if g == 200 && input != horizon_client::menu::Input::QuickMove {
return false;
}
match map.to_menu(g) {
Some(i) => i as i32,
None => return false,
}
}
None => -999,
};
clicks.push((menu_slot, button, input));
}
let mut menu = Menu::new(kind);
let total = menu.slot_count();
let before: Vec<Option<ItemStack>> = (0..total)
.map(|i| map.to_game(i).and_then(|g| self.slot_mut(g).clone()))
.collect();
let carried = self.carried.clone();
let creative = self.creative;
let (after, carried, dropped): (Vec<Option<ItemStack>>, Option<ItemStack>, Vec<ItemStack>) = {
let env = Env {
items: &self.res.items,
recipes: &self.res.recipes,
brewing: &self.res.stations.brewing,
};
menu.creative = creative;
for (i, stack) in before.iter().enumerate() {
menu.set_slot(&env, i, stack.clone());
}
menu.carried = carried;
for (menu_slot, button, input) in clicks {
if menu.click(&env, menu_slot, button, input).is_err() {
return true;
}
}
(
(0..total).map(|i| menu.slot(i).cloned()).collect(),
menu.carried.take(),
std::mem::take(&mut menu.dropped),
)
};
for (i, stack) in after.into_iter().enumerate() {
if let Some(g) = map.to_game(i) {
*self.slot_mut(g) = stack;
}
}
self.carried = carried;
for stack in dropped {
self.player_drop(stack);
}
if matches!(kind, Kind::Furnace(_))
&& let Some(BlockEntity::Furnace(f)) = self
.container
.and_then(|k| self.world.block_entities.get_mut(&k))
{
f.cooking_timer = 0;
}
self.apply_equipment();
true
}
/// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar
/// slot or the off hand, THROW one or the whole stack.
fn inventory_hotkey(&mut self, key: KeyCode) -> bool {
use horizon_client::menu::Input;
let Some(size) = self
.renderer
.as_ref()
.map(|r| [r.config.width, r.config.height])
else {
return false;
};
let batch = HudBatch::new(size);
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
return false;
};
let digit = [
KeyCode::Digit1,
KeyCode::Digit2,
KeyCode::Digit3,
KeyCode::Digit4,
KeyCode::Digit5,
KeyCode::Digit6,
KeyCode::Digit7,
KeyCode::Digit8,
KeyCode::Digit9,
]
.iter()
.position(|k| *k == key);
let done = match (digit, key) {
(Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap),
(None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap),
(None, KeyCode::KeyQ) => {
let all = self.keys.contains(&KeyCode::ControlLeft);
self.menu_click(Some(slot), i32::from(all), Input::Throw)
}
_ => false,
};
if done && let Some(key) = self.container {
self.container_changed(key);
}
done
}
/// The plain inventory mouse press: starts a quick craft drag when a
/// stack is held, gathers on a double click, else the normal click.
fn inventory_press(&mut self, right: bool) {
use horizon_client::menu::Input;
let slot = self.renderer.as_ref().and_then(|r| {
let batch = HudBatch::new([r.config.width, r.config.height]);
self.slot_at(&batch, self.cursor.0, self.cursor.1)
});
let shift =
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
if let Some(slot) = slot
&& !shift
&& slot != 200
{
let now = std::time::Instant::now();
let double = !right
&& self.carried.is_some()
&& self.last_inv_click.is_some_and(|(at, last, was_right)| {
last == slot && !was_right && now.duration_since(at).as_millis() < 250
});
self.last_inv_click = Some((now, slot, right));
if double && self.menu_click(Some(slot), 0, Input::PickupAll) {
self.last_inv_click = None;
return;
}
if self.carried.is_some() {
self.inv_drag = Some((i32::from(right), vec![slot]));
return;
}
}
self.click_inventory(right);
}
/// Mouse movement while a quick craft drag is running.
fn inventory_drag_move(&mut self) {
let Some((_, slots)) = self.inv_drag.as_ref() else {
return;
};
let Some(r) = self.renderer.as_ref() else {
return;
};
let batch = HudBatch::new([r.config.width, r.config.height]);
if let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1)
&& slot != 200
&& !slots.contains(&slot)
&& let Some((_, slots)) = self.inv_drag.as_mut()
{
slots.push(slot);
}
}
/// Mouse release: finishes a quick craft drag (one slot is a plain click).
fn inventory_release(&mut self) {
use horizon_client::menu::Input;
let Some((ty, slots)) = self.inv_drag.take() else {
return;
};
if slots.len() == 1 {
if !self.menu_click(Some(slots[0]), ty, Input::Pickup) {
self.click_inventory(ty == 1);
}
} else {
let mask = |header: i32| header | (ty << 2);
let mut ops = vec![(None, mask(0), Input::QuickCraft)];
ops.extend(
slots
.into_iter()
.map(|slot| (Some(slot), mask(1), Input::QuickCraft)),
);
ops.push((None, mask(2), Input::QuickCraft));
if !self.menu_ops(&ops) {
// Not a menu the engine models: the drag is a plain click.
self.click_inventory(ty == 1);
}
}
if let Some(key) = self.container {
self.container_changed(key);
}
}
fn click_inventory(&mut self, right: bool) {
if self.mount_click(right) {
return;
@@ -3703,13 +4041,13 @@ impl Game<'_> {
if slot == 200 {
// ResultSlot: take the crafted stack and consume one of each ingredient.
let mut crafted = 0;
while let Some(result) = self.craft_result() {
while let Some((recipe, result)) = self.craft_recipe() {
let made = (result.item.clone(), result.count);
let cells = self.craft_size * self.craft_size;
let remainders = self.res.recipes.remainders(
&self.res.items,
&recipe,
&self.craft_grid[..cells],
&result,
self.craft_size,
);
if shift {
if self.give(result).is_some() {
@@ -3751,68 +4089,10 @@ impl Game<'_> {
}
return;
}
if shift && (500..504).contains(&slot) {
// InventoryMenu.quickMoveStack: armour back to the main
// inventory, then the hotbar.
if let Some(stack) = self.armor[slot - 500].take() {
if let Some(i) = (9..36).chain(0..9).find(|&i| self.inventory[i].is_none()) {
self.inventory[i] = Some(stack);
} else {
self.armor[slot - 500] = Some(stack);
}
self.apply_equipment();
}
return;
}
if shift && slot < 36 {
// InventoryMenu.quickMoveStack: armour into its empty slot, an
// off-hand item into an empty off hand.
let equip = self.inventory[slot]
.as_ref()
.and_then(|s| self.res.items.get(&s.item))
.and_then(|i| i.equip_slot.clone());
let armor = ["head", "chest", "legs", "feet"]
.iter()
.position(|s| equip.as_deref() == Some(*s));
if let Some(a) = armor
&& self.armor[a].is_none()
{
self.armor[a] = self.inventory[slot].take();
self.apply_equipment();
return;
}
if equip.as_deref() == Some("offhand") && self.offhand.is_none() {
self.offhand = self.inventory[slot].take();
return;
}
// Quick move between hotbar and main inventory.
if let Some(stack) = self.inventory[slot].take() {
let range = if slot < 9 { 9..36 } else { 0..9 };
let mut stack = stack;
for i in range.clone() {
if let Some(s) = &mut self.inventory[i]
&& s.same_item_same_components(&stack)
{
let moved = max(&self.res.items, s)
.saturating_sub(s.count)
.min(stack.count);
s.count += moved;
stack.count -= moved;
}
}
if stack.count > 0
&& let Some(i) = range.clone().find(|&i| self.inventory[i].is_none())
{
self.inventory[i] = Some(stack);
stack = ItemStack {
count: 0,
..self.inventory[i].clone().unwrap()
};
}
if stack.count > 0 {
self.inventory[slot] = Some(stack);
}
}
if shift
&& (slot < 36 || (500..504).contains(&slot) || (100..109).contains(&slot))
&& self.inventory_quick_move(slot)
{
return;
}
if (500..504).contains(&slot) {
@@ -4629,6 +4909,13 @@ impl Game<'_> {
.filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z)
.map(|(p, e)| (*p, e.clone()))
.collect();
c.block_names = self
.world
.block_names
.iter()
.filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z)
.map(|(p, n)| (*p, n.clone()))
.collect();
self.attach_save_data(&mut c);
Arc::new(c)
}
@@ -5553,6 +5840,160 @@ impl Game<'_> {
}
None
}
/// `CauldronInteractions` for the held item aimed at a cauldron.
fn use_on_cauldron(&mut self, pos: [i32; 3]) -> Result<bool> {
use horizon_client::cauldron::{self, Outcome};
struct Hand<'g, 'a>(&'g mut Game<'a>);
impl cauldron::Player for Hand<'_, '_> {
fn creative(&self) -> bool {
self.0.creative
}
fn hand(&mut self) -> &mut Option<ItemStack> {
let selected = self.0.selected;
&mut self.0.inventory[selected]
}
fn add(&mut self, stack: &mut ItemStack) -> bool {
let before = stack.count;
match self.0.give(stack.clone()) {
None => stack.count = 0,
Some(rest) => stack.count = rest.count,
}
stack.count < before
}
fn contains(&self, stack: &ItemStack) -> bool {
self.0
.inventory
.iter()
.flatten()
.any(|have| have.same_item_same_components(stack))
}
fn drop_stack(&mut self, stack: ItemStack) {
if let Some(eye) = self.0.eye_position() {
self.0.spawn_item(stack, eye, [0.0, 0.1, 0.0], 40);
}
}
}
let registry = self.res.assets.registry;
let id = self.world.block(pos[0], pos[1], pos[2]);
let Some(state) = registry
.state(id)
.filter(|s| s.name.ends_with("cauldron"))
.cloned()
else {
return Ok(false);
};
let Some(held) = self.inventory[self.selected].as_ref() else {
return Ok(false);
};
let removes_dye = cauldron::removes_dye(&self.res.items, &held.item);
let above = self.world.block(pos[0], pos[1] + 1, pos[2]);
let under_water = registry
.state(above)
.is_some_and(|s| s.name == "minecraft:water");
let result = cauldron::interact(&state, under_water, removes_dye, &mut Hand(self));
if result.outcome == Outcome::Pass {
return Ok(false);
}
if let Some(block) = result.block
&& let Ok(new) = registry.resolve(&block)
{
self.level_set(pos, new)?;
}
if let Some(sound) = result.sound {
self.audio.play(
sound,
Some([
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
]),
1.0,
1.0,
);
}
Ok(true)
}
/// `BlockTransformer.transformBlock` for a held axe, hoe or shovel.
fn use_block_transformer(
&mut self,
stack: &ItemStack,
pos: [i32; 3],
face: [i32; 3],
) -> Result<bool> {
use horizon_client::block_transform::Around;
struct Column<'w> {
world: &'w World,
registry: &'w horizon_world::registry::BlockRegistry,
pos: [i32; 3],
}
impl Around for Column<'_> {
fn state(&self, o: [i32; 3]) -> horizon_world::chunk::BlockState {
let id =
self.world
.block(self.pos[0] + o[0], self.pos[1] + o[1], self.pos[2] + o[2]);
self.registry.state(id).cloned().unwrap_or_else(|| {
horizon_world::chunk::BlockState {
name: "minecraft:air".into(),
properties: Default::default(),
}
})
}
}
let Some(id) = self
.res
.items
.get(&stack.item)
.and_then(|i| i.block_transformer.clone())
else {
return Ok(false);
};
let face_name = match face {
[0, -1, 0] => "down",
[0, 1, 0] => "up",
[0, 0, -1] => "north",
[0, 0, 1] => "south",
[-1, 0, 0] => "west",
_ => "east",
};
let registry = self.res.assets.registry;
let (state, sound, loot, damage) = {
let around = Column {
world: &self.world,
registry,
pos,
};
let Some((_, t, state)) =
self.res
.transformers
.apply(&self.res.items, registry, &id, face_name, &around)
else {
return Ok(false);
};
(state, t.sound.clone(), t.loot.clone(), t.damage)
};
let Ok(new) = registry.resolve(&state) else {
return Ok(false);
};
self.level_set(pos, new)?;
if loot.as_deref() == Some("minecraft:till/rooted_dirt") {
self.pop_resource(
[pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]],
ItemStack::new("minecraft:hanging_roots", 1),
);
}
self.audio.play(
&sound,
Some([
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
]),
1.0,
1.0,
);
self.damage_held(damage);
Ok(true)
}
fn set_state_named(&mut self, pos: [i32; 3], name: &str, keep: &[&str]) -> Result<bool> {
let registry = &self.res.assets.registry;
let old = self.world.block(pos[0], pos[1], pos[2]);
@@ -5609,6 +6050,11 @@ impl Game<'_> {
f64::from(p[2]) + 0.5,
]
};
if let Some(hit) = self.pick()
&& self.use_on_cauldron(hit.pos)?
{
return Ok(true);
}
if item == "bucket" {
let Some(hit) = self.pick_fluid() else {
return Ok(false);
@@ -5648,17 +6094,6 @@ impl Game<'_> {
return Ok(false);
};
let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
let name = self
.res
.facts
.get(clicked)
.name
.trim_start_matches("minecraft:")
.to_owned();
let above_air =
self.res
.facts
.is_air(self.world.block(hit.pos[0], hit.pos[1] + 1, hit.pos[2]));
if item == "water_bucket" || item == "lava_bucket" {
let target = if self.res.facts.get(clicked).replaceable {
hit.pos
@@ -5695,60 +6130,25 @@ impl Game<'_> {
}
return Ok(true);
}
if item.ends_with("_hoe") && hit.face != [0, -1, 0] && above_air {
// HoeItem.TILLABLES
let result = match name.as_str() {
"grass_block" | "dirt_path" | "dirt" => Some("minecraft:farmland"),
"coarse_dirt" | "rooted_dirt" => Some("minecraft:dirt"),
_ => None,
};
if let Some(result) = result {
self.set_state_named(hit.pos, result, &[])?;
if name == "rooted_dirt" {
self.pop_resource(
[hit.pos[0], hit.pos[1] - 1, hit.pos[2]],
ItemStack {
item: Arc::from("minecraft:hanging_roots"),
count: 1,
damage: 0,
extra: None,
},
);
}
self.audio
.play("minecraft:item.hoe.till", Some(at(hit.pos)), 1.0, 1.0);
self.damage_held(1);
return Ok(true);
}
}
if item.ends_with("_shovel")
&& hit.face != [0, -1, 0]
&& above_air
&& matches!(
name.as_str(),
"grass_block" | "dirt" | "podzol" | "coarse_dirt" | "mycelium" | "rooted_dirt"
)
{
// ShovelItem.FLATTENABLES
self.set_state_named(hit.pos, "minecraft:dirt_path", &[])?;
self.audio
.play("minecraft:item.shovel.flatten", Some(at(hit.pos)), 1.0, 1.0);
self.damage_held(1);
if self.use_block_transformer(stack, hit.pos, hit.face)? {
return Ok(true);
}
if item.ends_with("_axe") && !name.starts_with("stripped_") {
// AxeItem.STRIPPABLES
let strippable = name.ends_with("_log")
|| name.ends_with("_wood")
|| name.ends_with("_stem")
|| name.ends_with("_hyphae")
|| name == "bamboo_block";
let stripped = format!("minecraft:stripped_{name}");
if strippable && self.res.assets.registry.default_state(&stripped).is_some() {
self.set_state_named(hit.pos, &stripped, &["axis"])?;
self.audio
.play("minecraft:item.axe.strip", Some(at(hit.pos)), 1.0, 1.0);
self.damage_held(1);
if item == "honeycomb" {
let registry = self.res.assets.registry;
let old = registry.state(clicked).cloned();
if let Some(waxed) = old.and_then(|old| self.res.transformers.waxed(registry, &old))
&& let Ok(state) = registry.resolve(&waxed)
{
self.level_set(hit.pos, state)?;
self.audio.play(
"minecraft:item.honeycomb.wax_on",
Some(at(hit.pos)),
1.0,
1.0,
);
if !self.creative {
self.consume_held();
}
return Ok(true);
}
}
@@ -7112,6 +7512,18 @@ impl Game<'_> {
Screen::WorldOptions => self.close_world_options(),
Screen::Chat => self.close_chat(),
},
KeyCode::Digit1
| KeyCode::Digit2
| KeyCode::Digit3
| KeyCode::Digit4
| KeyCode::Digit5
| KeyCode::Digit6
| KeyCode::Digit7
| KeyCode::Digit8
| KeyCode::Digit9
| KeyCode::KeyF
| KeyCode::KeyQ
if self.screen == Screen::Inventory && self.inventory_hotkey(key) => {}
KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(),
KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""),
// key.advancements.
@@ -7250,6 +7662,9 @@ impl Game<'_> {
self.world
.block_entities
.retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z));
self.world
.block_names
.retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z));
}
if !modified.is_empty()
&& let Err(e) = self
@@ -7367,6 +7782,7 @@ impl ApplicationHandler for Game<'_> {
}
if self.screen == Screen::Inventory {
self.loom_drag();
self.inventory_drag_move();
}
if self.dragging && self.screen == Screen::Options {
let _ = b;
@@ -7509,12 +7925,15 @@ impl ApplicationHandler for Game<'_> {
}
}
Screen::Inventory if pressed => {
self.click_inventory(button == MouseButton::Right);
self.inventory_press(button == MouseButton::Right);
if let Some(key) = self.container {
self.container_changed(key);
}
}
Screen::Inventory => self.loom_release(),
Screen::Inventory => {
self.inventory_release();
self.loom_release();
}
Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(),
Screen::Creative if pressed => {
self.click_creative(button == MouseButton::Right);
@@ -7803,6 +8222,7 @@ pub fn run() -> Result<()> {
let items = Items::load(&root, assets.registry, &facts)?;
eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32());
let recipes = Recipes::load(&root, &items)?;
let transformers = horizon_client::block_transform::Transformers::load(&root, assets.registry)?;
let biomes = Arc::new(Biomes::load(&root)?);
let environment = Environment::load(&root)?;
eprintln!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32());
@@ -7874,6 +8294,7 @@ pub fn run() -> Result<()> {
facts,
items,
recipes,
transformers,
biomes,
environment,
atlas,
@@ -7946,6 +8367,8 @@ pub fn run() -> Result<()> {
carried: None,
craft_grid: vec![None; 9],
craft_size: 2,
inv_drag: None,
last_inv_click: None,
container: None,
station: None,
potions: Default::default(),
@@ -8076,6 +8499,7 @@ pub fn run() -> Result<()> {
ender_open: None,
pending_shulker: HashMap::new(),
pending_banner: HashMap::new(),
pending_names: HashMap::new(),
recipe_ui: Default::default(),
mount_menu: Default::default(),
hook: None,
+2 -2
View File
@@ -777,8 +777,8 @@ impl Game<'_> {
}
// Saddles, horse armour and chests always drop.
let mut gear: Vec<&str> = Vec::new();
if m.extra.saddled {
gear.push("minecraft:saddle");
if let Some(saddle) = m.saddle_item() {
self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10);
}
// WitherBoss.dropCustomDeathLoot.
if m.species() == Species::Wither {
+2 -1
View File
@@ -578,7 +578,7 @@ impl Game<'_> {
(_, Some(1)) => m.extra.chest = Some(item.clone()),
(_, Some(2)) => m.extra.legs = Some(item.clone()),
(_, Some(3)) => m.extra.feet = Some(item.clone()),
("saddle", _) => m.extra.saddled = true,
("saddle", _) => m.set_saddle(Some(one.clone())),
_ => m.extra.head = Some(item.clone()),
}
// setGuaranteedDrop / setPersistenceRequired.
@@ -1155,6 +1155,7 @@ impl Game<'_> {
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
self.world.block_entities.insert(target, entity);
self.fill_placed_box([target.0, target.1, target.2], &stack);
self.name_placed_container([target.0, target.1, target.2], &stack);
}
let sounds = self.res.facts.get(state).sounds.clone();
self.audio.play(
@@ -746,6 +746,7 @@ impl Game<'_> {
batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX);
}
let grey = horizon_client::hud::rgba(64, 64, 64, 255);
let title = &self.container_title(title.to_owned());
let title_x = if screen == Screen::Hopper {
8.0
} else {
@@ -125,7 +125,7 @@ impl Game<'_> {
true,
horizon_world::level::flags::UPDATE_CLIENTS,
);
let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result);
let remainders = self.res.recipes.remainders(&recipe, &grid, 3);
self.crafter_eject(key, facing, result, &recipe);
for rest in remainders.into_iter().flatten() {
self.crafter_eject(key, facing, rest, &recipe);
@@ -270,7 +270,7 @@ impl Game<'_> {
256.0,
);
let grey = rgba(64, 64, 64, 255);
let title = self.translate("container.crafter", "Crafter");
let title = self.container_title(self.translate("container.crafter", "Crafter"));
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
+4 -7
View File
@@ -67,10 +67,7 @@ impl Game<'_> {
mob: m.id,
species,
columns,
saddle: m
.extra
.saddled
.then(|| ItemStack::new("minecraft:saddle", 1)),
saddle: m.saddle_item(),
armor: m
.extra
.head
@@ -137,18 +134,18 @@ impl Game<'_> {
let Some(index) = self.mount_mob_index(open.mob) else {
return;
};
let (saddle, armor) = (open.saddle.is_some(), open.armor.clone());
let (saddle, armor) = (open.saddle.clone(), open.armor.clone());
let items = open.items.clone();
let m = &mut self.mobs[index];
let at = m.center();
let sound = if saddle && !m.extra.saddled {
let sound = if saddle.is_some() && !m.extra.saddled {
Some("minecraft:entity.horse.saddle")
} else if armor.is_some() && m.extra.head.is_none() {
Some("minecraft:entity.horse.armor")
} else {
None
};
m.extra.saddled = saddle;
m.set_saddle(saddle);
if open.show_armor {
m.extra.head = armor.map(|a| a.item);
}
+4 -2
View File
@@ -45,13 +45,14 @@ impl Game<'_> {
}
/// `Pig` / `Strider.mobInteract`: saddle an adult, or ride a saddled one.
fn interact_steerable(&mut self, index: usize, item: &str) -> bool {
let held = self.inventory[self.selected].clone();
let m = &mut self.mobs[index];
if m.is_baby() || !m.alive() || Some(m.id) == self.riding {
return false;
}
let at = m.center();
if item == "minecraft:saddle" && !m.extra.saddled {
m.extra.saddled = true;
m.set_saddle(held);
let sound = if m.species() == Species::Strider {
"minecraft:entity.strider.saddle"
} else {
@@ -98,6 +99,7 @@ impl Game<'_> {
}
/// `AbstractHorse.mobInteract`. Returns whether the click was used.
pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool {
let held = self.inventory[self.selected].clone();
let m = &self.mobs[index];
let species = m.species();
if matches!(species, Species::Pig | Species::Strider) {
@@ -131,7 +133,7 @@ impl Game<'_> {
let at = m.center();
let tamed = m.extra.tame;
let sound = if item == "minecraft:saddle" && tamed && !m.extra.saddled {
m.extra.saddled = true;
m.set_saddle(held);
Some("minecraft:entity.horse.saddle")
} else if item.ends_with("_horse_armor")
&& species == Species::Horse
+98 -10
View File
@@ -68,6 +68,9 @@ pub(super) struct RecipeUi {
overlay: Option<Overlay>,
view: View,
view_key: u64,
/// Squeeze animations of new recipes: ticks left per button index and tab.
button_anim: Vec<(usize, f32)>,
tab_anim: Vec<(Tab, f32)>,
}
impl RecipeUi {
@@ -179,6 +182,11 @@ impl Game<'_> {
return;
}
self.ensure_book();
for id in recipes {
if !self.level.recipe_book.to_be_displayed.contains(id) {
self.level.recipe_book.to_be_displayed.push(id.clone());
}
}
let icon = self
.recipe_ui
.book
@@ -291,6 +299,71 @@ impl Game<'_> {
if self.recipe_ui.page >= pages.max(1) {
self.recipe_ui.page = 0;
}
self.start_new_recipe_animations(book_type);
}
/// `RecipeBookTabButton.startAnimation` and `RecipeButton.init`: tabs
/// holding a recipe still to be displayed squeeze, and the buttons of the
/// shown page squeeze once and clear their recipes' highlight.
fn start_new_recipe_animations(&mut self, book_type: BookType) {
if self.level.recipe_book.to_be_displayed.is_empty() {
return;
}
let Some(book) = self.recipe_ui.book.take() else {
return;
};
let unlocked = self.unlocked_recipes();
let filtering = self.book_filtering(book_type);
let (gw, gh) = self.book_grid();
let available = self.book_available(book_type);
let shown = |e: &Entry| {
(book_type != BookType::Crafting || e.fits(gw, gh))
&& (!filtering || available.can_craft(&e.requirements()))
};
let new = |level: &Self, e: &Entry| level.level.recipe_book.to_be_displayed.contains(&e.id);
let mut tabs = Vec::new();
for tab in self.recipe_ui.view.tabs.clone() {
if tab == Tab::Search {
continue;
}
let hit = book
.collections(&unlocked, book_type, tab)
.iter()
.flat_map(|c| c.entries.iter())
.any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i]));
if hit {
tabs.push((tab, 15.0));
}
}
self.recipe_ui.tab_anim = tabs;
let first = self.recipe_ui.page * 20;
let mut buttons = Vec::new();
let mut cleared = Vec::new();
for (n, button) in self
.recipe_ui
.view
.buttons
.iter()
.skip(first)
.take(20)
.enumerate()
{
let ids: Vec<&String> = button
.entries
.iter()
.map(|e| &book.entries[e.0].id)
.filter(|id| self.level.recipe_book.to_be_displayed.contains(*id))
.collect();
if !ids.is_empty() {
buttons.push((first + n, 15.0));
cleared.extend(ids.into_iter().cloned());
}
}
self.level
.recipe_book
.to_be_displayed
.retain(|id| !cleared.contains(id));
self.recipe_ui.button_anim = buttons;
self.recipe_ui.book = Some(book);
}
fn build_view(&mut self, ui: &RecipeUi, book_type: BookType) -> View {
let Some(book) = ui.book.as_ref() else {
@@ -329,9 +402,8 @@ impl Game<'_> {
continue;
}
if !query.is_empty()
&& !c.entries.iter().any(|&i| {
let e = &book.entries[i];
book.matches_search(e, &query, &self.res.names.item(&e.result.item))
&& !book.collection_matches(&c.entries, &query, &|stack| {
self.stack_tooltip(stack).into_iter().map(|l| l.0).collect()
})
{
continue;
@@ -972,26 +1044,30 @@ impl Game<'_> {
.tab
.filter(|t| tabs.contains(t))
.unwrap_or(Tab::Search);
let mut tab_icons = Vec::new();
let frame = self.frame_ticks;
for (n, tab) in tabs.iter().enumerate() {
let (x, y) = self.tab_pos(xo, yo, n);
let selected = *tab == current;
let name = if selected { "tab_selected" } else { "tab" };
let sx = if selected { x - 2.0 } else { x };
let start = batch.vertices.len();
batch.sprite(&self.res.atlas, &sprite(name), sx, y);
let (a, b) = tab.icons();
let shift = if selected { -2.0 } else { 0.0 };
match b {
Some(b) => {
tab_icons.push((a, x + 3.0 + shift, y + 5.0));
tab_icons.push((b, x + 14.0 + shift, y + 5.0));
self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0);
self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0);
}
None => tab_icons.push((a, x + 9.0 + shift, y + 5.0)),
None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0),
}
if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) {
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze);
entry.1 -= frame;
}
}
for (item, x, y) in tab_icons {
self.draw_item(batch, &ItemStack::new(item, 1), x, y);
}
self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0);
// Craftable filter.
let filtering = self.book_filtering(book_type);
let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0);
@@ -1019,6 +1095,7 @@ impl Game<'_> {
break;
};
let (x, y) = Self::button_pos(xo, yo, n);
let anim_start = batch.vertices.len();
let many = button.entries.len() > 1;
let name = match (button.craftable(), many) {
(true, true) => "slot_many_craftable",
@@ -1048,6 +1125,16 @@ impl Game<'_> {
offset -= 1.0;
}
self.draw_item_plain(batch, &stack, x + offset, y + offset);
if let Some(entry) = self
.recipe_ui
.button_anim
.iter_mut()
.find(|e| e.0 == first + n)
{
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze);
entry.1 -= self.frame_ticks;
}
if inside(cursor, x, y, 25.0, 25.0) && !overlay_open {
let mut lines = self.stack_tooltip(&stack);
if many {
@@ -1059,6 +1146,7 @@ impl Game<'_> {
tooltip = Some(lines);
}
}
self.recipe_ui.button_anim.retain(|e| e.1 > 0.0);
// Page arrows and number.
if pages > 1 {
let page_text = self
+7 -1
View File
@@ -1305,7 +1305,13 @@ impl Game<'_> {
);
}
}
let title = self.translate("container.brewing", "Brewing Stand");
let default = self.translate("container.brewing", "Brewing Stand");
let title = self
.station
.as_ref()
.and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2])))
.cloned()
.unwrap_or(default);
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
+44 -66
View File
@@ -11,6 +11,14 @@ impl Game<'_> {
/// Block-entity contents on removal: shulker boxes keep theirs for the
/// dropped box (`copy_components`), other containers spill them.
pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) {
if let Some(name) = self
.world
.block_names
.remove(&(pos[0], pos[1], pos[2]))
.filter(|_| !matches!(entity, BlockEntity::Banner(_)))
{
self.pending_names.insert(pos, (block.to_owned(), name));
}
if let BlockEntity::Banner(banner) = entity {
self.pending_banner.insert(pos, banner);
return;
@@ -41,6 +49,38 @@ impl Game<'_> {
stack.data_mut().container = contents;
}
}
/// The custom name a broken container drops with (`copy_components`).
pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
if self
.pending_names
.get(&pos)
.is_some_and(|(item, _)| **item == *stack.item)
&& let Some((_, name)) = self.pending_names.remove(&pos)
{
stack.data_mut().custom_name = Some(name);
}
}
/// A placed container takes the item's custom name.
pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) {
let key = (pos[0], pos[1], pos[2]);
if let Some(name) = stack.custom_name()
&& !matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Banner(_) | BlockEntity::Sign(_))
)
{
self.world.block_names.insert(key, name.to_owned());
}
}
/// The custom name of the open container, or its default title
/// (a double chest is named by whichever half has a name).
pub(super) fn container_title(&self, default: String) -> String {
self.container_parts()
.iter()
.find_map(|(key, _)| self.world.block_names.get(key))
.cloned()
.unwrap_or(default)
}
/// A placed shulker box takes the item's contents.
pub(super) fn fill_placed_box(&mut self, pos: [i32; 3], stack: &ItemStack) {
let Some(data) = stack.data() else { return };
@@ -234,7 +274,7 @@ impl Game<'_> {
_ if rows > 3 => ("container.chestDouble", "Large Chest"),
_ => ("container.chest", "Chest"),
};
self.translate(key, fallback)
self.container_title(self.translate(key, fallback))
}
/// `ContainerScreen` / `ShulkerBoxScreen`: the background with its
/// container rows, the title and the inventory label.
@@ -302,72 +342,10 @@ impl Game<'_> {
impl Game<'_> {
/// `quickMoveStack` of the open chest-like, hopper, dispenser or furnace
/// menu for a shift-click on `slot`; false when the menu has none.
/// menu for a shift-click on `slot`, run by the verified menu engine
/// (`horizon_client::menu`); false when the menu has none.
pub(super) fn container_quick_move(&mut self, slot: usize) -> bool {
let size = self.container_size();
let furnace = match self.container_kind() {
Some(BlockEntity::Chest(_)) => None,
Some(BlockEntity::Furnace(f)) => Some(f.kind),
_ => return false,
};
if slot >= 300 + size.max(3) {
return false;
}
let Some(mut stack) = self.slot_mut(slot).take() else {
return true;
};
let player: Vec<usize> = (9..36).chain(0..9).collect();
let hotbar_or_main = |slot: usize| -> Vec<usize> {
if slot < 9 {
(9..36).collect()
} else {
(0..9).collect()
}
};
match furnace {
None => {
if slot >= 300 {
self.move_to(&mut stack, &player, true);
} else {
let targets: Vec<usize> = (300..300 + size).collect();
self.move_to(&mut stack, &targets, false);
}
}
Some(kind) => {
// AbstractFurnaceMenu.quickMoveStack.
if slot >= 300 {
self.move_to(&mut stack, &player, slot == 302);
} else {
let smeltable = self.res.recipes.cook(kind.recipe_type(), &stack).is_some();
let fuel = self
.res
.items
.get(&stack.item)
.is_some_and(|i| i.fuel.is_some());
let moved = if smeltable {
self.move_to(&mut stack, &[300], false)
} else if fuel {
self.move_to(&mut stack, &[301], false)
} else {
false
};
if !moved && !smeltable && !fuel {
let other = hotbar_or_main(slot);
self.move_to(&mut stack, &other, false);
}
if let Some(BlockEntity::Furnace(f)) = self
.container
.and_then(|k| self.world.block_entities.get_mut(&k))
{
f.cooking_timer = 0;
}
}
}
}
if stack.count > 0 {
*self.slot_mut(slot) = Some(stack);
}
true
self.menu_click(Some(slot), 0, horizon_client::menu::Input::QuickMove)
}
}
+8
View File
@@ -278,6 +278,14 @@ impl HudBatch {
/// Clip the quads drawn since `start` to `[x0, x1) x [y0, y1)` (the
/// GUI scissor): axis-aligned quads are cut with their UVs, others are
/// kept or dropped by their centre.
/// Scale the vertices pushed since `start` about `(cx, cy)` (a GUI pose
/// matrix of translate, scale, translate back).
pub fn scale_since(&mut self, start: usize, cx: f32, cy: f32, sx: f32, sy: f32) {
for v in &mut self.vertices[start..] {
v.pos[0] = cx + (v.pos[0] - cx) * sx;
v.pos[1] = cy + (v.pos[1] - cy) * sy;
}
}
pub fn clip_since(&mut self, start: usize, x0: f32, y0: f32, x1: f32, y1: f32) {
let quads: Vec<[HudVertex; 6]> = self.vertices[start..].as_chunks::<6>().0.to_vec();
self.vertices.truncate(start);
+279 -67
View File
@@ -44,6 +44,18 @@ pub struct StackData {
pub ominous_banner: bool,
/// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0).
pub ominous_amplifier: Option<u8>,
/// `minecraft:dyed_color` (leather armour, wolf armour, ... as RGB).
pub dyed_color: Option<i32>,
/// `minecraft:firework_explosion` (a firework star).
pub firework_explosion: Option<crate::particles::FireworkExplosion>,
/// `minecraft:pot_decorations`: back, left, right, front sherds.
pub pot_decorations: Option<Box<[Option<ItemStack>; 4]>>,
/// `minecraft:bundle_contents`.
pub bundle_contents: Vec<ItemStack>,
/// `minecraft:suspicious_stew_effects`: (effect id, duration).
pub stew_effects: Vec<(Arc<str>, i32)>,
/// `minecraft:map_post_processing`: 0 lock, 1 scale.
pub map_post_processing: Option<u8>,
}
/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers.
pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
@@ -243,6 +255,151 @@ fn read_text(t: &Tag) -> Option<String> {
}
}
/// A `FireworkExplosion` as vanilla's codec writes it (defaults omitted).
fn explosion_tag(e: &crate::particles::FireworkExplosion) -> Tag {
let colors = |c: &[u32]| Tag::List(c.iter().map(|c| Tag::Int(*c as i32)).collect());
let mut fields = vec![("shape", Tag::String(e.shape.name().into()))];
if !e.colors.is_empty() {
fields.push(("colors", colors(&e.colors)));
}
if !e.fade.is_empty() {
fields.push(("fade_colors", colors(&e.fade)));
}
if e.trail {
fields.push(("has_trail", Tag::Byte(1)));
}
if e.twinkle {
fields.push(("has_twinkle", Tag::Byte(1)));
}
Tag::compound(fields)
}
fn explosion_from(e: &Tag) -> crate::particles::FireworkExplosion {
let ints = |t: Option<&Tag>| match t {
Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(),
Some(Tag::List(v)) => v.iter().filter_map(int).map(|c| c as u32).collect(),
_ => Vec::new(),
};
crate::particles::FireworkExplosion {
shape: crate::particles::FireworkShape::from_name(
e.get("shape")
.and_then(string)
.as_deref()
.map_or("small_ball", |s| s.strip_prefix("minecraft:").unwrap_or(s)),
),
colors: ints(e.get("colors")),
fade: ints(e.get("fade_colors")),
trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0,
twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0,
}
}
/// An `ItemStackTemplate`: `{id, count?, components?}`.
fn template_tag(stack: &ItemStack) -> Tag {
let mut entries = vec![("id", Tag::String((&*stack.item).into()))];
if stack.count != 1 {
entries.push(("count", Tag::Int(stack.count as i32)));
}
if let Some(components) = encode_components(stack) {
entries.push(("components", components));
}
Tag::compound(entries)
}
/// The pot prototype's decorations: a brick on every side.
pub fn all_bricks(sides: &[Option<ItemStack>; 4]) -> bool {
sides.iter().all(|s| {
s.as_ref()
.is_some_and(|s| &*s.item == "minecraft:brick" && s.count == 1 && s.extra.is_none())
})
}
fn template_from(tag: &Tag) -> Option<ItemStack> {
match tag {
Tag::String(id) => Some(ItemStack::new(&id.to_string_lossy(), 1)),
_ => {
let id = tag.get("id").and_then(string)?;
let (damage, extra) = decode_components(tag.get("components"));
Some(ItemStack {
item: Arc::from(id.as_str()),
count: tag.get("count").and_then(int).unwrap_or(1).max(1) as u32,
damage,
extra,
})
}
}
}
/// Sorted-key, type-annotated text of a tag (the differential harnesses
/// print the same form from the vanilla side).
pub fn canon_tag(tag: &Tag) -> String {
fn list(out: &mut String, prefix: &str, items: impl Iterator<Item = String>) {
out.push_str(prefix);
out.push_str(&items.collect::<Vec<_>>().join(","));
out.push(']');
}
fn go(tag: &Tag, out: &mut String) {
use std::fmt::Write as _;
match tag {
Tag::End => {}
Tag::Byte(v) => write!(out, "{v}b").unwrap(),
Tag::Short(v) => write!(out, "{v}s").unwrap(),
Tag::Int(v) => write!(out, "{v}").unwrap(),
Tag::Long(v) => write!(out, "{v}L").unwrap(),
Tag::Float(v) => write!(out, "{}f", f32::from_bits(*v)).unwrap(),
Tag::Double(v) => write!(out, "{}d", f64::from_bits(*v)).unwrap(),
Tag::String(s) => write!(
out,
"\"{}\"",
s.to_string_lossy()
.replace('\\', "\\\\")
.replace('"', "\\\"")
)
.unwrap(),
Tag::ByteArray(v) => list(out, "[B;", v.iter().map(|b| (*b as i8).to_string())),
Tag::IntArray(v) => list(out, "[I;", v.iter().map(i32::to_string)),
Tag::LongArray(v) => list(out, "[L;", v.iter().map(i64::to_string)),
Tag::List(items) => {
out.push('[');
for (i, t) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
go(t, out);
}
out.push(']');
}
Tag::Compound(map) => {
let mut keys: Vec<(String, &Tag)> =
map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
keys.sort_by(|a, b| a.0.cmp(&b.0));
out.push('{');
for (i, (k, v)) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&k);
out.push(':');
go(v, out);
}
out.push('}');
}
}
}
let mut out = String::new();
go(tag, &mut out);
out
}
/// `canon_tag` of a stack as `ItemStack.CODEC` writes it; "-" for none.
pub fn canon_stack(stack: Option<&ItemStack>) -> String {
stack.map_or_else(
|| "-".to_owned(),
|s| canon_tag(&crate::save::item_to_nbt(s)),
)
}
/// The stack of an SNBT `ItemStack.CODEC` compound; None for "-".
pub fn parse_stack(snbt: &str) -> Result<Option<ItemStack>, String> {
if snbt == "-" {
return Ok(None);
}
let (tag, _) = horizon_world::nbt::parse_snbt(snbt)?;
Ok(crate::save::item_from_nbt(&tag))
}
/// The `components` compound for a stack, or None when every component is default.
pub fn encode_components(stack: &ItemStack) -> Option<Tag> {
components_tag(stack.damage, stack.data())
@@ -317,40 +474,73 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
.collect();
entries.push((
"minecraft:written_book_content",
Tag::compound([
("title", raw(Tag::String(w.title.as_str().into()))),
("author", Tag::String(w.author.as_str().into())),
("generation", Tag::Int(i32::from(w.generation))),
("pages", Tag::List(pages)),
("resolved", Tag::Byte(1)),
]),
Tag::compound({
let mut fields = vec![
("title", raw(Tag::String(w.title.as_str().into()))),
("author", Tag::String(w.author.as_str().into())),
("pages", Tag::List(pages)),
];
if w.generation != 0 {
fields.push(("generation", Tag::Int(i32::from(w.generation))));
}
fields
}),
));
}
if let Some((flight, explosions)) = &d.fireworks {
let list = explosions
.iter()
.map(|e| {
Tag::compound([
("shape", Tag::String(e.shape.name().into())),
(
"colors",
Tag::IntArray(e.colors.iter().map(|c| *c as i32).collect()),
),
(
"fade_colors",
Tag::IntArray(e.fade.iter().map(|c| *c as i32).collect()),
),
("has_trail", Tag::Byte(i8::from(e.trail))),
("has_twinkle", Tag::Byte(i8::from(e.twinkle))),
])
})
.collect();
let mut fields = Vec::new();
if *flight != 0 {
fields.push(("flight_duration", Tag::Byte(*flight as i8)));
}
if !explosions.is_empty() {
fields.push((
"explosions",
Tag::List(explosions.iter().map(explosion_tag).collect()),
));
}
entries.push(("minecraft:fireworks", Tag::compound(fields)));
}
if let Some(e) = &d.firework_explosion {
entries.push(("minecraft:firework_explosion", explosion_tag(e)));
}
if let Some(color) = d.dyed_color {
entries.push(("minecraft:dyed_color", Tag::Int(color)));
}
if let Some(sides) = &d.pot_decorations {
let mut sherds = Vec::new();
for (name, side) in ["back", "left", "right", "front"].iter().zip(sides.iter()) {
if let Some(stack) = side {
sherds.push((*name, template_tag(stack)));
}
}
entries.push(("minecraft:pot_decorations", Tag::compound(sherds)));
}
if !d.bundle_contents.is_empty() {
entries.push((
"minecraft:fireworks",
Tag::compound([
("flight_duration", Tag::Byte(*flight as i8)),
("explosions", Tag::List(list)),
]),
"minecraft:bundle_contents",
Tag::List(d.bundle_contents.iter().map(template_tag).collect()),
));
}
if !d.stew_effects.is_empty() {
entries.push((
"minecraft:suspicious_stew_effects",
Tag::List(
d.stew_effects
.iter()
.map(|(id, duration)| {
Tag::compound([
("id", Tag::String((&**id).into())),
("duration", Tag::Int(*duration)),
])
})
.collect(),
),
));
}
if let Some(mode) = d.map_post_processing {
entries.push((
"minecraft:map_post_processing",
Tag::String(if mode == 0 { "lock" } else { "scale" }.into()),
));
}
if !d.charged.is_empty() {
@@ -399,7 +589,7 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
.map(|(slot, stack)| {
Tag::compound([
("slot", Tag::Int(i32::from(*slot))),
("item", crate::save::item_to_nbt(stack)),
("item", template_tag(stack)),
])
})
.collect();
@@ -456,36 +646,54 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
_ => Vec::new(),
},
}),
fireworks: c.get("minecraft:fireworks").map(|f| {
let flight = f
.get("flight_duration")
.and_then(int)
.unwrap_or(0)
.clamp(0, 255) as u8;
let ints = |t: Option<&Tag>| match t {
Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(),
_ => Vec::new(),
};
let explosions = match f.get("explosions") {
Some(Tag::List(list)) => list
.iter()
.map(|e| crate::particles::FireworkExplosion {
shape: crate::particles::FireworkShape::from_name(
e.get("shape")
.and_then(string)
.as_deref()
.unwrap_or("small_ball"),
),
colors: ints(e.get("colors")),
fade: ints(e.get("fade_colors")),
trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0,
twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0,
})
.collect(),
_ => Vec::new(),
};
(flight, explosions)
}),
fireworks: c
.get("minecraft:fireworks")
.map(|f| {
let flight = f
.get("flight_duration")
.and_then(int)
.unwrap_or(0)
.clamp(0, 255) as u8;
let explosions = match f.get("explosions") {
Some(Tag::List(list)) => list.iter().map(explosion_from).collect(),
_ => Vec::new(),
};
(flight, explosions)
})
.filter(|(flight, explosions)| !(*flight == 1 && explosions.is_empty())),
firework_explosion: c.get("minecraft:firework_explosion").map(explosion_from),
dyed_color: c
.get("minecraft:dyed_color")
.and_then(int)
.map(|v| v as i32),
pot_decorations: c
.get("minecraft:pot_decorations")
.map(|p| {
let side = |name: &str| p.get(name).and_then(template_from);
Box::new([side("back"), side("left"), side("right"), side("front")])
})
.filter(|sides| !all_bricks(sides)),
bundle_contents: match c.get("minecraft:bundle_contents") {
Some(Tag::List(list)) => list.iter().filter_map(template_from).collect(),
_ => Vec::new(),
},
stew_effects: match c.get("minecraft:suspicious_stew_effects") {
Some(Tag::List(list)) => list
.iter()
.filter_map(|e| {
Some((
Arc::from(e.get("id").and_then(string)?.as_str()),
e.get("duration").and_then(int).unwrap_or(160) as i32,
))
})
.collect(),
_ => Vec::new(),
},
map_post_processing: match c.get("minecraft:map_post_processing") {
Some(Tag::String(s)) => Some(u8::from(s.to_string_lossy() != "lock")),
Some(t) => int(t).map(|v| v.clamp(0, 1) as u8),
None => None,
},
charged: match c.get("minecraft:charged_projectiles") {
Some(Tag::List(list)) => list.iter().filter_map(crate::save::item_from_nbt).collect(),
_ => Vec::new(),
@@ -496,17 +704,21 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
.filter_map(|e| {
Some((
e.get("slot").and_then(int)?.clamp(0, 255) as u8,
crate::save::item_from_nbt(e.get("item")?)?,
template_from(e.get("item")?)?,
))
})
.collect(),
_ => Vec::new(),
},
ominous_banner: matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.first().is_some_and(|l|
l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus"))
),
ominous_banner: c
.get("minecraft:item_name")
.and_then(|n| n.get("translate"))
.and_then(string)
.as_deref()
== Some("block.minecraft.ominous_banner")
&& matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.len() == OMINOUS_LAYERS.len()),
ominous_amplifier: c
.get("minecraft:ominous_bottle_amplifier")
.and_then(int)
+31 -2
View File
@@ -60,7 +60,22 @@ pub struct ItemInfo {
pub equip_sound: Option<String>,
/// `jukebox_playable`: the jukebox song it plays.
pub jukebox_song: Option<String>,
/// `crafting_remainder`: what stays in the grid when the item is used in a recipe.
pub crafting_remainder: Option<String>,
/// `dye`: the dye colour name (dyes, and anything else with the component).
pub dye: Option<String>,
/// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks.
pub block_transformer: Option<String>,
}
/// `Item.Properties.craftRemainder` (not a data component, so not in the
/// default-component report): what an item leaves in the grid when crafted with.
pub const CRAFT_REMAINDERS: [(&str, &str); 5] = [
("minecraft:water_bucket", "minecraft:bucket"),
("minecraft:lava_bucket", "minecraft:bucket"),
("minecraft:milk_bucket", "minecraft:bucket"),
("minecraft:dragon_breath", "minecraft:glass_bottle"),
("minecraft:honey_bottle", "minecraft:glass_bottle"),
];
/// A reduction of `blocks_attacks.damage_reductions`.
#[derive(Clone, Debug)]
pub struct BlockReduction {
@@ -264,8 +279,6 @@ fn entity_spec(tags: &HashMap<String, HashSet<String>>, spec: &str) -> HashSet<S
}
impl Items {
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new();
for (i, s) in facts.states.iter().enumerate() {
let default = registry.default_state(&s.name);
@@ -275,6 +288,16 @@ impl Items {
.or_insert(BlockStateId(i as u32));
}
}
Self::load_with(root, &block_for_item)
}
/// Every item's default components and the tags, without the block <->
/// item mapping (for headless tools that never place blocks).
pub fn catalog(root: &Path) -> Result<Self> {
Self::load_with(root, &HashMap::new())
}
fn load_with(root: &Path, block_for_item: &HashMap<&str, BlockStateId>) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let entity_tags = load_tags(root, "entity_type")?;
let mut items = HashMap::new();
let mut order = Vec::new();
@@ -352,6 +375,12 @@ impl Items {
.as_str()
.map(str::to_owned),
jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned),
dye: c["minecraft:dye"].as_str().map(str::to_owned),
block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned),
crafting_remainder: CRAFT_REMAINDERS
.iter()
.find(|(item, _)| *item == name)
.map(|(_, rest)| (*rest).to_owned()),
use_speed: c["minecraft:use_effects"]["speed_multiplier"]
.as_f64()
.unwrap_or(0.2) as f32,
+3
View File
@@ -11,9 +11,11 @@ pub mod banner;
pub mod biome;
pub mod block_entity_nbt;
pub mod block_entity_render;
pub mod block_transform;
pub mod blocks;
pub mod bossbar;
pub mod brewing;
pub mod cauldron;
pub mod chat;
pub mod chunk;
pub mod clock;
@@ -51,6 +53,7 @@ pub mod lan;
pub mod landing;
pub mod lang;
pub mod light;
pub mod menu;
pub mod merchant;
pub mod mesher;
pub mod mobs;
File diff suppressed because it is too large Load Diff
+22
View File
@@ -452,6 +452,9 @@ pub struct Extra {
/// `Mob.canPickUpLoot` (also lets dispensers equip it).
pub pick_up_loot: bool,
pub saddled: bool,
/// The saddle's components (name, enchantments...) when it is not a bare
/// one; `saddled` stays the gameplay flag.
pub saddle_stack: Option<crate::items::ItemStack>,
pub chested: bool,
/// The chest contents of a donkey or mule (15 slots).
pub items: Vec<Option<crate::items::ItemStack>>,
@@ -1222,3 +1225,22 @@ pub fn render_model(
}
}
}
impl Mob {
/// The saddle worn, with its components.
pub fn saddle_item(&self) -> Option<crate::items::ItemStack> {
self.extra.saddled.then(|| {
self.extra
.saddle_stack
.clone()
.unwrap_or_else(|| crate::items::ItemStack::new("minecraft:saddle", 1))
})
}
/// Wear (or take off) a saddle stack, keeping its components.
pub fn set_saddle(&mut self, saddle: Option<crate::items::ItemStack>) {
self.extra.saddled = saddle.is_some();
self.extra.saddle_stack = saddle
.map(|s| crate::items::ItemStack { count: 1, ..s })
.filter(|s| s.damage != 0 || s.extra.is_some());
}
}
+71 -25
View File
@@ -280,14 +280,27 @@ impl Book {
ingredients,
result,
} => (Display::Shapeless(ingredients.clone()), result),
Recipe::Special(_) => continue,
// Custom recipes are never learnable; the others show one
// display per material count (TransmuteRecipe.display).
Recipe::Special(special) => {
for (display, result) in special.book_displays() {
entries.push(Entry {
id: format!("minecraft:{name}"),
category: crafting_category(&category),
group: group(&grp),
display,
result,
});
}
continue;
}
};
entries.push(Entry {
id: format!("minecraft:{name}"),
category: crafting_category(&category),
group: group(&grp),
display,
result: result.clone(),
result: result.create(),
});
}
for c in &recipes.cooking {
@@ -376,24 +389,33 @@ impl Book {
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
items
}
/// `RecipeCollection` search: the result's name or registry path, or
/// `@namespace`.
pub fn matches_search(&self, entry: &Entry, query: &str, name: &str) -> bool {
/// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a
/// `FullTextSearchTree`): without a colon the text must occur in a
/// tooltip line of a result item of the collection; `namespace:path`
/// needs the namespace in a result id and the path in an id or a line.
pub fn collection_matches(
&self,
entries: &[usize],
query: &str,
tooltip: &dyn Fn(&ItemStack) -> Vec<String>,
) -> bool {
let query = query.to_lowercase();
if let Some(ns) = query.strip_prefix('@') {
return entry
.result
.item
.split(':')
.next()
.is_some_and(|n| n.starts_with(ns));
}
name.to_lowercase().contains(&query)
|| entry
.result
.item
.trim_start_matches("minecraft:")
.contains(&query)
let results: Vec<&ItemStack> = entries.iter().map(|&i| &self.entries[i].result).collect();
let in_lines = |text: &str| {
results
.iter()
.any(|r| tooltip(r).iter().any(|l| l.to_lowercase().contains(text)))
};
let Some((namespace, path)) = query.split_once(':') else {
return in_lines(&query);
};
let (namespace, path) = (namespace.trim(), path.trim());
let id = |r: &&ItemStack| {
let (ns, p) = r.item.split_once(':').unwrap_or(("minecraft", &r.item));
(ns.to_lowercase(), p.to_lowercase())
};
results.iter().any(|r| id(r).0.contains(namespace))
&& (results.iter().any(|r| id(r).1.contains(path)) || in_lines(path))
}
}
@@ -524,6 +546,8 @@ pub struct Settings {
pub filtering: [bool; 4],
/// Unlocked recipe ids (`recipes`).
pub recipes: Vec<String>,
/// Recipes not yet shown in the book (`toBeDisplayed`): they animate once.
pub to_be_displayed: Vec<String>,
}
impl Settings {
pub fn read(tag: Option<&Tag>) -> Self {
@@ -535,18 +559,21 @@ impl Settings {
s.open[b.index()] = flag(open);
s.filtering[b.index()] = flag(filter);
}
if let Some(Tag::List(list)) = tag.get("recipes") {
s.recipes = list
let ids = |key: &str| match tag.get(key) {
Some(Tag::List(list)) => list
.iter()
.filter_map(|t| match t {
Tag::String(id) => Some(id.to_string_lossy()),
_ => None,
})
.collect();
}
.collect(),
_ => Vec::new(),
};
s.recipes = ids("recipes");
s.to_be_displayed = ids("toBeDisplayed");
s
}
/// The compound written to the player file; `toBeDisplayed` stays empty.
/// The compound written to the player file.
pub fn write(&self) -> Tag {
let mut entries: Vec<(&str, Tag)> = Vec::new();
for b in BookType::ALL {
@@ -558,7 +585,7 @@ impl Settings {
Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect())
};
entries.push(("recipes", list(&self.recipes)));
entries.push(("toBeDisplayed", Tag::List(Vec::new())));
entries.push(("toBeDisplayed", list(&self.to_be_displayed)));
Tag::compound(entries)
}
}
@@ -672,6 +699,25 @@ mod tests {
assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1);
}
#[test]
fn search_reads_tooltip_lines_and_ids() {
let book = Book {
entries: vec![Entry {
id: "minecraft:stick".into(),
category: Category::CraftingMisc,
group: None,
display: Display::Shapeless(Vec::new()),
result: ItemStack::new("minecraft:stick", 4),
}],
order: HashMap::new(),
};
let lines = |s: &ItemStack| vec![format!("Item {}", s.item), "Stick".to_owned()];
assert!(book.collection_matches(&[0], "STI", &lines));
// Plain text searches tooltips only, not the registry path.
assert!(!book.collection_matches(&[0], "stick:", &lines));
assert!(book.collection_matches(&[0], "minecraft:stic", &lines));
assert!(!book.collection_matches(&[0], "other:stick", &lines));
}
#[test]
fn settings_round_trip() {
let mut s = Settings::default();
s.open[BookType::Furnace.index()] = true;
+9 -1
View File
@@ -729,7 +729,12 @@ pub fn encode_with(
.iter()
.map(|(p, e)| {
let block = block_name(p);
let current = encode_block_entity(*p, e, &block);
let mut current = encode_block_entity(*p, e, &block);
if let Some((_, name)) = chunk.block_names.iter().find(|(q, _)| q == p)
&& let Tag::Compound(map) = &mut current
{
map.insert("CustomName".into(), string(name));
}
let source = extras
.and_then(|x| x.block_entity_sources.iter().find(|(q, _)| q == p))
.map(|(_, tag)| tag)
@@ -965,6 +970,9 @@ pub fn decode_with(
for e in entities {
match decode_block_entity(e) {
Some(be) => {
if let Some(name) = text(e.get("CustomName")) {
chunk.block_names.push((be.0, name));
}
extras.block_entity_sources.push((be.0, e.clone()));
chunk.block_entities.push(be);
}
+3
View File
@@ -361,6 +361,9 @@ impl Streaming {
world
.block_entities
.extend(std::mem::take(&mut chunk.block_entities));
world
.block_names
.extend(std::mem::take(&mut chunk.block_names));
let entities = std::mem::take(&mut chunk.entities);
if !entities.is_empty() {
world.loaded_entities.push(((chunk.x, chunk.z), entities));
+3
View File
@@ -26,6 +26,8 @@ pub struct World {
/// Chunks changed since the last save.
pub modified: HashSet<(i32, i32)>,
pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>,
/// `BaseContainerBlockEntity.name`: custom names of container block entities.
pub block_names: HashMap<(i32, i32, i32), String>,
/// States (by id) whose writes are recorded in `watched_writes` (sculk
/// blocks, which need a block entity).
pub watched: Vec<bool>,
@@ -114,6 +116,7 @@ impl World {
loaded_entities: Vec::new(),
modified: HashSet::new(),
block_entities: HashMap::new(),
block_names: HashMap::new(),
watched: Vec::new(),
watched_writes: Vec::new(),
inhabited: HashMap::new(),
@@ -0,0 +1,132 @@
package dev.horizonlab.parity;
import java.lang.reflect.Field;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.*;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.RegistryOps;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
/**
* Shared set-up for the interaction/inventory parity oracles: the vanilla data
* pack loaded into registries (as the server does), an NBT registry ops, a
* stand-in ServerLevel that only answers registryAccess, and canonical text
* for item stacks and NBT so both sides print comparable lines.
*/
public final class ParityData {
public static HolderLookup.Provider lookup;
public static RegistryAccess access;
public static RegistryOps<Tag> ops;
public static ServerLevel level;
public static void init() throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var repo = ServerPacksSource.createVanillaTrustedRepository();
repo.reload();
repo.setSelected(List.of("vanilla"));
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
var layers = RegistryLayer.createRegistryAccess();
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
lookup = loaded.lookupWithUpdatedTags();
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
staticTags.forEach(Registry.PendingTags::apply);
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
access = loaded.layers().compositeAccess();
ops = RegistryOps.create(NbtOps.INSTANCE, lookup);
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Object unsafe = unsafeField.get(null);
level = (ServerLevel) unsafe.getClass().getMethod("allocateInstance", Class.class).invoke(unsafe, ServerLevel.class);
Field registryAccess = Level.class.getDeclaredField("registryAccess");
registryAccess.setAccessible(true);
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, registryAccess);
unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, level, offset, access);
}
/** "-" is the empty stack; otherwise ItemStack.CODEC over SNBT. */
public static ItemStack stack(String snbt) throws Exception {
if (snbt.equals("-")) return ItemStack.EMPTY;
Tag tag = TagParser.parseCompoundFully(snbt);
return ItemStack.CODEC.parse(ops, tag).getOrThrow();
}
public static String canon(ItemStack stack) {
if (stack == null || stack.isEmpty()) return "-";
Tag tag = ItemStack.CODEC.encodeStart(ops, stack).getOrThrow();
return canon(tag);
}
/** Sorted-key, type-annotated text of an NBT tag. */
public static String canon(Tag tag) {
StringBuilder out = new StringBuilder();
canon(tag, out);
return out.toString();
}
private static void canon(Tag tag, StringBuilder out) {
switch (tag) {
case ByteTag t -> out.append(t.value()).append('b');
case ShortTag t -> out.append(t.value()).append('s');
case IntTag t -> out.append(t.value());
case LongTag t -> out.append(t.value()).append('L');
case FloatTag t -> out.append(t.value()).append('f');
case DoubleTag t -> out.append(t.value()).append('d');
case StringTag t -> out.append('"').append(t.value().replace("\\", "\\\\").replace("\"", "\\\"")).append('"');
case ByteArrayTag t -> {
out.append("[B;");
byte[] a = t.getAsByteArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case IntArrayTag t -> {
out.append("[I;");
int[] a = t.getAsIntArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case LongArrayTag t -> {
out.append("[L;");
long[] a = t.getAsLongArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case ListTag t -> {
out.append('[');
for (int i = 0; i < t.size(); i++) {
if (i > 0) out.append(',');
canon(t.get(i), out);
}
out.append(']');
}
case CompoundTag t -> {
out.append('{');
boolean first = true;
for (String key : new TreeSet<>(t.keySet())) {
if (!first) out.append(',');
first = false;
out.append(key).append(':');
canon(t.get(key), out);
}
out.append('}');
}
default -> throw new IllegalStateException(tag.toString());
}
}
}
@@ -0,0 +1,118 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.core.component.BlockTransformer;
/**
* Original oracle: the data-driven axe/hoe/shovel BlockTransformer entries.
* "dump" lists every block state; a case line "transformer TAB face TAB
* clicked TAB above" (states as "name|prop=value,...") prints the first
* transform that yields a state and its settings, as BlockTransformer.transformBlock
* would pick it.
*/
public final class VanillaBlockTransformerOracle {
static String describe(BlockState state) {
StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|');
List<Property<?>> props = new ArrayList<>(state.getProperties());
props.sort(Comparator.comparing(Property::getName));
boolean first = true;
for (Property<?> p : props) {
out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p));
first = false;
}
return out.toString();
}
@SuppressWarnings({"unchecked", "rawtypes"})
static String name(BlockState state, Property p) {
return p.getName(state.getValue(p));
}
@SuppressWarnings({"unchecked", "rawtypes"})
static BlockState parse(String text) {
String[] parts = text.split("\\|", -1);
Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0]));
BlockState state = block.defaultBlockState();
if (!parts[1].isEmpty()) {
for (String kv : parts[1].split(",")) {
String[] pair = kv.split("=");
Property p = block.getStateDefinition().getProperty(pair[0]);
state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow());
}
}
return state;
}
static LevelAccessor level(BlockState clicked, BlockState above) {
return (LevelAccessor) Proxy.newProxyInstance(LevelAccessor.class.getClassLoader(), new Class<?>[]{LevelAccessor.class}, (proxy, method, args) -> {
if (method.getName().equals("getBlockState")) {
BlockPos pos = (BlockPos) args[0];
return pos.getY() == 0 ? clicked : pos.getY() == 1 && pos.getX() == 0 && pos.getZ() == 0 ? above : net.minecraft.world.level.block.Blocks.STONE.defaultBlockState();
}
throw new UnsupportedOperationException(method.getName());
});
}
public static void main(String[] args) throws Exception {
ParityData.init();
if (args[0].equals("dump")) {
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
for (Block block : BuiltInRegistries.BLOCK) {
for (BlockState state : block.getStateDefinition().getPossibleStates()) out.println(describe(state));
}
}
return;
}
var registry = ParityData.access.lookupOrThrow(Registries.BLOCK_TRANSFORMER);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
String[] f = line.split("\t", -1);
try {
if (f[0].equals("honeycomb")) {
out.println(net.minecraft.world.item.HoneycombItem.getWaxed(parse(f[2])).map(VanillaBlockTransformerOracle::describe).orElse("none"));
continue;
}
var transformer = registry.getOrThrow(ResourceKey.create(Registries.BLOCK_TRANSFORMER, Identifier.parse(f[0]))).value();
Direction face = Direction.byName(f[1]);
BlockState clicked = parse(f[2]);
LevelAccessor level = level(clicked, parse(f[3]));
String result = "none";
int index = 0;
for (var data : transformer.transforms()) {
if (!data.disallowedFaces().contains(face)) {
BlockState state = data.blockStateProvider().value().getOptionalState(level, RandomSource.create(0L), BlockPos.ZERO);
if (state != null) {
result = index + "\t" + describe(state) + "\t" + BuiltInRegistries.SOUND_EVENT.getKey(data.sound().value())
+ "\t" + data.particle().name().toLowerCase() + "\t"
+ data.loot().map(k -> k.identifier().toString()).orElse("-") + "\t" + data.dropStrategy().name().toLowerCase()
+ "\t" + data.updateFromNeighbors() + "\t" + data.transformType().name().toLowerCase() + "\t" + data.consumeOnUse()
+ "\t" + data.itemDamagePerUse();
break;
}
}
index++;
}
out.println(result);
} catch (Throwable e) {
out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage());
}
}
}
}
}
@@ -0,0 +1,168 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.EntityEquipment;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.AbstractCauldronBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
/**
* Original oracle: a cauldron's useItemOn (CauldronInteractions) with a
* recording stand-in level and player. Each case line is JSON: cauldron state
* ("name|prop=value"), the held stack, creative, whether water is above. The
* output line lists the result, block writes, sounds, the final inventory and
* drops.
*/
public final class VanillaCauldronOracle {
static Object unsafe;
static java.lang.reflect.Method allocate;
static final List<String> events = new ArrayList<>();
static boolean underWater;
@SuppressWarnings("unchecked")
static <T> T make(Class<T> type) {
try {
return (T) allocate.invoke(unsafe, type);
} catch (Exception e) {
throw new AssertionError(e);
}
}
static void set(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
f.set(target, value);
}
static String describe(BlockState state) {
StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|');
List<Property<?>> props = new ArrayList<>(state.getProperties());
props.sort(Comparator.comparing(Property::getName));
boolean first = true;
for (Property<?> p : props) {
out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p));
first = false;
}
return out.toString();
}
@SuppressWarnings({"unchecked", "rawtypes"})
static String name(BlockState state, Property p) {
return p.getName(state.getValue(p));
}
@SuppressWarnings({"unchecked", "rawtypes"})
static BlockState parse(String text) {
String[] parts = text.split("\\|", -1);
Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0]));
BlockState state = block.defaultBlockState();
if (!parts[1].isEmpty()) {
for (String kv : parts[1].split(",")) {
String[] pair = kv.split("=");
Property p = block.getStateDefinition().getProperty(pair[0]);
state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow());
}
}
return state;
}
static final class World extends ServerLevel {
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@Override public boolean isClientSide() { return false; }
@Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int limit) { events.add("set " + describe(state)); return true; }
@Override public FluidState getFluidState(BlockPos pos) { return underWater ? Fluids.WATER.defaultFluidState() : Fluids.EMPTY.defaultFluidState(); }
@Override public void playSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) {
events.add("sound " + BuiltInRegistries.SOUND_EVENT.getKey(s));
}
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, net.minecraft.world.phys.Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
}
static final class FakePlayer extends ServerPlayer {
boolean creative;
Inventory inv;
FakePlayer() {
super(null, null, null, null);
}
@Override public Inventory getInventory() { return inv; }
@Override public boolean hasInfiniteMaterials() { return creative; }
@Override public boolean isCreative() { return creative; }
@Override public void setItemInHand(InteractionHand hand, ItemStack stack) { inv.setItem(0, stack); }
@Override public ItemStack getItemInHand(InteractionHand hand) { return inv.getItem(0); }
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { }
@Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) {
if (!stack.isEmpty()) events.add("drop " + ParityData.canon(stack));
return null;
}
}
public static void main(String[] args) throws Exception {
ParityData.init();
var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = field.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
try {
events.clear();
underWater = f.get("under_water").getAsBoolean();
var world = make(World.class);
var player = make(FakePlayer.class);
player.creative = f.get("creative").getAsBoolean();
player.inv = new Inventory(player, new EntityEquipment());
for (var other : f.getAsJsonArray("inventory")) {
var pair = other.getAsJsonArray();
player.inv.setItem(pair.get(0).getAsInt(), ParityData.stack(pair.get(1).getAsString()));
}
ItemStack held = ParityData.stack(f.get("held").getAsString());
player.inv.setItem(0, held);
BlockState state = parse(f.get("state").getAsString());
var cauldron = (AbstractCauldronBlock) state.getBlock();
var use = net.minecraft.world.level.block.state.BlockBehaviour.class.getDeclaredMethod("useItemOn", ItemStack.class, BlockState.class,
net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, net.minecraft.world.phys.BlockHitResult.class);
use.setAccessible(true);
InteractionResult result = (InteractionResult) use.invoke(cauldron, held, state, world, BlockPos.ZERO, player, InteractionHand.MAIN_HAND, null);
String kind = result == InteractionResult.SUCCESS ? "success" : result == InteractionResult.CONSUME ? "consume"
: result == InteractionResult.TRY_WITH_EMPTY_HAND ? "pass" : result.toString();
StringBuilder inventory = new StringBuilder();
for (int i = 0; i < 41; i++) {
ItemStack s = player.inv.getItem(i);
if (!s.isEmpty()) inventory.append(i).append('=').append(ParityData.canon(s)).append(' ');
}
out.println(kind + "\t" + String.join(";", events) + "\t" + inventory.toString().trim());
} catch (Throwable e) {
out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage());
if (System.getenv("CAULDRON_TRACE") != null) e.printStackTrace();
}
}
}
}
}
@@ -0,0 +1,205 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.Container;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.EntityEquipment;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.inventory.*;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeManager;
/**
* Original oracle: AbstractContainerMenu.clicked over vanilla's real menu
* classes. A stand-in player (inventory, drops recorded) and a stand-in server
* level (real RecipeManager, no networking) run each case's clicks; after
* every click the slots, carried stack, data slots, drops and player state
* are printed as canonical NBT.
*/
public final class VanillaMenuOracle {
static Object unsafe;
static java.lang.reflect.Method allocate;
static RecipeManager recipes;
static final List<String> drops = new ArrayList<>();
@SuppressWarnings("unchecked")
static <T> T make(Class<T> type) {
try {
return (T) allocate.invoke(unsafe, type);
} catch (Exception e) {
throw new AssertionError(e);
}
}
static void set(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
f.set(target, value);
}
static final class Server extends net.minecraft.server.dedicated.DedicatedServer {
Server() {
super(null, null, null, null, null, null, null, null, null, null);
}
@Override public RecipeManager getRecipeManager() { return recipes; }
}
static final class Connection extends ServerGamePacketListenerImpl {
Connection() {
super(null, null, null, null);
}
@Override public void send(net.minecraft.network.protocol.Packet<?> packet) { }
}
static final class World extends ServerLevel {
Server server;
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@Override public net.minecraft.server.MinecraftServer getServer() { return server; }
@Override public RecipeManager recipeAccess() { return recipes; }
@Override public boolean isClientSide() { return false; }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; }
@Override public net.minecraft.world.level.gamerules.GameRules getGameRules() { return new net.minecraft.world.level.gamerules.GameRules(FeatureFlags.DEFAULT_FLAGS); }
@Override public void levelEvent(net.minecraft.world.entity.Entity p, int type, BlockPos pos, int data) { }
@Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.core.Holder<net.minecraft.sounds.SoundEvent> s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { }
@Override public boolean addFreshEntity(net.minecraft.world.entity.Entity e) { return true; }
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
}
static final class FakePlayer extends ServerPlayer {
World world;
boolean creative;
Inventory inv;
FakePlayer() {
super(null, null, null, null);
}
@Override public Inventory getInventory() { return inv; }
@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 net.minecraft.world.entity.EntityTypes.PLAYER; }
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return net.minecraft.world.entity.EntityTypes.PLAYER.builtInRegistryHolder(); }
@Override public boolean canUseSlot(EquipmentSlot slot) { return true; }
@Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { }
@Override public boolean hasDisconnected() { return false; }
@Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) {
if (!stack.isEmpty()) drops.add(ParityData.canon(stack));
return null;
}
@Override public void triggerRecipeCrafted(net.minecraft.world.item.crafting.RecipeHolder<?> recipe, java.util.List<ItemStack> items) { }
@Override public int awardRecipes(java.util.Collection<net.minecraft.world.item.crafting.RecipeHolder<?>> recipes) { return 0; }
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { }
@Override public void giveExperiencePoints(int amount) { drops.add("xp+" + amount); }
@Override public void giveExperienceLevels(int amount) { drops.add("levels" + (amount >= 0 ? "+" : "") + amount); }
}
static AbstractContainerMenu menu(String kind, FakePlayer player, Inventory inv) {
var access = ContainerLevelAccess.create(player.world, BlockPos.ZERO);
if (kind.startsWith("chest")) {
int rows = Integer.parseInt(kind.substring(5));
MenuType<?> type = new MenuType[]{MenuType.GENERIC_9x1, MenuType.GENERIC_9x2, MenuType.GENERIC_9x3, MenuType.GENERIC_9x4, MenuType.GENERIC_9x5, MenuType.GENERIC_9x6}[rows - 1];
return new ChestMenu(type, 0, inv, new SimpleContainer(9 * rows), rows);
}
return switch (kind) {
case "inventory" -> new InventoryMenu(inv, true, player);
case "crafting" -> new CraftingMenu(0, inv, access);
case "hopper" -> new HopperMenu(0, inv);
case "dispenser" -> new DispenserMenu(0, inv);
case "shulker" -> new ShulkerBoxMenu(0, inv);
case "furnace" -> new FurnaceMenu(0, inv);
case "blast_furnace" -> new BlastFurnaceMenu(0, inv);
case "smoker" -> new SmokerMenu(0, inv);
case "brewing" -> new BrewingStandMenu(0, inv);
case "crafter" -> new CrafterMenu(0, inv);
default -> throw new IllegalArgumentException(kind);
};
}
static String state(AbstractContainerMenu menu, Inventory inv) throws Exception {
StringBuilder out = new StringBuilder();
for (int i = 0; i < menu.slots.size(); i++) {
out.append(i > 0 ? " " : "").append(ParityData.canon(menu.getSlot(i).getItem()));
}
out.append(" | ").append(ParityData.canon(menu.getCarried()));
Field dataSlots = AbstractContainerMenu.class.getDeclaredField("dataSlots");
dataSlots.setAccessible(true);
List<DataSlot> data = (List<DataSlot>) dataSlots.get(menu);
out.append(" |");
for (DataSlot d : data) out.append(' ').append(d.get());
out.append(" | ").append(String.join(";", drops));
return out.toString();
}
public static void main(String[] args) throws Exception {
ParityData.init();
var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = field.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
recipes = new RecipeManager(ParityData.lookup);
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
try {
drops.clear();
var world = make(World.class);
world.server = make(Server.class);
var player = make(FakePlayer.class);
player.world = world;
player.creative = f.get("creative").getAsBoolean();
set(player, ServerPlayer.class, "connection", make(Connection.class));
var inv = new Inventory(player, new EntityEquipment());
player.inv = inv;
AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv);
set(player, Player.class, "containerMenu", menu);
if (menu instanceof InventoryMenu im) set(player, Player.class, "inventoryMenu", im);
var slotsJson = f.getAsJsonArray("slots");
for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString()));
menu.setCarried(ParityData.stack(f.get("carried").getAsString()));
var dataJson = f.getAsJsonArray("data");
for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt());
drops.clear();
out.println("init " + state(menu, inv));
for (var opJson : f.getAsJsonArray("ops")) {
var op = opJson.getAsJsonArray();
int slot = op.get(0).getAsInt();
int button = op.get(1).getAsInt();
var input = ContainerInput.valueOf(op.get(2).getAsString());
try {
menu.clicked(slot, button, input, player);
} catch (RuntimeException e) {
Throwable cause = e.getCause() != null ? e.getCause() : e;
out.println("error " + cause.getClass().getSimpleName());
if (System.getenv("MENU_TRACE") != null) cause.printStackTrace();
continue;
}
out.println(state(menu, inv));
}
out.println("end");
} catch (Throwable e) {
out.println("error-case " + e.getClass().getSimpleName());
if (System.getenv("MENU_TRACE") != null) e.printStackTrace();
}
}
}
}
}
@@ -0,0 +1,140 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.*;
/**
* Original oracle: vanilla's RecipeManager over the data pack's recipes.
* Tab-separated commands (stacks are SNBT of ItemStack.CODEC, "-" is empty):
* craft N cells..., cook TYPE stack, stonecut stack, smith template base addition.
* "dump" prints every crafting recipe's ingredient item lists for the generator.
*/
public final class VanillaRecipeOracle {
static RecipeManager recipes;
public static void main(String[] args) throws Exception {
ParityData.init();
recipes = new RecipeManager(ParityData.lookup);
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
if (args[0].equals("dump")) {
dump(Path.of(args[1]));
return;
}
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
String result;
try {
result = run(line.split("\t", -1));
} catch (Exception e) {
result = "error";
}
out.println(result);
}
}
}
static String run(String[] f) throws Exception {
switch (f[0]) {
case "craft": {
int n = Integer.parseInt(f[1]);
List<ItemStack> items = new ArrayList<>();
for (int i = 0; i < n * n; i++) items.add(ParityData.stack(f[2 + i]));
var positioned = CraftingInput.ofPositioned(n, n, items);
var input = positioned.input();
if (input.isEmpty()) return "none";
var found = recipes.getRecipeFor(RecipeType.CRAFTING, input, null);
if (found.isEmpty()) return "none";
var recipe = found.get().value();
var result = recipe.assemble(input);
var rest = recipe.getRemainingItems(input);
StringJoiner joiner = new StringJoiner(";");
for (int i = 0; i < rest.size(); i++) {
if (rest.get(i).isEmpty()) continue;
int at = (positioned.top() + i / input.width()) * n + positioned.left() + i % input.width();
joiner.add(at + "=" + ParityData.canon(rest.get(i)));
}
return found.get().id().identifier().getPath() + "\t" + ParityData.canon(result) + "\t" + joiner;
}
case "cook": {
RecipeType<? extends AbstractCookingRecipe> type = switch (f[1]) {
case "smelting" -> RecipeType.SMELTING;
case "blasting" -> RecipeType.BLASTING;
case "smoking" -> RecipeType.SMOKING;
default -> RecipeType.CAMPFIRE_COOKING;
};
return cook(type, ParityData.stack(f[2]));
}
case "stonecut": {
var stack = ParityData.stack(f[1]);
StringJoiner joiner = new StringJoiner(";");
for (var entry : recipes.getSynchronizedStonecutterRecipes().selectByInput(stack).entries()) {
var holder = entry.recipe().recipe().get();
joiner.add(holder.id().identifier().getPath() + "=" + ParityData.canon(holder.value().assemble(new SingleRecipeInput(stack))));
}
return joiner.toString();
}
case "smith": {
var input = new SmithingRecipeInput(ParityData.stack(f[1]), ParityData.stack(f[2]), ParityData.stack(f[3]));
var found = recipes.getRecipeFor(RecipeType.SMITHING, input, null);
if (found.isEmpty()) return "none";
return ParityData.canon(found.get().value().assemble(input));
}
default:
throw new IllegalArgumentException(f[0]);
}
}
static <T extends AbstractCookingRecipe> String cook(RecipeType<T> type, ItemStack stack) {
if (stack.isEmpty()) return "none";
var input = new SingleRecipeInput(stack);
var found = recipes.getRecipeFor(type, input, null);
if (found.isEmpty()) return "none";
var recipe = found.get().value();
return found.get().id().identifier().getPath() + "\t" + ParityData.canon(recipe.assemble(input)) + "\t" + recipe.experience() + "\t" + recipe.cookingTime();
}
static String items(Ingredient ingredient) {
if (ingredient == null) return "[]";
StringBuilder row = new StringBuilder("[");
var items = ingredient.items().toList();
for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"');
return row.append(']').toString();
}
static void dump(Path path) throws Exception {
try (var out = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8))) {
for (var holder : recipes.getRecipes()) {
var recipe = holder.value();
if (recipe instanceof SmithingRecipe smithing) {
out.println("{\"id\":\"" + holder.id().identifier().getPath() + "\",\"kind\":\"" + recipe.getClass().getSimpleName()
+ "\",\"template\":" + items(smithing.templateIngredient().orElse(null)) + ",\"base\":" + items(smithing.baseIngredient())
+ ",\"addition\":" + items(smithing.additionIngredient().orElse(null)) + "}");
continue;
}
if (recipe.getType() != RecipeType.CRAFTING) continue;
var info = recipe.placementInfo();
StringBuilder row = new StringBuilder();
row.append("{\"id\":\"").append(holder.id().identifier().getPath()).append("\",\"kind\":\"").append(recipe.getClass().getSimpleName()).append("\",\"slots\":[");
for (int i = 0; i < info.slotsToIngredientIndex().size(); i++) row.append(i > 0 ? "," : "").append(info.slotsToIngredientIndex().getInt(i));
row.append("],\"ingredients\":[");
boolean firstIngredient = true;
for (var ingredient : info.ingredients()) {
row.append(firstIngredient ? "" : ",").append('[');
firstIngredient = false;
var items = ingredient.items().toList();
for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"');
row.append(']');
}
row.append("]}");
out.println(row);
}
}
}
}
+74
View File
@@ -0,0 +1,74 @@
"""Shared plumbing for the interaction/inventory differential harnesses
(test_recipe_parity, test_menu_click_parity, test_block_interaction_parity):
compile and run a vanilla Java oracle headlessly, run the matching Rust
example, and report differing lines grouped by a key."""
import json
import os
from pathlib import Path
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
RESOURCES = lab.LOCAL / 'horizon-client' / '26.3'
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
def work_dir(name):
path = lab.LOCAL / name
path.mkdir(parents=True, exist_ok=True)
return path
class Vanilla:
"""Compiles oracles against the pinned server jar and runs them."""
def __init__(self, work):
self.lock, self.jars, self.libraries = base.verify_artifacts()
self.work = work
self.classes = work / 'classes'
self.classes.mkdir(exist_ok=True)
self.deps = os.pathsep.join(map(str, [self.jars['server'], *self.libraries]))
def compile(self, *oracles):
sources = [PARITY / (name + '.java') for name in oracles]
done = subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none',
'-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', '-Xmaxerrs', '30',
'-cp', self.deps, '-d', str(self.classes), *map(str, sources)], capture_output=True, text=True)
if done.returncode:
print(done.stderr.replace(str(lab.ROOT) + '/', ''))
raise SystemExit('javac failed')
def run(self, oracle, *args, heap='2G'):
subprocess.run(['java', f'-Xmx{heap}', '-cp', str(self.classes) + os.pathsep + self.deps,
'dev.horizonlab.parity.' + oracle, *map(str, args)], check=True)
def cargo_example(package, example, *args, profile=None):
command = ['cargo', 'run', '-q', '-j3']
if profile:
command += ['--profile', profile]
command += ['-p', package, '--example', example, '--', *map(str, args)]
subprocess.run(command, check=True, cwd=lab.ROOT)
def compare(cases, native_path, rust_path, key, describe=None, limit=3):
"""Print differing cases grouped by key(case, native_line); returns the count."""
native = Path(native_path).read_text().split('\n')
rust = Path(rust_path).read_text().split('\n')
if len(native) != len(rust):
print(f'line counts differ: native {len(native)} rust {len(rust)}')
groups = {}
for case, a, b in zip(cases, native, rust):
if a != b:
groups.setdefault(key(case, a), []).append((case, a, b))
describe = describe or (lambda case: case if isinstance(case, str) else json.dumps(case))
total = sum(len(v) for v in groups.values())
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[:limit]:
print(f' case {describe(case)}\n native {a}\n rust {b}')
print(f'{len(cases) - total}/{len(cases)} cases match')
return total
View File
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Compare the data-driven axe/hoe/shovel block transformers with vanilla.
The Java oracle (VanillaBlockTransformerOracle) evaluates the registry's
BlockStateProviders on a stand-in level; the Rust example
(block_transform_fixture) evaluates horizon_client::block_transform. Cases are
every block state any transformer mentions (plus a random sample of all states)
under each transformer, with a few blocks above and three clicked faces.
"""
import argparse
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
ABOVE = ['minecraft:air|', 'minecraft:cave_air|', 'minecraft:stone|', 'minecraft:water|level=0', 'minecraft:oak_slab|type=bottom,waterlogged=false']
FACES = ['up', 'down', 'north']
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--sample', type=int, default=3000)
parser.add_argument('--limit', type=int, default=4)
args = parser.parse_args()
work = lib.work_dir('block-transformer-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaBlockTransformerOracle')
vanilla.run('VanillaBlockTransformerOracle', 'dump', work / 'states.txt')
states = (work / 'states.txt').read_text().splitlines()
mentioned = set()
for path in (lib.RESOURCES / 'data/minecraft/block_transformer').glob('*.json'):
text = path.read_text()
for name in set(__import__('re').findall(r'"minecraft:([a-z_0-9]+)"', text)):
mentioned.add('minecraft:' + name)
tags = set()
for tag in ['turns_into_farmland', 'turns_into_dirt_path', 'air']:
for name in __import__('json').loads((lib.RESOURCES / 'data/minecraft/tags/block' / (tag + '.json')).read_text())['values']:
if not name.startswith('#'):
tags.add(name)
rng = random.Random(args.seed)
chosen = [s for s in states if s.split('|')[0] in mentioned or s.split('|')[0] in tags or 'copper' in s or 'lightning_rod' in s]
chosen += rng.sample(states, args.sample)
cases = []
for transformer in ['axe', 'hoe', 'shovel', 'honeycomb']:
for state in chosen:
for face in FACES:
cases.append('\t'.join([transformer, face, state, rng.choice(ABOVE)]))
(work / 'cases.txt').write_text(''.join(c + '\n' for c in cases))
vanilla.run('VanillaBlockTransformerOracle', work / 'cases.txt', work / 'native.txt')
lib.cargo_example('horizon-client', 'block_transform_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt')
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt',
lambda case, line: case.split('\t')[0] + ' ' + line.split('\t')[0][:12], None, args.limit)
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Compare cauldron item interactions with vanilla's CauldronInteractions.
The Java oracle (VanillaCauldronOracle) calls the cauldron block's useItemOn
with a recording level and player; the Rust example (cauldron_fixture) runs
horizon_client::cauldron. Every item is used on every cauldron state (empty,
water, lava and powder snow at each level), with water potions, dyed armour,
patterned banners and shulker boxes, in survival and creative, under water or
not, and with a crowded inventory. The result, block writes, sounds, drops and
the final inventory are compared.
"""
import argparse
import json
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
STATES = ['minecraft:cauldron|', 'minecraft:water_cauldron|level=1', 'minecraft:water_cauldron|level=2',
'minecraft:water_cauldron|level=3', 'minecraft:lava_cauldron|', 'minecraft:powder_snow_cauldron|level=1',
'minecraft:powder_snow_cauldron|level=3']
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
def snbt(item, count=1, **components):
body = ','.join('"minecraft:%s":%s' % (k, v) for k, v in sorted(components.items()))
return '{id:"%s",count:%d%s}' % (item, count, ',components:{%s}' % body if body else '')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--limit', type=int, default=4)
args = parser.parse_args()
work = lib.work_dir('cauldron-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaCauldronOracle')
items = json.loads((lib.RESOURCES / 'items.json').read_text())
patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json'))
rng = random.Random(args.seed)
held = []
for name, info in items.items():
if name == 'minecraft:air':
continue
top = info.get('minecraft:max_stack_size', 64)
held.append(snbt(name, 1))
held.append(snbt(name, rng.randrange(1, top + 1)))
for color in DYES:
for layers in range(0, 4):
body = '[%s]' % ','.join('{pattern:"%s",color:"%s"}' % (rng.choice(patterns), rng.choice(DYES)) for _ in range(layers))
held.append(snbt('minecraft:%s_banner' % color, rng.choice([1, 3]), banner_patterns=body))
held.append(snbt('minecraft:%s_shulker_box' % color, rng.choice([1, 2])))
for item in ['leather_helmet', 'leather_chestplate', 'leather_leggings', 'leather_boots', 'leather_horse_armor', 'wolf_armor']:
held.append(snbt('minecraft:' + item, 1, dyed_color=rng.randrange(1 << 24)))
for potion in ['minecraft:water', 'minecraft:healing', 'minecraft:awkward']:
for item in ['potion', 'splash_potion', 'lingering_potion']:
held.append(snbt('minecraft:' + item, rng.choice([1, 2]), potion_contents='{potion:"%s"}' % potion))
cases = []
filler = [snbt(i, 64) for i in ['minecraft:stone', 'minecraft:dirt', 'minecraft:cobblestone']]
for state in STATES:
for stack in held:
crowded = rng.random() < 0.25
inventory = [[i, rng.choice(filler)] for i in range(1, 36)] if crowded else []
if not crowded and rng.random() < 0.3:
inventory = [[rng.randrange(1, 36), snbt('minecraft:bucket', rng.randrange(1, 16))]]
cases.append({'state': state, 'held': stack, 'creative': rng.random() < 0.3, 'under_water': rng.random() < 0.3,
'inventory': inventory})
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
vanilla.run('VanillaCauldronOracle', work / 'cases.jsonl', work / 'native.txt')
lib.cargo_example('horizon-client', 'cauldron_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt',
lambda case, line: case['state'].split('|')[0] + ' ' + line.split('\t')[0],
lambda case: json.dumps(case)[:700], args.limit)
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Compare AbstractContainerMenu.clicked with vanilla's menu classes.
The Java oracle (VanillaMenuOracle) runs each case's clicks on the real menu
class with a stand-in player and level; the Rust example (menu_fixture) runs
horizon_client::menu. Cases are randomized slot contents with random click
sequences covering every ContainerInput (pickup, quick move, swap, clone,
throw, the three quick craft drags, pickup all) over the player inventory,
crafting table, chests, hopper, dispenser, shulker box and the furnaces. After
every click the slots, carried stack, data slots and drops are compared.
"""
import argparse
import json
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81,
'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46}
DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10}
COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread',
'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool',
'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin',
'elytra', 'turtle_helmet', 'iron_sword', 'diamond_pickaxe', 'bow', 'shulker_box', 'red_shulker_box',
'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling',
'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest', 'glass_bottle', 'nether_wart', 'blaze_powder',
'redstone', 'gunpowder', 'sugar', 'potion', 'splash_potion', 'lingering_potion', 'fermented_spider_eye', 'dragon_breath']
def quote(text):
return '"' + text + '"'
def snbt(item, count, damage=0, curse=False, potion=None):
comps = []
if potion:
comps.append('"minecraft:potion_contents":{potion:"%s"}' % potion)
if damage:
comps.append('"minecraft:damage":%d' % damage)
if curse:
comps.append('"minecraft:enchantments":{"minecraft:binding_curse":1}')
body = ',components:{%s}' % ','.join(comps) if comps else ''
return '{id:%s,count:%d%s}' % (quote(item), count, body)
class Gen:
def __init__(self, rng, items):
self.rng = rng
self.items = items
self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items]
self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k
and not k.endswith('_spawn_egg')]
def stack(self):
rng = self.rng
item = rng.choice(self.pool if rng.random() < 0.85 else self.all)
info = self.items[item]
top = info.get('minecraft:max_stack_size', 64)
damage = 0
if info.get('minecraft:max_damage') and rng.random() < 0.3:
damage = rng.randrange(1, info['minecraft:max_damage'])
count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)])
potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None
return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion)
def slots(self, size, density):
return [self.stack() if self.rng.random() < density else '-' for _ in range(size)]
def recipe(self, slots, width):
"""Fills the crafting grid (slots 1..) with a small known recipe."""
rng = self.rng
amount = lambda: rng.choice([1, 1, 2, 5, 64])
choices = [[('oak_log',)], [('oak_planks',), ('oak_planks',)], [('oak_planks', 'oak_planks'), ('oak_planks', 'oak_planks')],
[('iron_ingot',) * 3] * 3, [('milk_bucket',) * 3, ('sugar', 'egg', 'sugar'), ('wheat',) * 3],
[('wheat',) * 3], [('white_wool',) * 2, ('white_wool',) * 2], [('coal',), ('stick',)]]
pattern = rng.choice(choices)
if len(pattern) > width or any(len(row) > width for row in pattern):
pattern = [('oak_planks',), ('oak_planks',)]
for y, row in enumerate(pattern):
for x, name in enumerate(row):
slots[1 + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1)
def ops(self, size):
rng = self.rng
out = []
for _ in range(rng.randrange(1, 9)):
kind = rng.choices(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'DRAG', 'PICKUP_ALL', 'JUNK'],
[30, 20, 8, 3, 6, 14, 6, 2])[0]
slot = 0 if rng.random() < 0.2 and size in (46,) else rng.randrange(size)
if kind == 'PICKUP':
out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind])
elif kind == 'QUICK_MOVE':
out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind])
elif kind == 'SWAP':
out.append([slot, rng.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 40, 9, -1]), kind])
elif kind in ('CLONE', 'THROW', 'PICKUP_ALL'):
out.append([slot, rng.randrange(0, 2), kind])
elif kind == 'DRAG':
ty = rng.randrange(0, 4)
out.append([-999, 0 | ty << 2, 'QUICK_CRAFT'])
for _ in range(rng.randrange(0, 6)):
out.append([rng.randrange(size), 1 | ty << 2, 'QUICK_CRAFT'])
out.append([-999, 2 | ty << 2, 'QUICK_CRAFT'])
else:
out.append([rng.choice([slot, 999, -5]), rng.randrange(-1, 5), rng.choice(
['PICKUP', 'QUICK_MOVE', 'QUICK_CRAFT', 'SWAP', 'THROW', 'PICKUP_ALL'])])
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--cases', type=int, default=6000)
parser.add_argument('--limit', type=int, default=3)
args = parser.parse_args()
work = lib.work_dir('menu-click-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaMenuOracle')
items = json.loads((lib.RESOURCES / 'items.json').read_text())
rng = random.Random(args.seed)
g = Gen(rng, items)
cases = []
for n in range(args.cases):
menu = list(MENUS)[n % len(MENUS)]
size = MENUS[menu]
slots = g.slots(size, rng.choice([0.1, 0.4, 0.8]))
if menu in ('inventory', 'crafting'):
slots[0] = '-'
if menu in ('inventory', 'crafting') and rng.random() < 0.6:
g.recipe(slots, 2 if menu == 'inventory' else 3)
cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots,
'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [rng.choice([0, 0, 1]) if menu == 'crafter' else 0 for _ in range(DATA.get(menu, 0))],
'ops': g.ops(size)})
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt')
lib.cargo_example('horizon-client', 'menu_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
native = (work / 'native.txt').read_text().split('\n')
rust = (work / 'rust.txt').read_text().split('\n')
def by_case(lines):
out, cur = [], []
for line in lines:
cur.append(line)
if line == 'end' or line.startswith('error-case'):
out.append(cur)
cur = []
return out
native, rust = by_case(native), by_case(rust)
bad = {}
for case, a, b in zip(cases, native, rust):
if a != b:
step = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) if len(a) == len(b) else 0
op = case['ops'][step - 1] if 0 < step <= len(case['ops']) else None
bad.setdefault((case['menu'], op[2] if op else 'init'), []).append((case, step, a, b))
total = sum(len(v) for v in bad.values())
for key, entries in sorted(bad.items(), key=lambda e: -len(e[1])):
print(f'{key}: {len(entries)} differing')
for case, step, a, b in entries[:args.limit]:
print(f' ops {case["ops"][:step]}\n start {a[0]}\n native {a[step]}\n rust {b[step]}')
print(f'{len(cases) - total}/{len(cases)} cases match')
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""Compare crafting, cooking, stonecutting and smithing with vanilla's RecipeManager.
The Java oracle (VanillaRecipeOracle) loads the data pack's recipe registry and
answers craft/cook/stonecut/smith commands; the Rust example (recipe_fixture)
answers the same commands from horizon_client::crafting and ::stations.
Crafting cases are built from every recipe's own ingredients (placed at random
offsets, mirrored, perturbed) plus focused generators for the special recipes
(banners, books, fireworks, dyeing, repair, pots, tipped arrows, maps) and
random grids. Results are compared as canonical ItemStack NBT, with the
matched recipe id and the crafting remainders.
"""
import argparse
import json
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
POTIONS = ['minecraft:healing', 'minecraft:swiftness', 'minecraft:water', 'minecraft:night_vision']
SHAPES = ['small_ball', 'large_ball', 'star', 'creeper', 'burst']
def quote(text):
return '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"'
def stack(item, count=1, **components):
"""SNBT of an ItemStack.CODEC compound; component values are SNBT text."""
body = ','.join(f'{quote("minecraft:" + key)}:{value}' for key, value in sorted(components.items()))
comp = f',components:{{{body}}}' if body else ''
return f'{{id:{quote(item)},count:{count}{comp}}}'
def colors(rng, n=None):
n = rng.randrange(0, 4) if n is None else n
return '[I;' + ','.join(str(rng.randrange(1 << 24)) for _ in range(n)) + ']'
def explosion(rng):
return ('{shape:%s,colors:%s,fade_colors:%s,has_trail:%db,has_twinkle:%db}'
% (quote(rng.choice(SHAPES)), colors(rng), colors(rng), rng.randrange(2), rng.randrange(2)))
class Gen:
def __init__(self, rng, items, recipes, patterns):
self.rng = rng
self.items = items
self.recipes = recipes
self.patterns = patterns
self.durable = [k for k, v in items.items() if v.get('minecraft:max_damage')]
def layers(self, n=None):
n = self.rng.choice([0, 0, 1, 2, 6, 7]) if n is None else n
return '[' + ','.join('{pattern:%s,color:%s}' % (quote(self.rng.choice(self.patterns)), quote(self.rng.choice(DYES))) for _ in range(n)) + ']'
def book(self, generation=None):
g = self.rng.randrange(4) if generation is None else generation
return stack('minecraft:written_book', written_book_content='{title:{raw:"T"},author:"A",generation:%d,pages:[{raw:"p1"},{raw:"p2"}]}' % g)
def stack(self, item, count=None, rich=0.5):
"""A stack of the item, with the components that apply to it."""
rng = self.rng
info = self.items.get(item, {})
count = rng.choice([1, 1, 1, 2, 3]) if count is None else count
c = {}
if rng.random() < rich:
if info.get('minecraft:max_damage') and rng.random() < 0.7:
c['damage'] = str(rng.randrange(0, info['minecraft:max_damage'] + 1))
if info.get('minecraft:max_damage') and rng.random() < 0.3:
c['enchantments'] = '{%s:1}' % quote(rng.choice(['minecraft:binding_curse', 'minecraft:vanishing_curse', 'minecraft:mending', 'minecraft:unbreaking']))
if item.endswith('_banner'):
c['banner_patterns'] = self.layers()
if item == 'minecraft:shield':
if rng.random() < 0.3:
c['banner_patterns'] = self.layers(rng.randrange(1, 3))
c['base_color'] = quote(rng.choice(DYES))
if item == 'minecraft:written_book':
return self.book()
if item == 'minecraft:firework_star':
c['firework_explosion'] = explosion(rng)
if item == 'minecraft:firework_rocket':
c['fireworks'] = '{flight_duration:%db,explosions:[%s]}' % (rng.randrange(1, 4), explosion(rng))
if item in ('minecraft:lingering_potion', 'minecraft:potion', 'minecraft:splash_potion'):
c['potion_contents'] = '{potion:%s}' % quote(rng.choice(POTIONS))
if item.startswith('minecraft:leather_') or item in ('minecraft:wolf_armor',):
if rng.random() < 0.6:
c['dyed_color'] = str(rng.randrange(1 << 24))
if item.endswith('shulker_box'):
c['container'] = '[{slot:0,item:{id:"minecraft:stone",count:%d}}]' % rng.randrange(1, 64)
if item.endswith('_bundle') or item == 'minecraft:bundle':
c['bundle_contents'] = '[{id:"minecraft:stone",count:%d}]' % rng.randrange(1, 64)
if item == 'minecraft:filled_map':
c['map_id'] = str(rng.randrange(1, 5))
return stack(item, count, **c)
def plain(self, item):
return self.stack(item, rich=0.3)
def place(rng, cells, size):
"""Cells (stack list) at random free positions of a size x size grid."""
grid = ['-'] * (size * size)
spots = rng.sample(range(size * size), len(cells))
for spot, cell in zip(spots, cells):
grid[spot] = cell
return grid
def place_box(rng, width, height, cells, size):
"""A width x height pattern at a random offset of the grid."""
x0 = rng.randrange(size - width + 1)
y0 = rng.randrange(size - height + 1)
grid = ['-'] * (size * size)
for i, cell in enumerate(cells):
grid[(y0 + i // width) * size + x0 + i % width] = cell
return grid
def craft_case(grid, size):
return 'craft\t%d\t%s' % (size, '\t'.join(grid))
def recipe_cases(g, count_per):
rng = g.rng
for recipe in g.recipes:
if 'slots' not in recipe or not recipe['ingredients']:
continue
ingredients = recipe['ingredients']
slots = recipe['slots']
shaped = recipe['kind'] == 'ShapedRecipe'
if shaped:
width = recipe['width']
height = len(slots) // width
for variant in range(count_per):
pick = [g.plain(rng.choice(i)) if i else '-' for i in ingredients]
if shaped:
cells = ['-' if s < 0 else pick[s] for s in slots]
if variant % 3 == 1: # mirrored
cells = [cells[y * width + width - 1 - x] for y in range(height) for x in range(width)]
size = rng.choice([s for s in (2, 3) if s >= max(width, height)])
grid = place_box(rng, width, height, cells, size)
else:
size = 3 if len(pick) > 4 else rng.choice([2, 3])
grid = place(rng, pick, size)
yield craft_case(grid, size)
# Perturbations: drop one, swap one for a stranger, add one, shift a count.
if variant < 2:
filled = [i for i, c in enumerate(grid) if c != '-']
broken = list(grid)
broken[rng.choice(filled)] = '-'
yield craft_case(broken, size)
broken = list(grid)
broken[rng.choice(filled)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))
yield craft_case(broken, size)
free = [i for i, c in enumerate(grid) if c == '-']
if free:
broken = list(grid)
broken[rng.choice(free)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))
yield craft_case(broken, size)
def special_cases(g, n):
rng = g.rng
items = g.items
banners = [f'minecraft:{d}_banner' for d in DYES]
dyes = [f'minecraft:{d}_dye' for d in DYES]
armor = [k for k in items if k.startswith('minecraft:leather_') and k.count('_') == 2] + ['minecraft:wolf_armor']
boxes = [k for k in items if k.endswith('shulker_box')]
bundles = [k for k in items if k.endswith('bundle')]
skulls = [k for k in items if k.endswith('_head') or k.endswith('_skull')]
for _ in range(n):
size = rng.choice([2, 3])
# banner duplicate / shield decoration
a, b = rng.choice(banners), rng.choice(banners)
yield craft_case(place(rng, [g.stack(a, 1, 1.0), g.stack(b if rng.random() < 0.3 else a, 1, 0.5)], size), size)
yield craft_case(place(rng, [g.stack(rng.choice(banners), 1, 1.0), g.stack('minecraft:shield', 1, 0.5)], size), size)
# book cloning
books = [g.book(rng.choice([0, 0, 1, 2, 3]))] + [stack('minecraft:writable_book') for _ in range(rng.randrange(0, 4))]
if rng.random() < 0.2:
books.append(g.book())
yield craft_case(place(rng, books, 3), 3)
# fireworks
star = [stack(rng.choice(['minecraft:gunpowder'] + dyes[:2] + ['minecraft:gold_nugget', 'minecraft:feather', 'minecraft:fire_charge',
'minecraft:diamond', 'minecraft:glowstone_dust', rng.choice(skulls)]))
for _ in range(rng.randrange(1, 7))]
star += [stack('minecraft:gunpowder'), stack(rng.choice(dyes))]
yield craft_case(place(rng, star[:9], 3), 3)
fade = [g.stack('minecraft:firework_star', 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))]
yield craft_case(place(rng, fade, 3), 3)
rocket = [stack('minecraft:paper')] + [stack('minecraft:gunpowder') for _ in range(rng.randrange(0, 5))] + \
[g.stack('minecraft:firework_star', 1, 1.0) for _ in range(rng.randrange(0, 4))]
yield craft_case(place(rng, rocket[:9], 3), 3)
# armour dyeing, with leftovers
dye_cells = [g.stack(rng.choice(armor), 1, 0.7)] + [stack(rng.choice(dyes + ['minecraft:stick'] if rng.random() < 0.1 else dyes)) for _ in range(rng.randrange(1, 5))]
yield craft_case(place(rng, dye_cells[:9], 3), 3)
# repair
tool = rng.choice(g.durable)
pair = [g.stack(tool, 1, 1.0), g.stack(tool if rng.random() < 0.85 else rng.choice(g.durable), 1, 1.0)]
yield craft_case(place(rng, pair, size), size)
# shulker boxes and bundles
yield craft_case(place(rng, [g.stack(rng.choice(boxes + bundles), 1, 1.0), stack(rng.choice(dyes))], size), size)
multi = [g.stack(rng.choice(boxes + bundles), 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))]
yield craft_case(place(rng, multi, 3), 3)
# decorated pots
sherds = ['minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:archer_pottery_sherd', 'minecraft:stick', 'minecraft:blade_pottery_sherd']
pot = ['-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-']
if rng.random() < 0.2:
pot[rng.choice([0, 2, 6, 8, 4])] = stack('minecraft:brick')
yield craft_case(pot, 3)
yield craft_case([stack('minecraft:brick') if i in (1, 3, 5, 7) else '-' for i in range(9)], 3)
# tipped arrows
ring = [stack('minecraft:arrow', rng.choice([1, 2]))] * 9
ring[4] = g.stack('minecraft:lingering_potion', 1, 1.0 if rng.random() < 0.8 else 0.0)
yield craft_case(ring, 3)
# map cloning
maps = [g.stack('minecraft:filled_map', 1, 1.0)] + [stack('minecraft:map') for _ in range(rng.randrange(1, 9))]
yield craft_case(place(rng, maps, 3), 3)
# mixed junk of the interesting items
pool = banners + dyes + armor + boxes + bundles + ['minecraft:written_book', 'minecraft:writable_book', 'minecraft:firework_star',
'minecraft:paper', 'minecraft:gunpowder', 'minecraft:shield', 'minecraft:glass_bottle',
'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:bowl', 'minecraft:stick']
junk = [g.stack(rng.choice(pool), None, 0.7) for _ in range(rng.randrange(1, 6))]
yield craft_case(place(rng, junk, 3), 3)
def smithing_cases(g):
rng = g.rng
for recipe in g.recipes:
if recipe['kind'].startswith('Smithing'):
for _ in range(24):
pick = lambda key: g.plain(rng.choice(recipe[key])) if recipe[key] else '-'
yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), pick('addition'))
yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), g.plain(rng.choice([i for i in g.items if i != 'minecraft:air'])))
# Armour with a trim already on it.
trims = ['{material:"minecraft:iron",pattern:"minecraft:coast"}', '{material:"minecraft:gold",pattern:"minecraft:sentry"}']
for recipe in g.recipes:
if recipe['kind'] == 'SmithingTrimRecipe':
for trim in trims:
base = rng.choice(recipe['base'])
yield 'smith\t%s\t%s\t%s' % (stack(rng.choice(recipe['template'])), stack(base, 1, trim=trim), stack(rng.choice(recipe['addition'])))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--variants', type=int, default=6)
parser.add_argument('--specials', type=int, default=1500)
parser.add_argument('--random', type=int, default=4000)
parser.add_argument('--limit', type=int, default=3)
args = parser.parse_args()
work = lib.work_dir('recipe-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaRecipeOracle')
vanilla.run('VanillaRecipeOracle', 'dump', work / 'recipes.jsonl')
recipes = [json.loads(line) for line in (work / 'recipes.jsonl').read_text().splitlines()]
# Shaped recipes: widths come from the data pack.
for recipe in recipes:
path = lib.RESOURCES / 'data/minecraft/recipe' / (recipe['id'] + '.json')
data = json.loads(path.read_text())
if recipe['kind'] == 'ShapedRecipe':
rows = [row.rstrip() for row in data['pattern']]
left = min(len(row) - len(row.lstrip()) for row in rows if row)
recipe['width'] = max(len(row) for row in rows) - left
items = json.loads((lib.RESOURCES / 'items.json').read_text())
patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json'))
rng = random.Random(args.seed)
g = Gen(rng, items, recipes, patterns)
cases = list(recipe_cases(g, args.variants))
cases += list(special_cases(g, args.specials))
pool = [k for k in items if not k.endswith('_spawn_egg') and k != 'minecraft:air']
interesting = [f'minecraft:{d}_dye' for d in DYES] + ['minecraft:paper', 'minecraft:gunpowder', 'minecraft:bowl', 'minecraft:stick',
'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:water_bucket']
for _ in range(args.random):
size = rng.choice([2, 3])
cells = [g.stack(rng.choice(interesting if rng.random() < 0.6 else pool), None, 0.5) for _ in range(rng.randrange(1, size * size + 1))]
cases.append(craft_case(place(rng, cells, size), size))
for kind in ['smelting', 'blasting', 'smoking', 'campfire_cooking']:
for item in [i for i in items if i != 'minecraft:air']:
cases.append('cook\t%s\t%s' % (kind, stack(item)))
for item in [i for i in items if i != 'minecraft:air']:
cases.append('stonecut\t' + stack(item))
cases += list(smithing_cases(g))
(work / 'cases.txt').write_text(''.join(c + '\n' for c in cases))
vanilla.run('VanillaRecipeOracle', work / 'cases.txt', work / 'native.txt')
lib.cargo_example('horizon-client', 'recipe_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt')
def key(case, native_line):
kind = case.split('\t')[0]
return kind if kind != 'craft' else 'craft ' + native_line.split('\t')[0]
def describe(case):
return case if len(case) < 1200 else case[:1200] + '...'
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', key, describe, args.limit)
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()