Merge main and reconcile cloud caching with see-through text

This commit is contained in:
LookImEcho-Rick
2026-10-16 06:25:15 -05:00
38 changed files with 2675 additions and 301 deletions
@@ -0,0 +1,96 @@
//! Block entity data on items for tools/test_pick_block_data_parity.py: reads
//! one JSON case per line (see VanillaPickBlockDataOracle) and prints the
//! picked item's component patch, a tab, then the placed block entity.
//!
//! usage: pick_block_data_fixture INPUT OUTPUT
use horizon_client::block_entity_item::{pick, place};
use horizon_client::block_entity_nbt::canonical;
use horizon_client::java_text::{double_to_string, float_to_string};
use horizon_world::nbt::{Tag, parse_snbt};
use serde_json::Value;
use std::fs;
/// ParityData.canon: sorted keys, typed numbers, Java's float text.
fn canon(tag: &Tag, out: &mut String) {
let join = |out: &mut String, prefix: &str, items: Vec<String>| {
out.push_str(prefix);
out.push_str(&items.join(","));
out.push(']');
};
match tag {
Tag::Float(v) => out.push_str(&format!("{}f", float_to_string(f32::from_bits(*v)))),
Tag::Double(v) => out.push_str(&format!("{}d", double_to_string(f64::from_bits(*v)))),
Tag::List(items) => join(
out,
"[",
items
.iter()
.map(|t| {
let mut s = String::new();
canon(t, &mut s);
s
})
.collect(),
),
Tag::Compound(map) => {
let mut keys: Vec<_> = 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(':');
canon(v, out);
}
out.push('}');
}
other => out.push_str(&horizon_client::item_data::canon_tag(other)),
}
}
fn snbt(value: &Value) -> Option<Tag> {
parse_snbt(value.as_str()?).ok().map(|(tag, _)| tag)
}
fn case(line: &str) -> Option<String> {
let case: Value = serde_json::from_str(line).ok()?;
let saved = canonical(&snbt(&case["nbt"])?)?;
let picked = pick(&saved);
let patch = match case.get("patch") {
Some(p) => match snbt(p)? {
Tag::Compound(c) => c,
_ => return None,
},
None => picked.clone(),
};
let target = canonical(&snbt(&case["target"])?)?;
let Tag::Compound(mut placed) = place(&target, &patch, case["op"].as_bool()?) else {
return None;
};
// keepPacked is the chunk's, not saveWithFullMetadata's.
placed.remove(&"keepPacked".into());
let mut out = String::new();
canon(&Tag::Compound(picked), &mut out);
out.push('\t');
canon(&Tag::Compound(placed), &mut out);
Some(out)
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let input = fs::read_to_string(
args.get(1)
.ok_or("usage: pick_block_data_fixture INPUT OUTPUT")?,
)?;
let lines: Vec<String> = input
.lines()
.map(|line| case(line).unwrap_or_else(|| "error".to_owned()))
.collect();
fs::write(
args.get(2).ok_or("missing OUTPUT")?,
lines.join("\n") + "\n",
)?;
Ok(())
}
@@ -0,0 +1,485 @@
//! Block entities carried by items, vanilla 26.3: Ctrl + Pick Block in creative
//! (`ServerGamePacketListenerImpl.addBlockDataToItem`) and placing such an item
//! (`BlockItem.updateCustomBlockEntityTag`, then
//! `BlockEntity.applyComponentsFromItemStack`). Both work on the block entity's
//! saved NBT (`block_entity_nbt::canonical`) and the item's component patch.
//!
//! What a type turns into item components (`removeComponentsFromTag`,
//! `collectImplicitComponents`) leaves its NBT; the rest goes to
//! `minecraft:block_entity_data`, tagged with the type's id.
use crate::block_entity_nbt::{self, canonical};
use horizon_world::nbt::{Compound, JavaString, Tag};
pub const BLOCK_ENTITY_DATA: &str = "minecraft:block_entity_data";
/// `BlockEntityTypes.OP_ONLY_CUSTOM_DATA`: the types whose data only a player
/// who can use game master blocks places (`BlockEntityType.onlyOpCanSetNbt`).
pub const OP_ONLY: [&str; 6] = [
"minecraft:command_block",
"minecraft:lectern",
"minecraft:sign",
"minecraft:hanging_sign",
"minecraft:mob_spawner",
"minecraft:trial_spawner",
];
/// The `minecraft:block_entity_data` of `stack`: its type id and its data.
pub fn data(stack: &crate::items::ItemStack) -> Option<(String, &Tag)> {
let data = stack.data()?.other(BLOCK_ENTITY_DATA)?;
Some((block_entity_nbt::id(data)?, data))
}
/// `BlockItem.shouldPrintOpWarning` for a player with game master permission:
/// the item carries data of an op-only type.
pub fn op_warning(stack: &crate::items::ItemStack) -> bool {
data(stack).is_some_and(|(id, _)| OP_ONLY.contains(&id.as_str()))
}
/// `Spawner.getSpawnEntityDisplayName` (`SpawnData.entity.id` of the item's
/// data, which `ItemStack.addDetailsToTooltip` reads for spawners and trial
/// spawners alike): the entity type a spawner item spawns.
pub fn spawner_entity(stack: &crate::items::ItemStack) -> Option<String> {
let (_, data) = data(stack)?;
match data.get("SpawnData")?.get("entity")?.get("id")? {
Tag::String(id) => Some(id.to_string_lossy()),
_ => None,
}
}
/// A part of a block entity's NBT that its item holds as a component.
#[derive(Clone, Copy)]
enum Part {
/// The NBT key and the component hold the same value.
Same(&'static str, &'static str),
/// `Items` as `minecraft:container`, in a container of this many slots.
Items(usize),
/// `LootTable` and `LootTableSeed` as `minecraft:container_loot`.
Loot,
/// `is_waxed` as `minecraft:waxed`.
Waxed,
/// A decorated pot's `item` as `minecraft:container`.
PotItem,
/// Left out of the item's data, with no component.
Drop(&'static str),
}
const NAME: Part = Part::Same("CustomName", "minecraft:custom_name");
const LOCK: Part = Part::Same("lock", "minecraft:lock");
const CONTAINER: &str = "minecraft:container";
/// Each type's `removeComponentsFromTag`, `collectImplicitComponents` and
/// `applyImplicitComponents`.
fn parts(id: &str) -> &'static [Part] {
match id {
"minecraft:chest"
| "minecraft:trapped_chest"
| "minecraft:barrel"
| "minecraft:shulker_box" => &[NAME, LOCK, Part::Items(27), Part::Loot],
"minecraft:dispenser" | "minecraft:dropper" | "minecraft:crafter" => {
&[NAME, LOCK, Part::Items(9), Part::Loot]
}
"minecraft:hopper" => &[NAME, LOCK, Part::Items(5), Part::Loot],
"minecraft:furnace" | "minecraft:smoker" | "minecraft:blast_furnace" => {
&[NAME, LOCK, Part::Items(3)]
}
"minecraft:brewing_stand" => &[NAME, LOCK, Part::Items(5)],
"minecraft:beacon" => &[NAME, LOCK],
"minecraft:enchanting_table" => &[NAME],
"minecraft:command_block" => &[NAME, Part::Drop("conditionMet"), Part::Drop("powered")],
"minecraft:campfire" => &[Part::Items(4)],
"minecraft:chiseled_bookshelf" => &[Part::Items(6)],
"minecraft:shelf" => &[Part::Items(3)],
"minecraft:beehive" => &[Part::Same("bees", "minecraft:bees")],
"minecraft:banner" => &[Part::Same("patterns", "minecraft:banner_patterns"), NAME],
"minecraft:decorated_pot" => &[
Part::Same("sherds", "minecraft:pot_decorations"),
Part::PotItem,
],
"minecraft:sign" | "minecraft:hanging_sign" => &[
Part::Same("front_text", "minecraft:sign_text_front"),
Part::Same("back_text", "minecraft:sign_text_back"),
Part::Waxed,
],
"minecraft:skull" => &[
Part::Same("profile", "minecraft:profile"),
Part::Same("note_block_sound", "minecraft:note_block_sound"),
Part::Same("custom_name", "minecraft:custom_name"),
],
_ => &[],
}
}
/// The component a part reads, and what it holds for `tag` (None: unset).
fn collect(part: Part, tag: &Tag) -> Option<(&'static str, Option<Tag>)> {
Some(match part {
Part::Same(key, component) => (
component,
tag.get(key).cloned().or_else(|| unset(component)),
),
Part::Items(_) => {
let slots = match tag.get("Items") {
Some(Tag::List(items)) => items.iter().filter_map(slot_entry).collect(),
_ => Vec::new(),
};
(CONTAINER, Some(Tag::List(slots)))
}
Part::Loot => {
let table = tag.get("LootTable").cloned();
let loot = table.map(|t| {
let mut entries = vec![("loot_table", t)];
if let Some(seed) = tag.get("LootTableSeed") {
entries.push(("seed", seed.clone()));
}
Tag::compound(entries)
});
("minecraft:container_loot", loot)
}
Part::Waxed => (
"minecraft:waxed",
matches!(tag.get("is_waxed"), Some(Tag::Byte(1)))
.then(|| Tag::Compound(Compound::new())),
),
Part::PotItem => {
let slots = match tag.get("item") {
Some(Tag::Compound(item)) => Some(container_slot(0, item.clone())),
_ => None,
};
(CONTAINER, Some(Tag::List(slots.into_iter().collect())))
}
Part::Drop(_) => return None,
})
}
/// What a type that always collects `component` gives when its NBT leaves the
/// value out (its empty value, which the NBT omits).
fn unset(component: &str) -> Option<Tag> {
Some(match component {
"minecraft:bees" | "minecraft:banner_patterns" => Tag::List(Vec::new()),
"minecraft:pot_decorations" => Tag::Compound(Compound::new()),
"minecraft:sign_text_front" | "minecraft:sign_text_back" => {
block_entity_nbt::sign_side(None)
}
_ => return None,
})
}
/// An `Items` entry as a `minecraft:container` slot.
fn slot_entry(entry: &Tag) -> Option<Tag> {
let Tag::Compound(entry) = entry else {
return None;
};
let mut item = entry.clone();
let slot = match item.remove(&JavaString::from("Slot"))? {
Tag::Byte(s) => i32::from(s),
_ => return None,
};
Some(container_slot(slot, item))
}
/// An `ItemContainerContents` slot: `ItemStackTemplate` leaves out a count of 1.
fn container_slot(slot: i32, mut item: Compound) -> Tag {
if item.get(&JavaString::from("count")) == Some(&Tag::Int(1)) {
item.remove(&JavaString::from("count"));
}
Tag::compound([("slot", Tag::Int(slot)), ("item", Tag::Compound(item))])
}
/// The value of `component` on the clone item of a type that collects it: a
/// picked item leaves it out of its patch, and a placed item without it in its
/// patch gives it to the block entity.
fn item_default(component: &str) -> Option<Tag> {
Some(match component {
CONTAINER | "minecraft:bees" | "minecraft:banner_patterns" => Tag::List(Vec::new()),
"minecraft:pot_decorations" => {
let brick = || Tag::compound([("id", Tag::String("minecraft:brick".into()))]);
Tag::compound([
("back", brick()),
("front", brick()),
("left", brick()),
("right", brick()),
])
}
"minecraft:sign_text_front" | "minecraft:sign_text_back" => {
block_entity_nbt::sign_side(None)
}
_ => return None,
})
}
const METADATA: [&str; 6] = ["id", "x", "y", "z", "keepPacked", "components"];
/// `saveCustomOnly`: the saved NBT without its id, position and components.
fn custom_only(saved: &Tag) -> Compound {
match saved {
Tag::Compound(c) => c
.iter()
.filter(|(k, _)| !METADATA.contains(&k.to_string_lossy().as_str()))
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => Compound::new(),
}
}
/// `addBlockDataToItem`: the component patch Ctrl + Pick Block gives the clone
/// item of the block entity saved as `saved` (a full, canonical compound).
pub fn pick(saved: &Tag) -> Compound {
let id = block_entity_nbt::id(saved).unwrap_or_default();
let mut patch = Compound::new();
// BlockItem.setBlockEntityData after removeComponentsFromTag.
let mut data = custom_only(saved);
for part in parts(&id) {
let key = match *part {
Part::Same(key, _) | Part::Drop(key) => key,
Part::Items(_) => "Items",
Part::Loot => {
data.remove(&JavaString::from("LootTableSeed"));
"LootTable"
}
Part::Waxed => "is_waxed",
Part::PotItem => "item",
};
data.remove(&JavaString::from(key));
}
if !data.is_empty() {
data.insert("id".into(), Tag::String(id.as_str().into()));
patch.insert(BLOCK_ENTITY_DATA.into(), Tag::Compound(data));
}
// ItemStack.applyComponents(collectComponents()): the block entity's own
// components, then the implicit ones; a value equal to the item's own is
// no change.
let mut collected = match saved.get("components") {
Some(Tag::Compound(c)) => c.clone(),
_ => Compound::new(),
};
for part in parts(&id) {
if let Some((component, value)) = collect(*part, saved) {
match value {
Some(v) => collected.insert(component.into(), v),
None => collected.remove(&JavaString::from(component)),
};
}
}
for (component, value) in collected {
if item_default(&component.to_string_lossy()).as_ref() == Some(&value) {
patch.remove(&component);
} else {
patch.insert(component, value);
}
}
patch
}
/// The block entity saved as `saved` after an item with component patch
/// `components` is placed as it: `BlockItem.updateCustomBlockEntityTag` (the
/// item's data of the same type, op-only types only when `game_master`, the
/// player can use game master blocks), then `applyComponentsFromItemStack`.
pub fn place(saved: &Tag, components: &Compound, game_master: bool) -> Tag {
let Some(id) = block_entity_nbt::id(saved) else {
return saved.clone();
};
let Tag::Compound(mut tag) = saved.clone() else {
return saved.clone();
};
// TypedEntityData.loadInto: saveCustomOnly, merge, loadCustomOnly when changed.
if let Some(Tag::Compound(data)) = components.get(&JavaString::from(BLOCK_ENTITY_DATA))
&& data
.get(&JavaString::from("id"))
.is_some_and(|t| matches!(t, Tag::String(s) if s.to_string_lossy() == id))
&& (game_master || !OP_ONLY.contains(&id.as_str()))
{
let custom = custom_only(saved);
let mut merged = custom.clone();
let mut data = data.clone();
data.remove(&JavaString::from("id"));
crate::data_cmd::merge_compound(&mut merged, &data);
if merged != custom {
for key in METADATA {
if let Some(v) = tag.get(&JavaString::from(key)) {
merged.insert(key.into(), v.clone());
}
}
if let Some(Tag::Compound(loaded)) = canonical(&Tag::Compound(merged)) {
tag = loaded;
}
}
}
// applyImplicitComponents, then the rest of the patch as the block
// entity's own components.
let mut read = vec![BLOCK_ENTITY_DATA, "minecraft:block_state"];
// The item's components: its patch over its own defaults.
let get = |c: &str| match components.get(&JavaString::from(c)) {
Some(v) => Some(v.clone()),
None if components.contains_key(&JavaString::from(format!("!{c}").as_str())) => None,
None => item_default(c),
};
let mut set = |key: &str, value: Option<Tag>| match value {
Some(v) => tag.insert(key.into(), v),
None => tag.remove(&JavaString::from(key)),
};
for part in parts(&id) {
match *part {
Part::Same(key, component) => {
read.push(component);
set(key, get(component));
}
Part::Items(size) => {
read.push(CONTAINER);
let items = container_slots(get(CONTAINER).as_ref())
.filter(|(slot, _)| (*slot as usize) < size)
.map(|(slot, mut item)| {
item.insert("Slot".into(), Tag::Byte(slot as i8));
Tag::Compound(item)
})
.collect();
set("Items", Some(Tag::List(items)));
}
Part::Loot => {
read.push("minecraft:container_loot");
if let Some(loot) = get("minecraft:container_loot") {
set("LootTable", loot.get("loot_table").cloned());
set("LootTableSeed", loot.get("seed").cloned());
}
}
Part::Waxed => {
read.push("minecraft:waxed");
set(
"is_waxed",
Some(Tag::Byte(i8::from(get("minecraft:waxed").is_some()))),
);
}
Part::PotItem => {
read.push(CONTAINER);
let first = container_slots(get(CONTAINER).as_ref()).find(|(slot, _)| *slot == 0);
set("item", first.map(|(_, item)| Tag::Compound(item)));
}
Part::Drop(_) => {}
}
}
let own: Compound = components
.iter()
.filter(|(k, _)| {
let k = k.to_string_lossy();
!k.starts_with('!') && !read.contains(&k.as_str())
})
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
tag.insert("components".into(), Tag::Compound(own));
let tag = Tag::Compound(tag);
canonical(&tag).unwrap_or(tag)
}
/// The slots of a `minecraft:container` component.
fn container_slots(container: Option<&Tag>) -> impl Iterator<Item = (i32, Compound)> + '_ {
let list = match container {
Some(Tag::List(list)) => list.as_slice(),
_ => &[],
};
list.iter().filter_map(|entry| {
let slot = match entry.get("slot")? {
Tag::Int(s) => *s,
_ => return None,
};
match entry.get("item")? {
Tag::Compound(item) => Some((slot, item.clone())),
_ => None,
}
})
}
#[cfg(test)]
mod tests {
use super::*;
fn snbt(text: &str) -> Tag {
horizon_world::nbt::parse_snbt(text).expect("snbt").0
}
fn saved(text: &str) -> Tag {
canonical(&snbt(text)).expect("known type")
}
fn canon(patch: &Compound) -> String {
crate::item_data::canon_tag(&Tag::Compound(patch.clone()))
}
#[test]
fn a_filled_named_chest_gives_its_items_and_name_as_components() {
let chest = saved(
"{id:\"minecraft:chest\",x:1,y:2,z:3,CustomName:\"Loot\",\
Items:[{Slot:4b,id:\"minecraft:stone\",count:5}]}",
);
let patch = pick(&chest);
assert_eq!(
canon(&patch),
crate::item_data::canon_tag(&snbt(
"{\"minecraft:container\":[{slot:4,item:{id:\"minecraft:stone\",count:5}}],\
\"minecraft:custom_name\":\"Loot\"}"
))
);
// Placing it back gives the same chest.
let empty = saved("{id:\"minecraft:chest\",x:1,y:2,z:3}");
assert_eq!(place(&empty, &patch, false), chest);
// An empty chest has nothing to carry.
assert!(pick(&empty).is_empty());
}
#[test]
fn a_command_block_keeps_its_command_in_block_entity_data() {
let block = saved(
"{id:\"minecraft:command_block\",x:0,y:0,z:0,Command:\"say hi\",auto:1b,powered:1b}",
);
let patch = pick(&block);
let data = patch
.get(&JavaString::from(BLOCK_ENTITY_DATA))
.expect("data");
assert_eq!(data.get("Command"), Some(&Tag::String("say hi".into())));
assert_eq!(data.get("powered"), None);
assert_eq!(
data.get("id"),
Some(&Tag::String("minecraft:command_block".into()))
);
// Only a player who can use game master blocks places it.
let fresh = saved("{id:\"minecraft:command_block\",x:0,y:0,z:0}");
assert_eq!(place(&fresh, &patch, false), fresh);
assert_eq!(
place(&fresh, &patch, true).get("Command"),
Some(&Tag::String("say hi".into()))
);
// Data of another type is ignored.
let chest = saved("{id:\"minecraft:chest\",x:0,y:0,z:0}");
assert_eq!(place(&chest, &patch, true), chest);
}
#[test]
fn item_data_names_its_spawn_and_op_only_types() {
let item = |text: &str| {
let components = snbt(&format!("{{\"minecraft:block_entity_data\":{text}}}"));
let (damage, extra) = crate::item_data::decode_components(Some(&components));
crate::items::ItemStack {
damage,
extra,
..crate::items::ItemStack::new("minecraft:spawner", 1)
}
};
let spawner =
item("{id:\"minecraft:mob_spawner\",SpawnData:{entity:{id:\"minecraft:zombie\"}}}");
assert_eq!(
spawner_entity(&spawner).as_deref(),
Some("minecraft:zombie")
);
assert!(op_warning(&spawner));
let chest = item("{id:\"minecraft:chest\",LootTable:\"x\"}");
assert_eq!(spawner_entity(&chest), None);
assert!(!op_warning(&chest));
}
#[test]
fn a_written_sign_gives_its_text_and_wax() {
let sign = saved(
"{id:\"minecraft:sign\",x:0,y:0,z:0,is_waxed:1b,\
front_text:{messages:[\"a\",\"b\",\"\",\"\"]}}",
);
let patch = pick(&sign);
let keys: Vec<String> = patch.keys().map(|k| k.to_string_lossy()).collect();
assert_eq!(keys, ["minecraft:sign_text_front", "minecraft:waxed"]);
let fresh = saved("{id:\"minecraft:sign\",x:0,y:0,z:0}");
assert_eq!(place(&fresh, &patch, false), sign);
}
}
@@ -259,7 +259,7 @@ fn is_pos(tag: &Tag) -> bool {
matches!(tag, Tag::IntArray(v) if v.len() == 3)
}
/// The loaded `SignText` of one side, or the empty text.
fn sign_side(tag: Option<&Tag>) -> Tag {
pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag {
let empty = || string("");
let mut messages: Vec<Tag> = match tag.and_then(|t| t.get("messages")) {
Some(Tag::List(list)) => list.iter().filter_map(component).collect(),
+50
View File
@@ -61,6 +61,33 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> {
_ => Err(not_map(t)),
},
"minecraft:custom_name" | "minecraft:item_name" => super::component::decode(t),
// TypedEntityData.codec: the type is the compound's id.
"minecraft:block_entity_data" => match t {
Tag::Compound(c) => match c.get(&"id".into()) {
None => Err(format!("Expected 'id' field in {}", snbt(t))),
Some(Tag::String(id)) => {
let id = id.to_string_lossy();
let id = if id.contains(':') {
id
} else {
format!("minecraft:{id}")
};
let known = crate::block_entity_nbt::TYPES
.iter()
.chain(&crate::block_entity_nbt::NEWEST)
.any(|k| *k == id);
if known {
Ok(())
} else {
Err(format!(
"Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: {id}"
))
}
}
Some(_) => Ok(()),
},
_ => Ok(()),
},
_ => Ok(()),
}
}
@@ -609,3 +636,26 @@ pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) {
fn _unused(t: &Tag) -> String {
snbt(t)
}
#[cfg(test)]
mod tests {
use super::decode_component;
fn check(snbt: &str) -> Result<(), String> {
let tag = horizon_world::nbt::parse_snbt(snbt).expect("snbt").0;
decode_component("minecraft:block_entity_data", &tag)
}
#[test]
fn block_entity_data_needs_a_known_type() {
assert_eq!(check("{id:\"chest\",Lock:1}"), Ok(()));
assert_eq!(
check("{Command:\"say\"}"),
Err("Expected 'id' field in {Command:\"say\"}".into())
);
assert_eq!(
check("{id:\"minecraft:stone\"}"),
Err("Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: minecraft:stone".into())
);
}
}
+105 -67
View File
@@ -10,6 +10,7 @@ mod banners;
mod beacon;
mod beehives;
mod block_entity_anims;
mod block_items;
mod blockctl;
mod boats;
mod books;
@@ -61,6 +62,8 @@ mod jukebox;
mod lan;
mod lan_actions;
mod lan_crafting;
mod lan_mobs;
mod lan_pvp;
mod lan_screen;
mod lan_trading;
mod leads;
@@ -770,6 +773,8 @@ struct Game<'a> {
renderer: Option<Renderer>,
/// CPU geometry storage retained across frames, including empty/title frames.
entity_vertices: Vec<Vertex>,
/// Name tags drawn over everything (`RenderPipelines.TEXT_SEE_THROUGH`).
see_through_vertices: Vec<Vertex>,
started: Instant,
previous: Instant,
/// FramerateLimitTracker.latestInputTime.
@@ -1028,6 +1033,9 @@ struct Game<'a> {
saved_for_exit: bool,
/// The block a guest is acting on (game/lan_actions.rs).
forced_hit: Option<Hit>,
/// A guest's `ServerboundUseItemPacket`: the held item alone, no block
/// or entity (`ServerGamePacketListenerImpl.handleUseItem`).
lan_item_only: bool,
/// Level events of this tick for the guests, and the guest acting now.
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
/// Block events (position, b0, b1, state) and entity events (id, event,
@@ -1038,6 +1046,10 @@ struct Game<'a> {
/// have each chest open.
lid_openers: HashMap<(i32, i32, i32), i32>,
lan_acting: Option<u32>,
/// The name of the guest `lan_acting` acts for (`Player.getName`).
lan_acting_name: Option<String>,
/// Their UUID (`Player.getUUID`).
lan_acting_uuid: Option<u128>,
/// Command feedback to forward to a guest.
chat_capture: Option<Vec<horizon_client::text::Text>>,
/// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends.
@@ -1106,6 +1118,27 @@ fn facing_offset(facing: &str) -> [i32; 3] {
_ => [0, -1, 0],
}
}
/// How far along `dir` (within `reach`) a ray from `eye` enters `b`.
fn ray_box(eye: [f64; 3], dir: [f64; 3], reach: f64, b: Aabb) -> Option<f64> {
let (min, max) = (b.min_position(), b.max_position());
let (lo, hi) = ([min.x, min.y, min.z], [max.x, max.y, max.z]);
let (mut t0, mut t1) = (0.0f64, reach);
for a in 0..3 {
if dir[a].abs() < 1e-9 {
if eye[a] < lo[a] || eye[a] > hi[a] {
return None;
}
continue;
}
let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]);
if ta > tb {
std::mem::swap(&mut ta, &mut tb);
}
t0 = t0.max(ta);
t1 = t1.min(tb);
}
(t0 <= t1).then_some(t0)
}
fn view_vector(yaw: f32, pitch: f32) -> [f64; 3] {
let (y, p) = (f64::from(yaw).to_radians(), f64::from(pitch).to_radians());
[-y.sin() * p.cos(), -p.sin(), y.cos() * p.cos()]
@@ -2351,17 +2384,18 @@ impl Game<'_> {
{
return Ok(Some(Hand::Main));
}
if self.interact_frame()
|| self.interact_armor_stand()
|| self.interact_boat()
|| self.interact_cart()
|| self.interact_mob()?
|| self.interact_knot()
if !self.lan_item_only
&& (self.interact_frame()
|| self.interact_armor_stand()
|| self.interact_boat()
|| self.interact_cart()
|| self.interact_mob()?
|| self.interact_knot())
{
return Ok(Some(Hand::Main));
}
// An EntityHitResult may fall through to Item.use, never to useItemOn.
let block_hit = if self.entity_targeted() {
let block_hit = if self.lan_item_only || self.entity_targeted() {
None
} else {
self.pick()
@@ -2572,19 +2606,21 @@ impl Game<'_> {
};
let target = [pos.x, pos.y, pos.z];
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
let sign = matches!(entity, BlockEntity::Sign(_));
let command_block = matches!(entity, BlockEntity::CommandBlock(_));
self.world
.block_entities
.insert((target[0], target[1], target[2]), entity);
if command_block {
self.command_block_placed((target[0], target[1], target[2]));
}
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);
let key = (target[0], target[1], target[2]);
self.world.block_entities.insert(key, entity);
let game_master = self.can_use_game_master_blocks();
self.apply_placed_item(target, &stack, game_master);
// Block.setPlacedBy.
match self.world.block_entities.get(&key) {
Some(BlockEntity::CommandBlock(_)) => {
let data = stack.data().is_some_and(|d| {
d.other(horizon_client::block_entity_item::BLOCK_ENTITY_DATA)
.is_some()
});
self.command_block_placed(key, !data);
}
Some(BlockEntity::Sign(sign)) if !sign.waxed => self.open_sign_editor(key, true),
_ => {}
}
}
self.swing_arm();
@@ -5359,7 +5395,10 @@ impl Game<'_> {
self.player_model_geometry(camera, alpha, &mut out);
self.guest_model_geometry(camera, alpha, &mut out);
self.fangs_geometry(camera, alpha, &mut out);
self.name_tag_geometry(camera, alpha, &mut out);
let mut see_through = std::mem::take(&mut self.see_through_vertices);
see_through.clear();
self.name_tag_geometry(camera, alpha, &mut out, &mut see_through);
self.see_through_vertices = see_through;
// Entity shadows (EntityRenderer.extractShadow).
if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() {
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
@@ -5660,31 +5699,41 @@ impl Game<'_> {
if !m.alive() {
continue;
}
let b = m.bounds();
let (min, max) = (b.min_position(), b.max_position());
let (lo, hi) = ([min.x, min.y, min.z], [max.x, max.y, max.z]);
let (mut t0, mut t1) = (0.0f64, reach);
let mut hit = true;
for a in 0..3 {
if dir[a].abs() < 1e-9 {
if eye[a] < lo[a] || eye[a] > hi[a] {
hit = false;
}
continue;
}
let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]);
if ta > tb {
std::mem::swap(&mut ta, &mut tb);
}
t0 = t0.max(ta);
t1 = t1.min(tb);
}
if hit && t0 <= t1 && best.is_none_or(|b| t0 < b.1) {
best = Some((i, t0));
if let Some(t) = ray_box(eye, dir, reach, m.bounds())
&& best.is_none_or(|b| t < b.1)
{
best = Some((i, t));
}
}
best
}
/// `Player.attack`'s damage against `target_kind` (with the attack
/// strength and whether it is a critical hit): the weapon and effects
/// scaled by the attack strength, a mace's smash, the critical hit, then
/// enchantments.
pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) {
let hand_damage = 1.0
+ self
.held()
.and_then(|h| self.res.items.get(&h.item))
.map_or(0.0, |i| i.attack_damage);
let damage = hand_damage + self.effect_attack_bonus();
let scale = self.attack_strength_scale();
let mut amount = damage * (0.2 + scale * scale * 0.8);
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
amount += self.smash_damage_bonus(target_kind);
let player = self.player.as_ref();
// Player.canCriticalAttack: falling, off the ground, not sprinting.
let falling =
player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
let crit = scale > 0.9 && falling;
if crit {
amount *= 1.5;
}
// Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
amount += self.enchant_damage_bonus(target_kind) * scale;
(amount, scale, crit)
}
/// `Player.getAttackStrengthScale(0.5)`.
fn attack_strength_scale(&self) -> f32 {
let speed = self
@@ -5742,6 +5791,7 @@ impl Game<'_> {
|| self.attack_boat(hand_damage)
|| self.attack_cart(hand_damage)
|| self.attack_dragon()
|| self.attack_guest()
{
return true;
}
@@ -5758,23 +5808,9 @@ impl Game<'_> {
return false;
}
}
let damage = hand_damage + self.effect_attack_bonus();
let scale = self.attack_strength_scale();
let mut amount = damage * (0.2 + scale * scale * 0.8);
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
amount += self.smash_damage_bonus(&target_kind);
let player = self.player.as_ref();
// Player.canCriticalAttack: falling, off the ground, not sprinting.
let falling =
player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
let crit = scale > 0.9 && falling;
if crit {
amount *= 1.5;
}
// Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
amount += self.enchant_damage_bonus(&target_kind) * scale;
let (amount, scale, crit) = self.melee_damage(&target_kind);
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
@@ -8391,6 +8427,7 @@ impl Game<'_> {
// Keep the buffer local while builders need mutable access to the game.
let mut entities = std::mem::take(&mut self.entity_vertices);
entities.clear();
self.see_through_vertices.clear();
if !title {
entities = horizon_client::spans::time("entity_geometry", || {
self.entity_geometry(camera, alpha, entities)
@@ -8448,6 +8485,7 @@ impl Game<'_> {
let border = (!title)
.then(|| self.border_draw(camera.to_array(), alpha as f32))
.flatten();
let see_through = std::mem::take(&mut self.see_through_vertices);
let frame = Frame {
shader: self.shader_inputs(camera, alpha as f32),
nether_lighting: self.dim == Dim::Nether,
@@ -8504,6 +8542,7 @@ impl Game<'_> {
}),
entities: &entities,
additive: &additive,
see_through: &see_through,
celestial: if self.settings.horizon.sky || title {
&celestial
} else {
@@ -8551,6 +8590,7 @@ impl Game<'_> {
};
// Restore storage even when rendering fails (for example, a lost surface).
self.entity_vertices = entities;
self.see_through_vertices = see_through;
result
}
/// The LevelLoadingScreen shown while the player waits for its chunks:
@@ -8807,17 +8847,11 @@ impl Game<'_> {
}
MouseButton::Middle if pressed => {
// Minecraft.pickBlockOrEntity -> the server's handlePickItemFromBlock:
// the block's clone item, picked from the inventory (`pick_item`).
// the block's clone item, with its block entity's data on Ctrl in
// creative, picked from the inventory (`pick_item`).
if let Some(hit) = self.pick() {
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
let item = self.res.facts.get(state).item.clone();
if &*item != "minecraft:air" {
let stack = ItemStack {
item,
count: 1,
damage: 0,
extra: None,
};
let include_data = self.creative && self.has_control_down();
if let Some(stack) = self.picked_stack(hit.pos, include_data) {
let infinite = self.creative;
horizon_client::pick_item::pick(
&mut self.inventory[..36],
@@ -9922,6 +9956,7 @@ pub fn run() -> Result<()> {
window: None,
renderer: None,
entity_vertices: Vec::new(),
see_through_vertices: Vec::new(),
health_hud: hud_layout::HealthHud::default(),
started: now,
previous: now,
@@ -10098,11 +10133,14 @@ pub fn run() -> Result<()> {
text_selection: Default::default(),
saved_for_exit: false,
forced_hit: None,
lan_item_only: false,
lan_events: Vec::new(),
lan_block_events: Vec::new(),
lan_entity_events: Vec::new(),
lid_openers: HashMap::new(),
lan_acting: None,
lan_acting_name: None,
lan_acting_uuid: None,
chat_capture: None,
cmds: Default::default(),
ui: Default::default(),
+1 -1
View File
@@ -638,7 +638,7 @@ impl Game<'_> {
fn messages_value(&self, n: usize) -> Value {
let titles = &self.titles;
json!({
"chat": self.ui.chat.recent_lines(n),
"chat": self.remote_chat(n).unwrap_or_else(|| self.ui.chat.recent_lines(n)),
"order": "newest first",
"title": (titles.time > 0).then(|| titles.title.as_ref().map(|t| t.plain())).flatten(),
"subtitle": (titles.time > 0).then(|| titles.subtitle.as_ref().map(|t| t.plain())).flatten(),
-14
View File
@@ -5,7 +5,6 @@ use super::Game;
use horizon_client::{
banner::{self, BannerLayer},
containers::BlockEntity,
items::ItemStack,
};
impl Game<'_> {
@@ -17,19 +16,6 @@ impl Game<'_> {
};
layer_textures(&self.res.stations.banners, &b.layers)
}
/// A placed banner takes the item's layers and name.
pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) {
self.pending.banner.remove(&pos);
if !stack.item.ends_with("_banner") {
return;
}
if let Some(BlockEntity::Banner(b)) =
self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2]))
{
b.layers = banner::layers(stack).to_vec();
b.name = stack.custom_name().map(str::to_owned);
}
}
}
/// Texture names and tints of banner layers (`Sheets.getBannerSprite`).
@@ -0,0 +1,117 @@
//! Block entities and the items that carry them
//! (`horizon_client::block_entity_item`): the item Pick Block gives, with the
//! block entity's data on Ctrl in creative, and the data and components a
//! placed item gives its block entity.
use super::Game;
use horizon_client::{
block_entity_item, block_entity_nbt, containers::BlockEntity, item_data, items::ItemStack, save,
};
use horizon_world::nbt::{Compound, Tag};
/// The component patch of `stack`.
fn components(stack: &ItemStack) -> Compound {
match item_data::encode_components(stack) {
Some(Tag::Compound(c)) => c,
_ => Compound::new(),
}
}
impl Game<'_> {
/// The block entity at `key` as vanilla saves it, with its custom name.
fn saved_block_entity(&self, key: (i32, i32, i32)) -> Option<Tag> {
let entity = self.world.block_entities.get(&key)?;
let block = &self
.res
.facts
.get(self.world.block(key.0, key.1, key.2))
.name;
let mut tag = save::encode_block_entity(key, entity, block);
if let (Some(name), Tag::Compound(map)) = (self.world.block_names.get(&key), &mut tag) {
map.insert("CustomName".into(), Tag::String(name.as_str().into()));
}
block_entity_nbt::canonical(&tag)
}
/// `BlockState.getCloneItemStack` of the block at `pos`, then, with
/// `include_data`, `ServerGamePacketListenerImpl.addBlockDataToItem`.
pub(super) fn picked_stack(&self, pos: [i32; 3], include_data: bool) -> Option<ItemStack> {
let key = (pos[0], pos[1], pos[2]);
let state = self.world.block(pos[0], pos[1], pos[2]);
let facts = self.res.facts.get(state);
if &*facts.item == "minecraft:air" {
return None;
}
let mut stack = ItemStack::new(&facts.item, 1);
let mut patch = Compound::new();
// BeehiveBlock.getCloneItemStack: the honey level as the item's block state.
if include_data
&& let Some(level) = self
.res
.assets
.registry
.state(state)
.filter(|s| matches!(s.name.as_str(), "minecraft:beehive" | "minecraft:bee_nest"))
.and_then(|s| s.properties.get("honey_level"))
{
patch.insert(
"minecraft:block_state".into(),
Tag::compound([("honey_level", Tag::String(level.as_str().into()))]),
);
}
// AbstractBannerBlock.getCloneItemStack: the banner's own item
// (BannerBlockEntity.getItem), data or not.
let banner = matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Banner(_))
);
if (include_data || banner)
&& let Some(saved) = self.saved_block_entity(key)
{
patch.extend(block_entity_item::pick(&saved));
}
if !patch.is_empty() {
let mut all = components(&stack);
all.extend(patch);
(stack.damage, stack.extra) = item_data::decode_components(Some(&Tag::Compound(all)));
}
Some(stack)
}
/// `BlockItem.updateCustomBlockEntityTag` and `updateBlockEntityComponents`
/// for the block entity just placed at `pos` from `stack`; `game_master`:
/// the placer can use game master blocks (a dispenser can't).
pub(super) fn apply_placed_item(
&mut self,
pos: [i32; 3],
stack: &ItemStack,
game_master: bool,
) {
let key = (pos[0], pos[1], pos[2]);
self.pending.banner.remove(&pos);
let Some(saved) = self.saved_block_entity(key) else {
return;
};
let placed = block_entity_item::place(&saved, &components(stack), game_master);
if placed == saved {
return;
}
let Some((_, mut entity)) = save::decode_block_entity(&placed) else {
return;
};
// The new crafter's state flag (CrafterBlock.newBlockEntity), which
// its saved data has no part of.
if let (BlockEntity::Crafter(new), Some(BlockEntity::Crafter(old))) =
(&mut entity, self.world.block_entities.get(&key))
{
new.state_triggered = old.state_triggered;
}
// Banners and signs keep their name themselves.
if !matches!(entity, BlockEntity::Banner(_) | BlockEntity::Sign(_)) {
match save::text(placed.get("CustomName")) {
Some(name) => self.world.block_names.insert(key, name),
None => self.world.block_names.remove(&key),
};
}
self.world.block_entities.insert(key, entity);
}
}
@@ -210,15 +210,16 @@ impl Game<'_> {
self.with_level(|b, level, ticks| b.update_neighbour_for_output_signal(level, ticks, at));
}
/// `CommandBlock.setPlacedBy`: output tracking follows
/// `send_command_feedback`, then the block takes the signal around it.
pub(super) fn command_block_placed(&mut self, pos: Pos) {
/// `CommandBlock.setPlacedBy`: unless the item carried block entity data
/// (`defaults` false), output tracking follows `send_command_feedback` and
/// the block's own automatic flag; then the block takes the signal around it.
pub(super) fn command_block_placed(&mut self, pos: Pos, defaults: bool) {
let feedback = self.ui.rules.bool("send_command_feedback");
let Some(name) = self.block_state_at(pos).map(|s| s.name.as_str()) else {
return;
};
let auto = command_block::automatic_block(name);
if let Some(c) = command_block_mut(&mut self.world, pos) {
if defaults && let Some(c) = command_block_mut(&mut self.world, pos) {
c.track_output = feedback;
c.auto = auto;
}
+9 -5
View File
@@ -324,11 +324,15 @@ impl Game<'_> {
/// Entity.getDisplayName.
pub(super) fn target_name(&self, t: Target) -> Text {
match t {
Target::Player => match self.score.board.players_team(PLAYER_NAME) {
// PlayerTeam.formatNameForTeam.
Some(team) => team.formatted_name(Text::literal(PLAYER_NAME)),
None => Text::literal(PLAYER_NAME),
},
Target::Player => {
// A guest's commands name the guest.
let name = self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME);
match self.score.board.players_team(name) {
// PlayerTeam.formatNameForTeam.
Some(team) => team.formatted_name(Text::literal(name)),
None => Text::literal(name),
}
}
Target::Item(id) => {
let item = self
.dropped
+12
View File
@@ -590,6 +590,18 @@ impl Game<'_> {
fn control_key_down(&mut self, key: KeyCode) -> Result<()> {
self.physical_keys.insert(key);
// A server's chat input takes the keys first, as remote_chat_key does.
if self.remote_chat_open() {
use winit::keyboard::NamedKey;
let named = match key {
KeyCode::Escape => Some(NamedKey::Escape),
KeyCode::Enter | KeyCode::NumpadEnter => Some(NamedKey::Enter),
KeyCode::Backspace => Some(NamedKey::Backspace),
_ => None,
};
self.remote_chat_input(named, None);
return Ok(());
}
if self.screen == Screen::Chat {
self.chat_key_code(key, None);
return Ok(());
+74 -9
View File
@@ -514,6 +514,13 @@ impl Game<'_> {
let mut dead = Vec::new();
let mut died = std::mem::take(&mut self.died);
let ticking = self.entity_ticking_area();
// With guests on, each mob sees its nearest player (game/lan_mobs.rs).
let guests = self.lan_guest_views();
let mut bindings = match self.lan.as_mut() {
Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players),
_ => Default::default(),
};
let mut guest_events = Vec::new();
let level_random;
{
// The level random, lent to the mobs (brain behaviours draw from
@@ -522,8 +529,24 @@ impl Game<'_> {
let mut pushes = Vec::new();
let mut keep = Vec::with_capacity(mobs.len());
for i in 0..mobs.len() {
let w = self.mob_world_base(&snapshot);
let mut w = self.mob_world_base(&snapshot);
let m = &mut mobs[i];
let seen_guest = if guests.is_empty() {
None
} else {
let bound = bindings.get(&m.id).copied();
let conn = super::lan_mobs::player_for(m, w.player.as_ref(), &guests, bound);
match conn {
Some(conn) => {
bindings.insert(m.id, conn);
w.player = guests.iter().find(|g| g.0 == conn).map(|g| g.1.clone());
}
None => {
bindings.remove(&m.id);
}
}
conn
};
if !w
.world
.loaded(m.position.x.floor() as i32, m.position.z.floor() as i32)
@@ -547,6 +570,16 @@ impl Game<'_> {
let from = events.len();
let kept = m.tick(&w, &mut scratch, &mut events);
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
if let Some(conn) = seen_guest {
let mut k = from;
while k < events.len() {
if super::lan_mobs::acts_on_player(&events[k]) {
guest_events.push((conn, events.remove(k)));
} else {
k += 1;
}
}
}
// Killed during its own tick (drowning, burning, falling...).
if !m.alive() && !m.removed && died.insert(m.id) {
dead.push(m.clone());
@@ -569,6 +602,12 @@ impl Game<'_> {
level_random = scratch;
}
self.world.random = level_random;
if let Some(host) = self.lan.as_mut()
&& !guests.is_empty()
{
bindings.retain(|id, _| mobs.iter().any(|m| m.id == *id));
host.mob_players = bindings;
}
self.mobs.append(&mut mobs);
self.died = died;
self.sync_riders();
@@ -581,6 +620,7 @@ impl Game<'_> {
self.mob_died(&m);
}
self.handle_mob_events(events)?;
self.lan_guest_mob_events(guest_events);
self.tick_projectiles()?;
self.tick_fangs();
self.tick_allays();
@@ -1337,7 +1377,12 @@ impl Game<'_> {
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
self.mob_hits_player(amount, from, kind);
}
fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) -> bool {
pub(super) fn mob_hits_player(
&mut self,
amount: f32,
from: [f64; 3],
damage_type: &str,
) -> bool {
if self.creative {
return false;
}
@@ -1350,8 +1395,8 @@ impl Game<'_> {
.is_some_and(|t| t.contains(damage_type));
let blocking = self.player_blocking(Some(from), damage_type, false);
let raised = blocking.is_some();
// Melee: the attacker stands at `from`.
let attacker = (!projectile)
// Melee: the attacker stands at `from` (another player's hit has no mob behind it).
let attacker = (!projectile && damage_type != "minecraft:player_attack")
.then(|| {
self.mobs
.iter()
@@ -1536,12 +1581,24 @@ impl Game<'_> {
// Arrows also hit minecarts (VehicleEntity is pickable).
let mut arrow_targets = targets.clone();
arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds())));
// Mobs' projectiles also hit the guests (game/lan_mobs.rs).
let guests = self.lan_projectile_targets();
let mut arrow_targets_guests = arrow_targets.clone();
arrow_targets_guests.extend(guests.iter().copied());
let mut targets_guests = targets.clone();
targets_guests.extend(guests);
let pw = ProjWorld { w: &w, targets };
let pw_guests = ProjWorld {
w: &w,
targets: targets_guests,
};
projectiles.retain_mut(|p| {
let (keep, hit) = if p.arrow.is_some() {
horizon_client::arrows::tick(p, &scene, &arrow_targets)
} else {
p.tick(&pw)
let mob_shot = !matches!(p.owner, Some(Who::Player));
let (keep, hit) = match (p.arrow.is_some(), mob_shot) {
(true, false) => horizon_client::arrows::tick(p, &scene, &arrow_targets),
(true, true) => horizon_client::arrows::tick(p, &scene, &arrow_targets_guests),
(false, false) => p.tick(&pw),
(false, true) => p.tick(&pw_guests),
};
if let Some(a) = p.arrow.as_mut() {
arrow_events.extend(a.events.drain(..).map(|e| (p.position, e)));
@@ -1722,7 +1779,7 @@ impl Game<'_> {
self.creatures.projectiles.push(arrow);
}
}
fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
self.combat.projectile_owner = match p.owner {
Some(Who::Mob(id)) => Some(id),
_ => None,
@@ -1731,6 +1788,14 @@ impl Game<'_> {
Hit::Entity { at, .. } | Hit::Block { at, .. } => at,
Hit::None => return Ok(()),
};
if let Hit::Entity {
who: Who::Mob(id),
at,
} = hit
&& self.lan_projectile_hit(p, id, at)
{
return Ok(());
}
if matches!(
p.kind,
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge
+1 -2
View File
@@ -1541,8 +1541,7 @@ impl Game<'_> {
let target = (placed.x, placed.y, placed.z);
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);
self.apply_placed_item([target.0, target.1, target.2], &stack, false);
}
self.process_level_events()?;
Ok((shrink(stack), CLICK))
+1
View File
@@ -143,6 +143,7 @@ impl Game<'_> {
|| before(self.cart_hit().map(|h| h.1))
|| before(self.dragon_hit().map(|h| h.1))
|| before(self.mob_hit().map(|h| h.1))
|| before(self.guest_hit().map(|h| h.1))
}
/// `LocalPlayer.isHandsBusy`: paddling a boat.
fn hands_busy(&self) -> bool {
+11
View File
@@ -53,6 +53,8 @@ pub(super) struct LanHost {
pub broken: Vec<[f64; 3]>,
/// Hurt and death state of the mobs guests see.
mob_state: HashMap<u32, (i32, bool)>,
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
pub mob_players: HashMap<u32, u32>,
}
/// A stable UUID for an entity that has none.
@@ -335,6 +337,14 @@ impl Game<'_> {
"placed": g.placed,
"loaded": g.loaded,
"game_mode": g.game_mode,
"sneaking": g.sneaking,
"health": g.health,
// FoodData: food level, saturation and exhaustion.
"food": [
f64::from(g.food),
f64::from(g.saturation),
g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)),
],
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
// The armour the host draws on this guest, head to feet.
@@ -454,6 +464,7 @@ impl Game<'_> {
play: HashMap::new(),
broken: Vec::new(),
mob_state: HashMap::new(),
mob_players: HashMap::new(),
});
self.audio.capture = Some(Vec::new());
Ok(())
+136 -28
View File
@@ -11,8 +11,11 @@ use horizon_client::{
containers::BlockEntity,
entities::Experience,
items::ItemStack,
lan::{guest::SPECTATOR, menu::Rules},
motion::{MotionWorld, PlayerMotion},
lan::{
guest::SPECTATOR,
menu::{Rules, Slots},
},
motion::{MotionEvent, MotionWorld, PlayerMotion},
};
use horizon_core::geometry::Vec3;
use horizon_protocol::{
@@ -145,10 +148,22 @@ impl Game<'_> {
self.right = play.using.is_some() || self.using.is_some();
let riding = self.riding.take();
let host_station = self.station.take();
// The guest's own ender inventory; one the host has open goes back
// into the host's while the guest acts.
let host_ender = self.ender_open;
self.close_ender_chest();
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
self.lan_acting = Some(conn);
self.lan_acting_name = Some(g.name.clone());
self.lan_acting_uuid = Some(g.uuid);
let result = f(self);
self.lan_acting = None;
self.lan_acting_name = None;
self.lan_acting_uuid = None;
// An ender chest the guest opened: the menu shows their inventory
// itself (lan_open_container), not a stand-in block entity.
self.close_ender_chest();
// What the action opened: handed to the guest instead of the host.
let opened = self.container.take();
@@ -172,6 +187,13 @@ impl Game<'_> {
self.keys.remove(&KeyCode::ShiftLeft);
}
let g = &mut host.hub.guests[i];
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
if let Some(key) = host_ender {
self.world
.block_entities
.insert(key, BlockEntity::Chest(self.ender_items.clone()));
self.ender_open = Some(key);
}
let new_xp = std::mem::replace(&mut self.experience, xp);
g.xp_level = new_xp.level;
g.xp_progress = new_xp.progress;
@@ -240,30 +262,51 @@ impl Game<'_> {
/// Hand a container the guest opened over (ServerPlayer.openMenu);
/// false when it is not one a guest can open.
fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) -> bool {
let Some(entity) = self.world.block_entities.get(&pos) else {
return false;
};
let (menu, title) = match entity {
BlockEntity::Chest(items) => match items.len() {
27 => ("minecraft:generic_9x3", "container.chest"),
9 => ("minecraft:generic_3x3", "container.dispenser"),
5 => ("minecraft:hopper", "container.hopper"),
_ => return false,
},
_ => return false,
};
let name = &self
.res
.facts
.get(self.world.block(pos.0, pos.1, pos.2))
.name;
let title = match &**name {
"minecraft:barrel" => "container.barrel",
"minecraft:dropper" => "container.dropper",
n if n.ends_with("shulker_box") => "container.shulkerBox",
_ => title,
let (menu, title, slots) = if &**name == "minecraft:ender_chest" {
// EnderChestBlock.useWithoutItem: the player's own inventory.
(
"minecraft:generic_9x3",
"container.enderchest",
Slots::Ender,
)
} else if let Some((other, right)) = self.chest_partner(pos) {
// ChestBlock.combine: the right half's slots come first.
let halves = if right {
Slots::Double(pos, other)
} else {
Slots::Double(other, pos)
};
("minecraft:generic_9x6", "container.chestDouble", halves)
} else {
let Some(BlockEntity::Chest(items)) = self.world.block_entities.get(&pos) else {
return false;
};
let (menu, title) = match items.len() {
27 => ("minecraft:generic_9x3", "container.chest"),
9 => ("minecraft:generic_3x3", "container.dispenser"),
5 => ("minecraft:hopper", "container.hopper"),
_ => return false,
};
let title = match &**name {
"minecraft:barrel" => "container.barrel",
"minecraft:dropper" => "container.dropper",
n if n.ends_with("shulker_box") => "container.shulkerBox",
_ => title,
};
(menu, title, Slots::Block(pos))
};
let Some(items) = host
.hub
.guest(conn)
.and_then(|g| slots.read(&self.world, g))
else {
return false;
};
let items = entity.slots().to_vec();
// ServerPlayer.openMenu closes the menu that was open.
self.guest_container_closed(host, conn);
host.hub.open_container(
@@ -271,6 +314,7 @@ impl Game<'_> {
menu,
horizon_protocol::text::translatable(title, &[]),
pos,
slots,
items,
);
true
@@ -401,8 +445,13 @@ impl Game<'_> {
if spectator {
return;
}
// handleUseItem: the client's rotation, then the item alone. What it
// looked at a moment ago (a block, a mob) is UseItemOn's or Interact's.
self.as_guest(host, conn, |g| {
(g.yaw, g.pitch) = (p.yaw, p.pitch);
g.lan_item_only = true;
let _ = g.use_item();
g.lan_item_only = false;
});
}
S::Attack(p) => self.guest_attack(host, conn, p.id),
@@ -582,6 +631,12 @@ impl Game<'_> {
if host.hub.guests[gi].spectator() {
return;
}
if let Some(victim) = Self::pvp_victim(host, conn, id) {
if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) {
self.pvp_land(host, victim, &strike);
}
return;
}
let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch);
if self.look_at_entity(host, gi, id).is_none() {
return;
@@ -589,6 +644,10 @@ impl Game<'_> {
self.as_guest(host, conn, |g| {
g.attack();
});
// The mob now answers to this guest (game/lan_mobs.rs).
if let Ok(id) = u32::try_from(id) {
host.mob_players.insert(id, conn);
}
host.hub.guests[gi].yaw = old_yaw;
host.hub.guests[gi].pitch = old_pitch;
}
@@ -766,23 +825,35 @@ impl Game<'_> {
}
/// The guest's body on the server each tick: ServerPlayer.tick's damage
/// clock and Entity.baseTick's fluid phase, then
/// ServerPlayer.doCheckFallDamage for each move the guest made (the fall
/// distance grows while they go down and hurts them where they land, as
/// the host's own landing does; water resets it, lava halves it), then
/// regeneration and the food tick (ServerPlayer.doTick).
/// clock and Entity.baseTick's fluid phase (burning), then for each move
/// the guest made ServerGamePacketListenerImpl.handleMovePlayer's jump
/// (`ServerPlayer.jumpFromGround`'s exhaustion),
/// ServerPlayer.doCheckFallDamage (the fall distance grows while they go
/// down and hurts them where they land, as the host's own landing does;
/// water resets it, lava halves it) and checkMovementStatistics (the
/// exhaustion of sprinting and swimming), then LivingEntity.baseTick's
/// hazards (drowning, lava, fire blocks, suffocation, the void), and
/// regeneration and the food tick (ServerPlayer.doTick). Their hurt
/// sounds are heard at the guest.
fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) {
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
let moves = std::mem::take(&mut g.moves);
let from_ground = if moves.is_empty() {
g.on_ground
} else {
g.moves_from_ground
};
if g.spectator() {
return;
}
self.as_guest(host, conn, |game| {
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
let at = g.position;
let sounds = self.as_guest(host, conn, |game| {
let (rules, health) = (game.world.health_rules, &game.motion.health);
let Some(player) = game.player.as_mut() else {
return;
return Vec::new();
};
let mut w = MotionWorld {
entities: &[],
@@ -794,21 +865,58 @@ impl Game<'_> {
};
w.player.health.advance_clock();
let _ = w.fluid_base_tick();
w.player.ground.on_ground = from_ground;
for (moved, on_ground) in moves {
let movement = Vec3::new(moved[0], moved[1], moved[2]);
if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 {
let sprinting = w.player.sprinting;
w.player
.health
.food
.add_exhaustion(if sprinting { 0.2 } else { 0.05 });
}
let landed = (|| -> horizon_client::Result<()> {
w.set_on_ground_with_movement(on_ground, false, movement)?;
let pos = w.legacy_on_position()?;
let state = w.block_state(pos)?;
w.check_fall_damage(moved[1], on_ground, state, pos)
w.check_fall_damage(moved[1], on_ground, state, pos)?;
w.check_movement_statistics(movement)
})();
if landed.is_err() {
break;
}
}
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
let _ = w.player.peaceful_regeneration(rules);
let _ = w.player.food_tick(health, rules);
std::mem::take(&mut w.player.events)
.into_iter()
.filter_map(|e| match e {
MotionEvent::HurtSound(sound) => Some(sound),
_ => None,
})
.collect::<Vec<_>>()
});
for sound in sounds.into_iter().flatten() {
self.player_hurt_sound(sound, at);
}
}
/// `Player.isInWall`: a suffocating block in the 0.48-wide box at the
/// eyes. Suffocating is a full collision box that is also a full render
/// cube (`BlockBehaviour.isSuffocating`'s default; glass and the like
/// opt out), as the mobs' check has it.
fn in_wall(&self, at: [f64; 3], eye_height: f64) -> bool {
let (y, half) = ((at[1] + eye_height).floor() as i32, 0.24);
let range = |v: f64| (v - half).floor() as i32..=(v + half).floor() as i32;
range(at[0]).any(|x| {
range(at[2]).any(|z| {
let f = self.res.facts.get(self.world.block(x, y, z));
f.full_collision && f.solid_render
})
})
}
/// The crack animation other players see.
+305
View File
@@ -0,0 +1,305 @@
//! Mobs and the guests of an open world. The mob code sees one player
//! (`MobWorld.player`, `Who::Player`); with guests on, each mob sees the
//! player vanilla's `Level.getNearestPlayer` would give it, and keeps the
//! guest it targets until it lets go. What it then does to `Who::Player`
//! (hits, pushes, fire, its projectiles) runs with that guest swapped in.
use super::{Game, lan::LanHost};
use horizon_client::{
mobs::{Mob, MobEvent, PlayerView, Who},
projectiles::{Hit, Projectile},
};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_protocol::packets::play::{self, Clientbound as C};
/// The guests mobs can see this tick, by connection.
pub(super) type GuestViews = Vec<(u32, PlayerView)>;
/// The player a mob sees this tick: `None` for the host, else a guest.
/// A mob that targets a guest, or that a guest hurt in the last 100 ticks
/// (`LivingEntity.getLastHurtByMob`), keeps them while they are still a
/// valid target; otherwise it sees the nearest player
/// (`TargetingConditions`: alive, neither creative nor spectator), or the
/// nearest one that is not a spectator if none qualifies.
pub(super) fn player_for(
m: &Mob,
host: Option<&PlayerView>,
guests: &GuestViews,
bound: Option<u32>,
) -> Option<u32> {
let targeting = m.ai.target == Some(Who::Player)
|| m.ai.last_hurt_by == Some(Who::Player) && m.age as i32 - m.ai.last_hurt_by_time <= 100;
choose(m.position, targeting, host, guests, bound)
}
fn choose(
at: Vec3,
targeting: bool,
host: Option<&PlayerView>,
guests: &GuestViews,
bound: Option<u32>,
) -> Option<u32> {
let targetable = |v: &PlayerView| v.alive && !v.creative && !v.spectator;
if targeting
&& let Some(conn) = bound
&& guests.iter().any(|(c, v)| *c == conn && targetable(v))
{
return Some(conn);
}
let d = |v: &PlayerView| at.distance_squared(v.position);
let nearest = |ok: &dyn Fn(&PlayerView) -> bool| {
let mut best = host.filter(|v| ok(v)).map(|v| (None, d(v)));
for (conn, v) in guests.iter().filter(|(_, v)| ok(v)) {
if best.is_none_or(|(_, b)| d(v) < b) {
best = Some((Some(*conn), d(v)));
}
}
best
};
nearest(&targetable)
.or_else(|| nearest(&|v: &PlayerView| v.alive && !v.spectator))
.and_then(|(conn, _)| conn)
}
/// The events of a mob's tick that act on the player it sees.
pub(super) fn acts_on_player(e: &MobEvent) -> bool {
matches!(
e,
MobEvent::AttackPlayer(..)
| MobEvent::DamagePlayer { .. }
| MobEvent::Push {
target: Who::Player,
..
}
| MobEvent::Ignite {
target: Who::Player,
..
}
| MobEvent::Launch {
target: Who::Player,
..
}
)
}
impl Game<'_> {
/// How mobs see each guest in play (`player_view` with the guest swapped
/// in; what the host alone tracks, such as its last attacker, stays out).
pub(super) fn lan_guest_views(&mut self) -> GuestViews {
let Some(mut host) = self.lan.take() else {
return Vec::new();
};
let conns: Vec<(u32, u128, [f64; 3])> = host
.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead)
.map(|g| {
let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]);
(g.conn, g.uuid, moved)
})
.collect();
let mut views = Vec::new();
for (conn, uuid, moved) in conns {
if let Some(Some(mut v)) = self.as_guest(&mut host, conn, |g| g.player_view()) {
v.hurt_by = None;
v.last_hurt = None;
v.hero = false;
v.velocity = Vec3::new(moved[0], moved[1], moved[2]);
v.uuid = horizon_client::lan::playerdata::uuid_ints(uuid);
v.allies = Default::default();
views.push((conn, v));
}
}
self.lan = Some(host);
views
}
/// Mob events aimed at a guest, run as that guest (`guest_hit_by`).
pub(super) fn lan_guest_mob_events(&mut self, events: Vec<(u32, MobEvent)>) {
if events.is_empty() {
return;
}
let Some(mut host) = self.lan.take() else {
return;
};
for (conn, e) in events {
self.guest_hit_by(&mut host, conn, |g| {
let _ = g.handle_mob_events(vec![e]);
});
}
self.lan = Some(host);
}
/// The guests a projectile can hit, under their entity ids.
pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> {
let Some(host) = self.lan.as_ref() else {
return Vec::new();
};
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g)))
.collect()
}
/// A projectile that hit a guest: its hit runs as theirs. False when
/// `id` is not a guest.
pub(super) fn lan_projectile_hit(&mut self, p: &Projectile, id: u32, at: Vec3) -> bool {
let Some(mut host) = self.lan.take() else {
return false;
};
let conn = host
.hub
.guests
.iter()
.find(|g| g.entity_id as u32 == id)
.map(|g| g.conn);
if let Some(conn) = conn {
self.guest_hit_by(&mut host, conn, |g| {
let hit = Hit::Entity {
who: Who::Player,
at,
};
let _ = g.projectile_hit(p, hit);
});
}
self.lan = Some(host);
conn.is_some()
}
}
impl Game<'_> {
/// Hurt a guest: `f` runs as them, and the knockback it gave reaches
/// their client (`hurtMarked`: ClientboundSetEntityMotionPacket).
pub(super) fn guest_hit_by<R>(
&mut self,
host: &mut LanHost,
conn: u32,
f: impl FnOnce(&mut Self) -> R,
) -> Option<R> {
let (result, pushed) = self.as_guest(host, conn, |g| {
let before = g.player.as_ref().map(|p| p.velocity);
let result = f(g);
let after = g.player.as_ref().map(|p| p.velocity);
(result, after.filter(|v| Some(*v) != before))
})?;
if let (Some(v), Some(g)) = (pushed, host.hub.guest(conn)) {
g.send(&C::SetEntityMotion(play::SetEntityMotion {
id: g.entity_id,
velocity: [v.x, v.y, v.z],
}));
}
Some(result)
}
}
/// A guest as the blocks that look for players see them
/// (`PlayerDetector`, `level.getPlayers`: the dead ones too).
pub(super) struct Present {
pub uuid: [i32; 4],
pub position: [f64; 3],
pub eye: [f64; 3],
pub height: f32,
pub creative: bool,
pub spectator: bool,
pub alive: bool,
}
impl Game<'_> {
/// Every guest in the world (`ServerLevel.getPlayers` past the host).
pub(super) fn lan_present(&self) -> Vec<Present> {
let guests = self.lan.iter().flat_map(|h| &h.hub.guests);
guests
.filter(|g| g.placed && g.loaded)
.map(|g| {
let [x, y, z] = g.position;
Present {
uuid: horizon_client::lan::playerdata::uuid_ints(g.uuid),
position: g.position,
eye: [x, y + g.eye_height(), z],
height: if g.sneaking { 1.5 } else { 1.8 },
creative: g.creative(),
spectator: g.spectator(),
alive: !g.dead,
}
})
.collect()
}
/// The UUID of the player acting: the guest `as_guest` runs, else the host.
pub(super) fn acting_uuid(&self) -> [i32; 4] {
self.lan_acting_uuid
.map(horizon_client::lan::playerdata::uuid_ints)
.or(self.level.player_uuid)
.unwrap_or_default()
}
}
/// A guest's bounding box (0.6 wide, 1.8 tall, 1.5 crouching).
pub(super) fn guest_bounds(g: &horizon_client::lan::guest::Guest) -> Aabb {
let [x, y, z] = g.position;
let height = if g.sneaking { 1.5 } else { 1.8 };
Aabb::new(
Vec3::new(x - 0.3, y, z - 0.3),
Vec3::new(x + 0.3, y + height, z + 0.3),
)
}
#[cfg(test)]
mod tests {
use super::*;
fn view(x: f64, creative: bool) -> PlayerView {
PlayerView {
position: Vec3::new(x, 64.0, 0.0),
bounds: Aabb::new(Vec3::new(x, 64.0, 0.0), Vec3::new(x, 65.8, 0.0)),
eye: [x, 65.62, 0.0],
alive: true,
creative,
sneaking: false,
look: [0.0; 3],
main_hand: None,
off_hand: None,
head: None,
armor_cover: 0.0,
spectator: false,
gold_armor: false,
hurt_by: None,
last_hurt: None,
velocity: Vec3::ZERO,
yaw: 0.0,
hero: false,
uuid: [0; 4],
allies: Default::default(),
}
}
const MOB: Vec3 = Vec3::new(0.0, 64.0, 0.0);
#[test]
fn the_nearest_survival_player_is_seen() {
let host = view(10.0, false);
let guests = vec![(7, view(3.0, false)), (8, view(-5.0, false))];
assert_eq!(choose(MOB, false, Some(&host), &guests, None), Some(7));
// A creative guest is passed over for the host further away.
let guests = vec![(7, view(3.0, true))];
assert_eq!(choose(MOB, false, Some(&host), &guests, None), None);
// Nobody targetable: the nearest one is still seen.
let host = view(10.0, true);
assert_eq!(choose(MOB, false, Some(&host), &guests, None), Some(7));
assert_eq!(choose(MOB, false, None, &Vec::new(), None), None);
}
#[test]
fn a_targeted_guest_stays_the_target() {
let host = view(1.0, false);
let guests = vec![(7, view(12.0, false))];
assert_eq!(choose(MOB, true, Some(&host), &guests, Some(7)), Some(7));
// Gone creative: the mob looks again.
let guests = vec![(7, view(12.0, true))];
assert_eq!(choose(MOB, true, Some(&host), &guests, Some(7)), None);
// Without a target the nearest player wins.
let guests = vec![(7, view(12.0, false))];
assert_eq!(choose(MOB, false, Some(&host), &guests, Some(7)), None);
}
}
+110
View File
@@ -0,0 +1,110 @@
//! Players hitting players in an open world (`Player.attack` on a player):
//! the host hits a guest, a guest hits the host or another guest. The hit
//! is worked out as the attacker (weapon, attack strength, critical hit,
//! enchantments, a mace's smash) and lands on the victim like any player
//! attack (blocking, armour, knockback), when the `pvp` game rule allows it
//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`).
use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector};
/// Who a player's attack lands on.
#[derive(Clone, Copy)]
pub(super) enum Victim {
Host,
Guest(u32),
}
/// The attacker's side of the hit.
pub(super) struct Strike {
amount: f32,
scale: f32,
crit: bool,
from: [f64; 3],
}
impl Game<'_> {
/// The guest on the host's crosshair and how far, within reach.
pub(super) fn guest_hit(&self) -> Option<(u32, f64)> {
let host = self.lan.as_ref()?;
let eye = self.eye_position()?;
let dir = view_vector(self.yaw, self.pitch);
let reach = if self.creative { 5.0 } else { 3.0 };
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?)))
.min_by(|a, b| a.1.total_cmp(&b.1))
}
/// The host's attack on the guest under the crosshair, when no mob or
/// block is nearer.
pub(super) fn attack_guest(&mut self) -> bool {
let Some((conn, d)) = self.guest_hit() else {
return false;
};
if self.mob_hit().is_some_and(|(_, m)| m < d) || !self.before_block(d) {
return false;
}
let Some(mut host) = self.lan.take() else {
return false;
};
if let Some(strike) = self.pvp_strike() {
self.pvp_land(&mut host, Victim::Guest(conn), &strike);
}
self.lan = Some(host);
true
}
/// The player `id` that guest `conn` attacks, if it is one.
pub(super) fn pvp_victim(host: &LanHost, conn: u32, id: i32) -> Option<Victim> {
if id == host.host_entity {
return Some(Victim::Host);
}
host.hub
.guests
.iter()
.find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead)
.map(|g| Victim::Guest(g.conn))
}
/// The attacker's side of `Player.attack` (the host, or a guest swapped
/// in): the damage, the charge reset, the exhaustion and the swing.
pub(super) fn pvp_strike(&mut self) -> Option<Strike> {
let p = self.player.as_ref()?;
let from = [p.position.x, p.position.y, p.position.z];
let (amount, scale, crit) = self.melee_damage("minecraft:player");
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
{
p.health.food.exhaustion = (p.health.food.exhaustion + 0.1).min(40.0);
}
self.swing_arm();
Some(Strike {
amount,
scale,
crit,
from,
})
}
/// The hit landing on the victim, then the attacker's attack sound.
pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) {
let hurt = self.ui.rules.bool("pvp")
&& match victim {
Victim::Host => self.mob_hits_player(s.amount, s.from, "minecraft:player_attack"),
Victim::Guest(conn) => self
.guest_hit_by(host, conn, |g| {
g.mob_hits_player(s.amount, s.from, "minecraft:player_attack")
})
.unwrap_or(false),
};
let sound = match (hurt, s.crit, s.scale > 0.9) {
(false, ..) => "minecraft:entity.player.attack.nodamage",
(true, true, _) => "minecraft:entity.player.attack.crit",
(true, false, true) => "minecraft:entity.player.attack.strong",
(true, false, false) => "minecraft:entity.player.attack.weak",
};
self.audio.play(sound, Some(s.from), 1.0, 1.0);
}
}
+133 -80
View File
@@ -6,7 +6,10 @@
//! objective displayed below names. Other players' names (on a LAN host
//! or a server) show whenever `LivingEntityRenderer.shouldShowName` allows.
use super::{Game, view_vector};
use horizon_client::{mesher::Vertex, mobs::Mob, save::uuid_text, scoreboard as sb, text::Text};
use horizon_client::{
block_entity_render::vertex_light, mesher::Vertex, mobs::Mob, save::uuid_text,
scoreboard as sb, text::Text,
};
impl Game<'_> {
/// A named name tag names the mob under the crosshair.
@@ -69,16 +72,11 @@ impl Game<'_> {
pub(super) fn shown_name_tags(&self, camera: glam::DVec3) -> Vec<String> {
self.name_tags(camera, 1.0)
.into_iter()
.filter_map(|(_, lines, _)| lines.last().map(|(t, _)| t.plain()))
.filter_map(|t| t.lines.last().map(|(t, _)| t.plain()))
.collect()
}
/// Each name tag: where it hangs, its lines (text, lift) and its light.
#[allow(clippy::type_complexity)]
fn name_tags(
&self,
camera: glam::DVec3,
alpha: f64,
) -> Vec<(glam::DVec3, Vec<(Text, f64)>, u32)> {
/// Each name tag this frame.
fn name_tags(&self, camera: glam::DVec3, alpha: f64) -> Vec<NameTag> {
let target = self.mob_hit().map(|(i, _)| self.mobs[i].id);
let viewer = self.player_team();
let mut tags = Vec::new();
@@ -128,8 +126,10 @@ impl Game<'_> {
self.spectator(),
m.has_effect("minecraft:invisibility"),
);
// Entity.isDiscrete: a crouching player.
let discrete = player && m.extra.crouching;
let view = sb::NameView {
discrete: player && m.extra.crouching,
discrete,
distance_sqr,
invisible_to_viewer: invisible,
hud_hidden: self.ui.hide_gui,
@@ -164,91 +164,144 @@ impl Game<'_> {
(m.position.y + height).floor() as i32,
m.position.z.floor() as i32,
);
let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8);
tags.push((p, lines, light));
tags.push(NameTag {
at: p,
lines,
light: l,
discrete,
});
}
tags
}
pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
/// `SubmitNodeCollection.submitNameTag`: a discrete name is drawn once,
/// faded, on its background; any other in full over the world, its faded
/// copy and background in `see_through`, over everything.
pub(super) fn name_tag_geometry(
&self,
camera: glam::DVec3,
alpha: f64,
out: &mut Vec<Vertex>,
see_through: &mut Vec<Vertex>,
) {
// The text alpha that goes with getBackgroundOpacity(0.25):
// max((0.25 + 0.75) / 2, 0.5), as ARGB.color (the floor of 255 times it).
const FADED: u32 = 0x7F;
for tag in self.name_tags(camera, alpha) {
let o = tag.at - camera;
if tag.discrete {
self.name_tag_quads(o, &tag.lines, FADED, true, 0, vertex_light(tag.light), out);
continue;
}
// LightCoordsUtil.lightCoordsWithEmission(lightCoords, 2).
let lit = (tag.light >> 4).max(2) << 4 | (tag.light & 15).max(2);
self.name_tag_quads(o, &tag.lines, 0xFF, false, 0, vertex_light(lit), out);
// RenderPipelines.TEXT_SEE_THROUGH: no depth test, no lightmap.
self.name_tag_quads(o, &tag.lines, FADED, true, 2, 0, see_through);
}
}
/// The lines of one name tag, `o` from the camera: the text at
/// `text_alpha` in its layer, on the translucent black background
/// (unlit, a hair behind) when `background`.
#[allow(clippy::too_many_arguments)]
fn name_tag_quads(
&self,
o: glam::DVec3,
lines: &[(Text, f64)],
text_alpha: u32,
background: bool,
text_layer: u32,
light: u32,
out: &mut Vec<Vertex>,
) {
// Options.getBackgroundOpacity(0.25) black, as ARGB.color.
const BACKGROUND: u32 = 0x3F00_0000;
let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
let up = right.cross(forward).normalize_or_zero();
let white = self.res.atlas.font.white();
let away = forward.as_vec3() * 0.002;
for (p, lines, light) in self.name_tags(camera, alpha) {
for (text, lift) in lines {
let o = (p + glam::DVec3::new(0.0, lift, 0.0) - camera).as_vec3();
let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025);
// Text space: x right, y down (scale 0.025, -0.025).
let at = |x: f32, y: f32| o + r * x - u * y;
let chars: Vec<(char, u32)> = text
.spans
.iter()
.flat_map(|s| {
let rgb = s.style.color.unwrap_or(0xFF_FF_FF);
// RGBA8, alpha in the top byte.
let color = 0xFF00_0000
| ((rgb & 0xFF) << 16)
| (rgb & 0xFF00)
| ((rgb >> 16) & 0xFF);
s.text.chars().map(move |c| (c, color))
})
.collect();
let width: f32 = chars
.iter()
.map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1))
.sum();
let x0 = -(width / 2.0).trunc();
let y0 = if text.plain() == "deadmau5" {
-10.0
} else {
0.0
};
// `background`: unlit (vertex colour only) and a hair behind the text.
let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, background: bool| {
let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])];
let uvs = [
[uv[0], uv[3]],
[uv[2], uv[3]],
[uv[2], uv[1]],
[uv[0], uv[1]],
];
for ((x, y), uv) in corners.into_iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: (at(x, y) + if background { away } else { glam::Vec3::ZERO })
.to_array(),
uv,
layer: if background { 2 } else { 0 },
color,
light,
});
}
};
// Background: Options.getBackgroundOpacity(0.25) black.
for (text, lift) in lines {
let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).as_vec3();
let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025);
// Text space: x right, y down (scale 0.025, -0.025).
let at = |x: f32, y: f32| o + r * x - u * y;
let chars: Vec<(char, u32)> = text
.spans
.iter()
.flat_map(|s| {
let rgb = s.style.color.unwrap_or(0xFF_FF_FF);
// RGBA8, alpha in the top byte.
let color = text_alpha << 24
| ((rgb & 0xFF) << 16)
| (rgb & 0xFF00)
| ((rgb >> 16) & 0xFF);
s.text.chars().map(move |c| (c, color))
})
.collect();
let width: f32 = chars
.iter()
.map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1))
.sum();
let x0 = -(width / 2.0).trunc();
let y0 = if text.plain() == "deadmau5" {
-10.0
} else {
0.0
};
let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, behind: bool, layer: u32| {
let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])];
let uvs = [
[uv[0], uv[3]],
[uv[2], uv[3]],
[uv[2], uv[1]],
[uv[0], uv[1]],
];
for ((x, y), uv) in corners.into_iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: (at(x, y) + if behind { away } else { glam::Vec3::ZERO }).to_array(),
uv,
layer,
color,
light,
});
}
};
if background {
quad(
[x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0],
[white.u0, white.v0, white.u1, white.v1],
0x40_00_00_00,
BACKGROUND,
true,
2,
);
let mut x = x0;
for (ch, color) in chars {
let Some((g, advance)) = self.res.atlas.glyph(ch) else {
x += 6.0;
continue;
};
if ch != ' ' {
quad(
[x, y0, x + 8.0, y0 + 8.0],
[g.u0, g.v0, g.u1, g.v1],
color,
false,
);
}
x += advance;
}
let mut x = x0;
for (ch, color) in chars {
let Some((g, advance)) = self.res.atlas.glyph(ch) else {
x += 6.0;
continue;
};
if ch != ' ' {
quad(
[x, y0, x + 8.0, y0 + 8.0],
[g.u0, g.v0, g.u1, g.v1],
color,
false,
text_layer,
);
}
x += advance;
}
}
}
}
/// A name tag: where it hangs, its lines (text, lift), the packed light at
/// the entity and whether it is discrete.
struct NameTag {
at: glam::DVec3,
lines: Vec<(Text, f64)>,
light: u8,
discrete: bool,
}
+48 -2
View File
@@ -90,6 +90,8 @@ pub(super) struct Remote {
loaded_sent: bool,
/// Open container: (window id, menu name).
menu: Option<(i32, String)>,
/// The open menu's title as the server named it.
menu_title: Option<String>,
state_id: i32,
use_target: Option<[i32; 3]>,
entities: HashMap<i32, Tracked>,
@@ -231,6 +233,7 @@ impl Game<'_> {
carried: None,
loaded_sent: false,
menu: None,
menu_title: None,
state_id: 0,
use_target: None,
entities: HashMap::new(),
@@ -369,6 +372,12 @@ impl Game<'_> {
}
}
/// The server's last `n` chat lines, newest first.
pub(super) fn remote_chat(&self, n: usize) -> Option<Vec<String>> {
let r = self.remote.as_ref()?;
Some(r.chat.iter().rev().take(n).map(|l| l.0.clone()).collect())
}
/// Process everything the network thread received (once per frame, like
/// the client's packet processor).
pub(super) fn poll_remote(&mut self) -> Result<()> {
@@ -1046,6 +1055,12 @@ impl Game<'_> {
}
self.remove_entity(p.item);
}
// ClientPacketListener.handleSetEntityMotion: knockback on this player.
C::SetEntityMotion(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => {
if let Some(pl) = self.player.as_mut() {
pl.velocity = Vec3::new(p.velocity[0], p.velocity[1], p.velocity[2]);
}
}
C::HurtAnimation(p) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
m.hurt_time = 10;
@@ -2278,7 +2293,7 @@ impl Game<'_> {
if let Some(hit) = self.pick() {
self.send(S::PickItemFromBlock(play::PickItemFromBlock {
pos: hit.pos,
include_data: false,
include_data: self.has_control_down(),
}));
}
}
@@ -2545,6 +2560,7 @@ impl Game<'_> {
fn remote_close_local(&mut self) {
if let Some(r) = self.remote.as_mut() {
r.menu = None;
r.menu_title = None;
}
if self
.station
@@ -2673,19 +2689,49 @@ impl Game<'_> {
return;
}
};
let title = plain(
&p.title,
&self
.remote
.as_ref()
.map(|r| r.lang.clone())
.unwrap_or_default(),
);
if let Some(r) = self.remote.as_mut() {
r.menu = Some((p.container, menu.clone()));
r.menu_title = Some(title);
}
self.craft_size = if menu == "minecraft:crafting" { 3 } else { 2 };
self.container = None;
if let Some(entity) = entity {
let key = target.unwrap_or((i32::MIN, 0, 0));
// The clicked block shows the menu when it holds that container;
// an ender chest's or a double chest's slots are no one block's,
// so they go under a key no block has.
let holds = |k: &(i32, i32, i32)| {
let name = &self.res.facts.get(self.world.block(k.0, k.1, k.2)).name;
BlockEntity::for_block(name).is_some_and(|e| {
e.id() == entity.id() && e.slots().len() == entity.slots().len()
})
};
let key = target.filter(holds).unwrap_or((i32::MIN, 0, 0));
self.world.block_entities.insert(key, entity);
self.container = Some(key);
}
self.screen = Screen::Inventory;
self.capture(false);
}
/// A server's chest-like menu (`MenuType.GENERIC_9xN`): its rows and title.
pub(super) fn remote_chest_menu(&self) -> Option<(usize, String)> {
let r = self.remote.as_ref()?;
let rows = r
.menu
.as_ref()?
.1
.strip_prefix("minecraft:generic_9x")?
.parse()
.ok()?;
Some((rows, r.menu_title.clone().unwrap_or_default()))
}
pub(super) fn remote_respawn(&mut self) {
self.send(S::ClientCommand(play::ClientCommand { action: 0 }));
}
+47 -1
View File
@@ -5,7 +5,7 @@
//! `BrewingStandScreen`); item rules live in `horizon_client::stations`.
use super::{Game, Screen};
use horizon_client::{
brewing,
block_entity_item, brewing,
containers::BlockEntity,
enchant::Enchantments,
hud::{HudBatch, rgba},
@@ -1894,6 +1894,15 @@ impl Game<'_> {
self.res.names.item(&stack.item)
};
let mut lines = vec![(name, color)];
let translate = |k: &str| e.translate(k).map(str::to_owned);
// ItemContainerContents.addToTooltip.
let hover_name = |s: &ItemStack| {
s.custom_name()
.map_or_else(|| self.res.names.item(&s.item), str::to_owned)
};
for line in horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) {
lines.push((line, u32::MAX));
}
if stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" {
let scale = match &*stack.item {
"minecraft:lingering_potion" => 0.25,
@@ -1947,6 +1956,27 @@ impl Game<'_> {
let key = self.res.stations.banners.layer_key(layer);
lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255)));
}
// Spawner.appendHoverText: what a spawner or trial spawner item spawns.
if matches!(
&*stack.item,
"minecraft:spawner" | "minecraft:trial_spawner"
) {
let gray = rgba(170, 170, 170, 255);
match block_entity_item::spawner_entity(stack) {
Some(id) => {
let key = format!("entity.{}", id.replacen(':', ".", 1));
lines.push((self.translate(&key, &id), gray));
}
None => {
lines.push((String::new(), u32::MAX));
let desc1 =
self.translate("block.minecraft.spawner.desc1", "Interact with Spawn Egg:");
lines.push((desc1, gray));
let desc2 = self.translate("block.minecraft.spawner.desc2", "Sets Mob Type");
lines.push((format!(" {desc2}"), rgba(85, 85, 255, 255)));
}
}
}
if let Some(info) = self.res.items.get(&stack.item)
&& info.max_damage > 0
&& stack.damage > 0
@@ -1961,6 +1991,22 @@ impl Game<'_> {
u32::MAX,
));
}
// ItemStack.OP_NBT_WARNING, for a player with game master permission.
if self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) {
for (key, fallback) in [
("item.op_warning.line1", "Warning:"),
(
"item.op_warning.line2",
"Use of this item might lead to command execution.",
),
(
"item.op_warning.line3",
"Do not use unless you know the exact contents!",
),
] {
lines.push((self.translate(key, fallback), rgba(255, 85, 85, 255)));
}
}
lines
}
/// Menu state for the control socket.
+7 -29
View File
@@ -8,18 +8,6 @@ pub(super) fn is_shulker_box(name: &str) -> bool {
name.ends_with("shulker_box")
}
impl Game<'_> {
/// 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 {
@@ -29,22 +17,6 @@ impl Game<'_> {
.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 };
if !is_shulker_box(&stack.item) || data.container.is_empty() {
return;
}
if let Some(BlockEntity::Chest(items)) =
self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2]))
{
for (slot, s) in &data.container {
if let Some(cell) = items.get_mut(usize::from(*slot)) {
*cell = Some(s.clone());
}
}
}
}
/// ShulkerBoxSlot.mayPlace: no shulker box inside a shulker box.
pub(super) fn refuses(&self, slot: usize, stack: &ItemStack) -> bool {
(300..400).contains(&slot)
@@ -103,7 +75,7 @@ fn facing_step(facing: &str) -> (i32, i32) {
impl Game<'_> {
/// The other half of the open double chest and whether the open one is
/// the right half (`ChestBlock.getConnectedDirection`).
fn chest_partner(&self, key: (i32, i32, i32)) -> Option<((i32, i32, i32), bool)> {
pub(super) fn chest_partner(&self, key: (i32, i32, i32)) -> Option<((i32, i32, i32), bool)> {
let registry = self.res.assets.registry;
let state = registry.state(self.world.block(key.0, key.1, key.2))?;
if !matches!(
@@ -197,6 +169,9 @@ impl Game<'_> {
/// Rows of the open generic 9-wide container (`ChestMenu`), or None for
/// the other menus (hoppers, dispensers, shulker boxes, furnaces...).
pub(super) fn chest_rows(&self) -> Option<usize> {
if let Some((rows, _)) = self.remote_chest_menu() {
return Some(rows);
}
if !matches!(self.container_kind()?, BlockEntity::Chest(_)) {
return None;
}
@@ -213,6 +188,9 @@ impl Game<'_> {
}
/// The title of the open chest-like menu.
fn chest_title(&self, rows: usize) -> String {
if let Some((_, title)) = self.remote_chest_menu() {
return title;
}
let (key, fallback) = match self.container_block().as_deref() {
Some("minecraft:barrel") => ("container.barrel", "Barrel"),
Some("minecraft:ender_chest") => ("container.enderchest", "Ender Chest"),
@@ -32,11 +32,23 @@ impl TrialSpawnerLevel for GameLevel<'_, '_> {
self.game.ui.rules.bool("spawn_mobs")
}
fn players(&self) -> Vec<TrialPlayer> {
let guests = self.game.lan_present().into_iter().map(|g| TrialPlayer {
uuid: g.uuid,
block: g.position.map(|v| v.floor() as i32),
eye: g.eye,
creative: g.creative,
spectator: g.spectator,
position: g.position,
height: g.height,
alive: g.alive,
// Guests carry no effects yet.
omen: None,
});
let (Some(p), Some(view)) = (self.game.player.as_ref(), self.game.player_view()) else {
return Vec::new();
return guests.collect();
};
vec![TrialPlayer {
uuid: self.game.level.player_uuid.unwrap_or_default(),
let host = TrialPlayer {
uuid: self.game.acting_uuid(),
block: [p.position.x, p.position.y, p.position.z].map(|v| v.floor() as i32),
eye: view.eye,
creative: self.game.creative,
@@ -49,7 +61,8 @@ impl TrialSpawnerLevel for GameLevel<'_, '_> {
} else {
self.game.potions.effects.get("bad_omen").map(|_| Omen::Bad)
},
}]
};
std::iter::once(host).chain(guests).collect()
}
fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]> {
let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]);
+10 -5
View File
@@ -17,7 +17,7 @@ use horizon_core::random::LegacyRandom;
type Pos = (i32, i32, i32);
/// What a vault reads: the game time and the player.
/// What a vault reads: the game time and the players.
struct Players {
time: i64,
players: Vec<VaultPlayer>,
@@ -33,14 +33,19 @@ impl VaultLevel for Players {
impl Game<'_> {
fn vault_players(&self) -> Players {
let players = self.player.as_ref().map(|p| VaultPlayer {
uuid: self.level.player_uuid.unwrap_or_default(),
let host = self.player.as_ref().map(|p| VaultPlayer {
uuid: self.acting_uuid(),
block: [p.position.x, p.position.y, p.position.z].map(|v| v.floor() as i32),
spectator: self.spectator(),
});
let guests = self.lan_present().into_iter().map(|g| VaultPlayer {
uuid: g.uuid,
block: g.position.map(|v| v.floor() as i32),
spectator: g.spectator,
});
Players {
time: self.world.game_time,
players: players.into_iter().collect(),
players: host.into_iter().chain(guests).collect(),
}
}
/// The vault at `key` with its block's state and ominous flag.
@@ -143,7 +148,7 @@ impl Game<'_> {
let Some(stack) = held.cloned() else {
return Ok(false);
};
let player = self.level.player_uuid.unwrap_or_default();
let player = self.acting_uuid();
let used = self.with_vault(
(pos[0], pos[1], pos[2]),
|v, l, random, state, ominous, roll, events| {
+42 -8
View File
@@ -148,6 +148,8 @@ pub struct Frame<'a> {
pub clouds: Option<crate::clouds::Input<'a>>,
/// Additive translucent geometry after the entities (lightning, dragon rays).
pub additive: &'a [Vertex],
/// Name tags over everything, without depth (`TEXT_SEE_THROUGH`).
pub see_through: &'a [Vertex],
/// Camera-relative sun, moon and stars (drawn behind everything, additive).
pub celestial: &'a [Vertex],
/// First-person hand and held item, drawn after clearing depth.
@@ -263,6 +265,7 @@ pub struct Renderer {
cloud_uniform: wgpu::Buffer,
cloud_group: wgpu::BindGroup,
additive_pipeline: wgpu::RenderPipeline,
see_through_pipeline: wgpu::RenderPipeline,
celestial_pipeline: wgpu::RenderPipeline,
celestial_buffer: wgpu::Buffer,
panorama: panorama::Panorama,
@@ -1057,7 +1060,7 @@ impl Renderer {
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &entity_attributes,
})];
let entity_pipeline = |label, cull_mode, depth_write, bias, blend, clouds| {
let entity_pipeline = |label, cull_mode, depth_write, compare, bias, blend, clouds| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(if clouds {
@@ -1078,7 +1081,7 @@ impl Renderer {
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(depth_write),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
depth_compare: Some(compare),
stencil: Default::default(),
bias,
}),
@@ -1101,6 +1104,7 @@ impl Renderer {
"Breaking cracks",
Some(wgpu::Face::Back),
false,
wgpu::CompareFunction::GreaterEqual,
wgpu::DepthBiasState {
constant: 10,
slope_scale: 1.0,
@@ -1113,14 +1117,26 @@ impl Renderer {
"Clouds",
Some(wgpu::Face::Back),
true,
wgpu::CompareFunction::GreaterEqual,
Default::default(),
alpha_blend,
true,
);
// RenderPipelines.TEXT_SEE_THROUGH: translucent, no depth test or writes.
let see_through_pipeline = entity_pipeline(
"See-through text",
None,
false,
wgpu::CompareFunction::Always,
Default::default(),
alpha_blend,
false,
);
let entity_pipeline = entity_pipeline(
"Entities",
None,
true,
wgpu::CompareFunction::GreaterEqual,
Default::default(),
alpha_blend,
false,
@@ -1513,6 +1529,7 @@ impl Renderer {
cloud_uniform,
cloud_group,
additive_pipeline,
see_through_pipeline,
celestial_pipeline,
celestial_buffer,
panorama,
@@ -2282,9 +2299,13 @@ impl Renderer {
self.queue
.write_buffer(&self.outline, 0, bytemuck::cast_slice(&lines));
}
let [entity_quads, crumbling_quads, translucent_crumbling_quads] = self
.entity_batch
.update(frame.entities, frame.additive, frame.hand);
let [entity_quads, crumbling_quads, translucent_crumbling_quads] =
self.entity_batch.update(
frame.entities,
frame.additive,
frame.hand,
frame.see_through,
);
let world_quads = entity_quads + crumbling_quads + translucent_crumbling_quads;
let cloud_quads = if let Some(input) = &frame.clouds {
let (rebuilt, uniform) =
@@ -2315,6 +2336,7 @@ impl Renderer {
let all_entities = &self.entity_batch.combined;
let hand_quads = (frame.hand.len() / 4) as u32;
let additive_quads = (frame.additive.len() / 4) as u32;
let see_through_quads = (frame.see_through.len() / 4) as u32;
let entity_vertices = all_entities.len() as u64;
if entity_vertices > self.entity_capacity {
self.entity_capacity = entity_vertices.next_power_of_two();
@@ -2337,7 +2359,8 @@ impl Renderer {
bytemuck::cast_slice(&frame.celestial[..celestial_vertices]),
);
}
let max_quads = (world_quads + additive_quads + hand_quads).max(cloud_quads);
let max_quads =
(world_quads + additive_quads + hand_quads + see_through_quads).max(cloud_quads);
if max_quads > self.index_quads {
self.index_quads = max_quads.next_power_of_two();
self.indices = Self::quad_indices(&self.device, self.index_quads);
@@ -2523,6 +2546,17 @@ impl Renderer {
pass.set_vertex_buffer(0, self.cloud_buffer.slice(..));
pass.draw_indexed(0..cloud_quads * 6, 0, 0..1);
}
// LevelRenderer.executeSeeThrough, after the rest of the world.
if see_through_quads > 0 {
pass.set_pipeline(&self.see_through_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..see_through_quads * 6,
((world_quads + additive_quads + hand_quads) * 4) as i32,
0..1,
);
}
}
if let (true, Some((color, depth)), Some(size), Some(stages)) =
(pack, &scaled, self.world_post.size(), self.pack.as_mut())
@@ -2948,7 +2982,7 @@ mod tests {
.flat_map(|(layer, id)| quad(layer, id))
.collect();
let mut batch = super::EntityBatch::default();
let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6));
let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8));
let vertices = &batch.combined;
assert_eq!(counts, [4, 1, 1]);
assert_eq!(
@@ -2958,7 +2992,7 @@ mod tests {
.iter()
.map(|q| q[0].light)
.collect::<Vec<_>>(),
[0, 1, 3, 4, 2, 7, 5, 6]
[0, 1, 3, 4, 2, 7, 5, 6, 8]
);
}
#[test]
@@ -16,6 +16,7 @@ impl EntityBatch {
entities: &[Vertex],
additive: &[Vertex],
hand: &[Vertex],
see_through: &[Vertex],
) -> [u32; 3] {
let quads = entities.as_chunks::<4>().0;
for bucket in &mut self.buckets {
@@ -35,7 +36,8 @@ impl EntityBatch {
}
let entity_vertices = quads.len() * 4;
self.combined.reserve(
(entity_vertices + additive.len() + hand.len()).saturating_sub(self.combined.len()),
(entity_vertices + additive.len() + hand.len() + see_through.len())
.saturating_sub(self.combined.len()),
);
self.combined
.resize(entity_vertices, bytemuck::Zeroable::zeroed());
@@ -60,6 +62,7 @@ impl EntityBatch {
}
self.combined.extend_from_slice(additive);
self.combined.extend_from_slice(hand);
self.combined.extend_from_slice(see_through);
counts.map(|count| count as u32)
}
}
@@ -119,7 +122,7 @@ mod tests {
hand: &[Vertex],
) {
let (expected, counts) = baseline(entities, additive, hand);
assert_eq!(batch.update(entities, additive, hand), counts);
assert_eq!(batch.update(entities, additive, hand, &[]), counts);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&batch.combined),
bytemuck::cast_slice::<_, u8>(&expected)
@@ -190,7 +193,7 @@ mod tests {
equivalent(&mut batch, &entities, &additive, &hand);
for _ in 0..50 {
black_box(baseline(black_box(&entities), &additive, &hand));
black_box(batch.update(black_box(&entities), &additive, &hand));
black_box(batch.update(black_box(&entities), &additive, &hand, &[]));
black_box(&batch.combined);
}
let mut before = Vec::new();
@@ -203,7 +206,7 @@ mod tests {
before.push(start.elapsed().as_nanos() / 100);
let start = Instant::now();
for _ in 0..100 {
black_box(batch.update(black_box(&entities), &additive, &hand));
black_box(batch.update(black_box(&entities), &additive, &hand, &[]));
black_box(&batch.combined);
}
after.push(start.elapsed().as_nanos() / 100);
+64
View File
@@ -247,6 +247,36 @@ pub fn detail_lines(
lines
}
/// `ItemContainerContents.addToTooltip`: "count x name" for the first five
/// stacks, by slot, then how many more there are (an italic line).
pub fn container_lines(
stack: &ItemStack,
name: &dyn Fn(&ItemStack) -> String,
translate: &dyn Fn(&str) -> Option<String>,
) -> Vec<String> {
let Some(data) = stack.data() else {
return Vec::new();
};
let mut slots: Vec<&(u8, ItemStack)> = data.container.iter().collect();
slots.sort_by_key(|(slot, _)| *slot);
let count = translate("item.container.item_count").unwrap_or_else(|| "%s x %s".into());
let mut lines: Vec<String> = slots
.iter()
.take(5)
.map(|(_, s)| {
count
.replacen("%s", &s.count.to_string(), 1)
.replacen("%s", &name(s), 1)
})
.collect();
if slots.len() > 5 {
let more =
translate("item.container.more_items").unwrap_or_else(|| "and %s more...".into());
lines.push(more.replacen("%s", &(slots.len() - 5).to_string(), 1));
}
lines
}
/// Every line of `stack`'s tooltip, name first.
pub fn lines(
stack: &ItemStack,
@@ -262,6 +292,40 @@ pub fn lines(
mod tests {
use super::*;
#[test]
fn container_lines_list_five_stacks_then_how_many_more() {
let mut chest = ItemStack::new("minecraft:chest", 1);
for slot in [9u8, 1, 2, 3, 4, 5, 6] {
chest
.data_mut()
.container
.push((slot, ItemStack::new("minecraft:stone", u32::from(slot))));
}
let lang = |k: &str| {
Some(
match k {
"item.container.item_count" => "%s x %s",
"item.container.more_items" => "and %s more...",
_ => return None,
}
.to_owned(),
)
};
let name = |s: &ItemStack| s.item.trim_start_matches("minecraft:").to_owned();
assert_eq!(
container_lines(&chest, &name, &lang),
[
"1 x stone",
"2 x stone",
"3 x stone",
"4 x stone",
"5 x stone",
"and 2 more..."
]
);
assert!(container_lines(&ItemStack::new("minecraft:chest", 1), &name, &lang).is_empty());
}
#[test]
fn amounts_use_two_decimals_at_most() {
assert_eq!(format_amount(8.0), "8");
+26 -27
View File
@@ -2,7 +2,7 @@
//! level events, animations and block containers with their clicks.
use super::{
hub::Hub,
menu::{self, Menu, Rules, View},
menu::{self, Menu, Rules, Slots, View},
};
use crate::{items::ItemStack, world::World};
use horizon_protocol::{
@@ -143,6 +143,7 @@ impl Hub {
menu_kind: &str,
title: Tag,
pos: (i32, i32, i32),
slots: Slots,
items: Vec<Option<ItemStack>>,
) {
let Some(kind) = self
@@ -169,6 +170,7 @@ impl Hub {
window,
kind,
pos: Some(pos),
slots,
size: items.len(),
state: 0,
sent: Vec::new(),
@@ -265,10 +267,7 @@ impl Hub {
fn view_slot(&self, i: usize, world: &World, slot: usize) -> Option<ItemStack> {
let g = &self.guests[i];
match &g.menu {
Some(m) if slot < m.size => {
let e = world.block_entities.get(&m.pos?)?;
e.slots().get(slot).cloned().flatten()
}
Some(m) if slot < m.size => m.slots.get(world, g, slot),
Some(m) => g
.inventory
.get(player_slot(slot - m.size))
@@ -299,32 +298,32 @@ impl Hub {
if !window_ok || self.guests[i].spectator() {
return Vec::new();
}
let pos = self.guests[i].menu.as_ref().and_then(|m| m.pos);
let source = self.guests[i].menu.as_ref().map(|m| m.slots);
let mut drag = if in_menu {
self.guests[i].menu.as_mut().and_then(|m| m.drag.take())
} else {
self.guests[i].drag.take()
};
let (drops, changed) = {
let guest = &mut self.guests[i];
let mut entity = pos.and_then(|k| world.block_entities.get_mut(&k));
let slots = entity.as_mut().map(|e| e.slots_mut());
if in_menu && slots.is_none() {
return Vec::new();
}
let mut view = View {
guest,
container: slots,
};
menu::click(
&mut view,
&mut drag,
i32::from(p.slot),
i32::from(p.button),
p.input,
rules,
)
let guest = &mut self.guests[i];
let mut items = source.and_then(|s| s.read(world, guest));
if in_menu && items.is_none() {
return Vec::new();
}
let mut view = View {
guest,
container: items.as_deref_mut(),
};
let (drops, changed) = menu::click(
&mut view,
&mut drag,
i32::from(p.slot),
i32::from(p.button),
p.input,
rules,
);
if let (Some(source), Some(items)) = (source, items) {
source.write(world, guest, items);
}
if in_menu {
if let Some(m) = self.guests[i].menu.as_mut() {
m.drag = drag;
@@ -427,8 +426,8 @@ impl Hub {
else {
continue;
};
let (size, window, pos) = (menu.size, menu.window, menu.pos);
if !pos.is_some_and(|k| world.block_entities.contains_key(&k)) {
let (size, window, slots) = (menu.size, menu.window, menu.slots);
if !slots.valid(world) {
self.close_container_at(i);
continue;
}
+6
View File
@@ -84,6 +84,8 @@ pub struct Guest {
/// (`InventoryMenu.craftSlots`, `resultSlots`), which the game computes.
pub craft_grid: [Option<ItemStack>; 4],
pub craft_result: Option<ItemStack>,
/// The ender chest inventory (`PlayerEnderChestContainer`, 27 slots).
pub ender_items: Vec<Option<ItemStack>>,
pub health: f32,
pub food: i32,
pub saturation: f32,
@@ -102,6 +104,8 @@ pub struct Guest {
/// The moves accepted since the game last looked (movement, on ground),
/// for ServerPlayer.doCheckFallDamage.
pub moves: Vec<([f64; 3], bool)>,
/// Whether the guest was on the ground before the first of `moves`.
pub moves_from_ground: bool,
pub dead: bool,
/// The join packets were sent (PlayerList.placeNewPlayer ran).
pub placed: bool,
@@ -163,6 +167,7 @@ impl Guest {
carried: None,
craft_grid: Default::default(),
craft_result: None,
ender_items: vec![None; 27],
health: 20.0,
food: 20,
saturation: 5.0,
@@ -178,6 +183,7 @@ impl Guest {
joined_tick: 0,
ticks: 0,
moves: Vec::new(),
moves_from_ground: false,
dead: false,
placed: false,
menu: None,
+3
View File
@@ -1461,6 +1461,9 @@ impl Hub {
let moved = pos.map_or([0.0; 3], |_| {
[0, 1, 2].map(|k| g.position[k] - g.previous_position[k])
});
if g.moves.is_empty() {
g.moves_from_ground = g.on_ground;
}
g.moves.push((moved, flags & 1 != 0));
if let Some((yaw, pitch)) = rot
&& yaw.is_finite()
+72 -1
View File
@@ -4,7 +4,7 @@
//! clone, throw, quick craft (drag) and pickup all; items thrown out of a
//! menu are returned for the game to drop.
use super::guest::Guest;
use crate::items::ItemStack;
use crate::{items::ItemStack, world::World};
/// What the menus need to know about items.
pub trait Rules {
@@ -19,6 +19,8 @@ pub struct Menu {
/// The `minecraft:menu` registry id.
pub kind: i32,
pub pos: Option<(i32, i32, i32)>,
/// Where the container's slots live.
pub slots: Slots,
/// Slots of the container itself (without the 36 inventory slots).
pub size: usize,
pub state: i32,
@@ -28,6 +30,75 @@ pub struct Menu {
pub drag: Option<(u8, Vec<usize>)>,
}
/// Where the slots of a container menu live.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Slots {
/// One block entity.
Block((i32, i32, i32)),
/// A double chest (`CompoundContainer`): the first half's slots, then
/// the second's.
Double((i32, i32, i32), (i32, i32, i32)),
/// The player's own ender chest inventory (`PlayerEnderChestContainer`).
Ender,
}
impl Slots {
fn halves(self) -> Vec<(i32, i32, i32)> {
match self {
Slots::Block(k) => vec![k],
Slots::Double(a, b) => vec![a, b],
Slots::Ender => Vec::new(),
}
}
/// Whether the block entities behind the slots are still there
/// (`Container.stillValid`).
pub fn valid(self, world: &World) -> bool {
self.halves()
.iter()
.all(|k| world.block_entities.contains_key(k))
}
/// Container slot `n`.
pub fn get(self, world: &World, guest: &Guest, mut n: usize) -> Option<ItemStack> {
if self == Slots::Ender {
return guest.ender_items.get(n).cloned().flatten();
}
for k in self.halves() {
let slots = world.block_entities.get(&k)?.slots();
if n < slots.len() {
return slots[n].clone();
}
n -= slots.len();
}
None
}
/// Every container slot, in menu order.
pub fn read(self, world: &World, guest: &Guest) -> Option<Vec<Option<ItemStack>>> {
if self == Slots::Ender {
return Some(guest.ender_items.clone());
}
let mut items = Vec::new();
for k in self.halves() {
items.extend_from_slice(world.block_entities.get(&k)?.slots());
}
Some(items)
}
/// Store what `read` gave, changed.
pub fn write(self, world: &mut World, guest: &mut Guest, items: Vec<Option<ItemStack>>) {
if self == Slots::Ender {
guest.ender_items = items;
return;
}
let mut rest = items.into_iter();
for k in self.halves() {
if let Some(e) = world.block_entities.get_mut(&k) {
for slot in e.slots_mut() {
*slot = rest.next().flatten();
}
}
}
}
}
/// Slots of a menu seen as one list.
pub struct View<'a> {
pub guest: &'a mut Guest,
+6 -1
View File
@@ -18,7 +18,8 @@ pub fn path(world: &Path, uuid: u128) -> PathBuf {
.join(format!("{}.dat", uuid_string(uuid)))
}
fn uuid_ints(uuid: u128) -> [i32; 4] {
/// `UUIDUtil.uuidToIntArray`.
pub fn uuid_ints(uuid: u128) -> [i32; 4] {
[
(uuid >> 96) as i32,
(uuid >> 64) as i32,
@@ -61,6 +62,9 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool {
guest.game_mode = level.mode();
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.saved = Some(tag);
if level.ender_items.len() == 27 {
guest.ender_items = level.ender_items.clone();
}
for (slot, item, count, damage) in &level.inventory {
let mut stack = ItemStack {
item: Arc::from(item.as_str()),
@@ -102,6 +106,7 @@ pub fn save(guest: &Guest, world: &Path) {
on_ground: guest.on_ground,
dimension: "minecraft:overworld".into(),
player_extra: guest.saved.clone(),
ender_items: guest.ender_items.clone(),
..Level::default()
};
let mut put = |slot: u8, stack: &Option<ItemStack>| {
+1
View File
@@ -17,6 +17,7 @@ pub mod beehive;
pub mod benchmark;
pub mod biome;
pub mod block_entity_anim;
pub mod block_entity_item;
pub mod block_entity_nbt;
pub mod block_entity_render;
pub mod block_transform;
@@ -91,7 +91,27 @@ impl MotionWorld<'_, '_, '_> {
}
Ok(())
}
pub(super) fn apply_fire_contact(&mut self) -> Result<()> {
/// What a server's `LivingEntity.baseTick` adds for a player it hosts:
/// the void (`Entity.checkBelowWorld`, 4 a tick, which creative players
/// take too) and suffocation (`isInWall`, which the caller decides from
/// the blocks at the eyes).
pub fn server_hazards_tick(&mut self, in_wall: bool) -> Result<()> {
if self.player.position.y < f64::from(crate::chunk::MIN_Y - 64) {
let id = self
.resources
.health
.damage
.id("minecraft:out_of_world")
.ok_or("missing environment damage type")?;
self.player
.hurt(&self.resources.health, self.scene.health_rules, id, 4.0)?;
}
if in_wall {
self.environment_hurt("minecraft:in_wall", 1.0)?;
}
Ok(())
}
pub fn apply_fire_contact(&mut self) -> Result<()> {
if self.player.spectator {
self.player.fire_ticks = 0;
return Ok(());
+32 -3
View File
@@ -47,9 +47,10 @@ fn append(tag: &Tag, lang: &Language, out: &mut String, depth: usize) {
Tag::Compound(_) => {
if let Some(text) = get(tag, "text").and_then(string) {
out.push_str(&text);
} else if let Some(text) = get(tag, "").and_then(string) {
// Mixed-list wrapper for a bare string.
out.push_str(&text);
} else if let Some(value) = get(tag, "") {
// NbtOps' wrapper for a bare value in a mixed list (a
// translation's number and string arguments).
append(value, lang, out, depth + 1);
} else if let Some(key) = get(tag, "translate").and_then(string) {
let args: Vec<String> = match get(tag, "with") {
Some(Tag::List(args)) => args
@@ -154,6 +155,34 @@ mod tests {
assert_eq!(format_java("100%% sure", &[]), "100% sure");
}
#[test]
fn unwraps_mixed_list_arguments() {
let mut lang = Language::new();
lang.insert(
"commands.item.entity.set.success.single".into(),
"Replaced %s slot(s) on %s with %s".into(),
);
// `with: [1, {text: "Alex"}, ...]` in NBT: the int comes wrapped.
let replaced = Tag::compound([
(
"translate",
Tag::String("commands.item.entity.set.success.single".into()),
),
(
"with",
Tag::List(vec![
Tag::compound([("", Tag::Int(1))]),
Tag::compound([("text", Tag::String("Alex".into()))]),
Tag::compound([("", Tag::String("[Emerald]".into()))]),
]),
),
]);
assert_eq!(
plain(&replaced, &lang),
"Replaced 1 slot(s) on Alex with [Emerald]"
);
}
#[test]
fn flattens_components() {
let mut lang = Language::new();
@@ -0,0 +1,91 @@
package dev.horizonlab.parity;
import com.google.gson.JsonParser;
import com.mojang.logging.LogUtils;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponentPatch;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
import net.minecraft.resources.Identifier;
import net.minecraft.util.ProblemReporter;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.TagValueOutput;
import org.slf4j.Logger;
/**
* Original oracle: block entity data on items. Each case line is JSON: a block,
* the saved NBT of its block entity, the block entity an item is placed as
* ("target", NBT), the item's component patch ("patch", SNBT; absent: the item
* Ctrl + Pick Block gave) and whether the player can use game master blocks.
* Prints the picked item's component patch, a tab, then the placed block
* entity's saveWithFullMetadata.
*/
public final class VanillaPickBlockDataOracle {
static final Logger LOGGER = LogUtils.getLogger();
static final BlockPos POS = new BlockPos(0, 64, 0);
static BlockEntity load(BlockState state, String snbt) throws Exception {
BlockEntity entity = BlockEntity.loadStatic(POS, state, TagParser.parseCompoundFully(snbt), ParityData.access);
if (entity == null) throw new IllegalStateException("no block entity: " + snbt);
return entity;
}
/** ServerGamePacketListenerImpl.addBlockDataToItem on the block's item. */
static ItemStack pick(BlockState state, BlockEntity entity) {
ItemStack item = new ItemStack(state.getBlock().asItem());
try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(entity.problemPath(), LOGGER)) {
TagValueOutput output = TagValueOutput.createWithContext(reporter, ParityData.access);
entity.saveCustomOnly(output);
entity.removeComponentsFromTag(output);
BlockItem.setBlockEntityData(item, entity.getType(), output);
item.applyComponents(entity.collectComponents());
}
return item;
}
/** BlockItem.updateCustomBlockEntityTag, then updateBlockEntityComponents. */
static void place(BlockEntity entity, ItemStack item, boolean gameMaster) {
var data = item.get(DataComponents.BLOCK_ENTITY_DATA);
if (data != null && data.type() == entity.getType() && (!entity.getType().onlyOpCanSetNbt() || gameMaster)) {
data.loadInto(entity, ParityData.access);
}
entity.applyComponentsFromItemStack(item);
}
public static void main(String[] args) throws Exception {
ParityData.init();
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 c = JsonParser.parseString(line).getAsJsonObject();
try {
BlockState state = BuiltInRegistries.BLOCK.getValue(Identifier.parse(c.get("block").getAsString())).defaultBlockState();
ItemStack picked = pick(state, load(state, c.get("nbt").getAsString()));
ItemStack item = picked;
if (c.has("patch")) {
var patch = DataComponentPatch.CODEC.parse(ParityData.ops, TagParser.parseCompoundFully(c.get("patch").getAsString())).getOrThrow();
item = new ItemStack(state.getBlock().asItem());
item.applyComponents(patch);
}
BlockEntity target = load(state, c.get("target").getAsString());
place(target, item, c.get("op").getAsBoolean());
CompoundTag saved = target.saveWithFullMetadata(ParityData.access);
var patch = DataComponentPatch.CODEC.encodeStart(ParityData.ops, picked.getComponentsPatch()).getOrThrow();
out.println(ParityData.canon(patch) + "\t" + ParityData.canon(saved));
} catch (Exception e) {
System.err.println(line + ": " + e);
out.println("error");
}
}
}
}
}
+370 -4
View File
@@ -12,7 +12,14 @@ address. The script then checks, from both sides, what a guest's game used to ge
- chest: a chest the guest opens opens on the guest's screen, its lid opens on both sides and
closes on both when the guest closes it;
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table;
- damage: a guest in survival takes fall damage.
- damage: a guest in survival takes fall damage;
- mobs: with the host in creative, a zombie and a skeleton go for the guest and hurt them;
- hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes,
drowning and the void (then respawns);
- pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing;
- containers: the guest's ender chest holds the guest's items, not the host's, and a double chest
opens as 9x6 with the right half first;
- feedback: the guest's command feedback names the guest and shows the numbers.
Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
both sides go to --out (host-*.png, guest-*.png).
@@ -27,11 +34,13 @@ macOS both games render offscreen. Games started here have no audio (HORIZON_NO_
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import zlib
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
@@ -39,7 +48,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
CHECKS = ['tab', 'self', 'armour', 'nametags', 'chest', 'crafting', 'damage']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials']
class Game:
@@ -263,8 +272,361 @@ def check_damage(host, guest, out):
return {'before': before, 'after': after, 'water': water}
def first_hurt(guest, before, ticks):
"""The guest's health once it drops below `before`, waiting at most `ticks`."""
health = remote(guest)['health']
for _ in range(ticks // 10):
if health < before:
break
guest.wait(10)
health = remote(guest)['health']
return health
def check_mobs(host, guest, out):
host('command', command='gamemode creative')
host('command', command='difficulty normal')
host('command', command='time set midnight')
guest('command', command='gamemode survival')
guest.wait(10)
hurt = {}
try:
for mob, distance in (('zombie', 3), ('skeleton', 7)):
x, y, z = pos_of(guest)
before = remote(guest)['health']
host('command', command=f'summon minecraft:{mob} {x:.2f} {y:.2f} {z + distance:.2f}')
low = first_hurt(guest, before, 300)
guest.shot(out, f'mobs-{mob}')
host.shot(out, f'mobs-{mob}')
host('command', command=f'kill @e[type=minecraft:{mob}]')
hurt[mob] = (before, low)
finally:
host('command', command='gamemode survival')
host('command', command='time set day')
for mob, (before, low) in hurt.items():
assert low < before, f'the {mob} never hurt the guest: health {before} -> {low} (all: {hurt})'
return hurt
def check_hazards(host, guest, out):
guest('command', command='gamemode survival')
# A fresh life: full health, so no regeneration eats food while the guest runs.
guest('command', command='kill @s')
guest.wait(20)
guest.raw('respawn')
guest.wait(40)
# Sprint-jumping down a stone lane: ServerPlayer.jumpFromGround and checkMovementStatistics.
guest('command', command='fill ~ ~-1 ~-1 ~60 ~-1 ~1 minecraft:stone')
guest('command', command='fill ~ ~ ~-1 ~60 ~3 ~1 minecraft:air')
guest.wait(10)
x, y, z = pos_of(guest)
guest.raw('look-at', f'{x + 60:.2f}', f'{y + 1.6:.2f}', f'{z:.2f}')
food = host.raw('lan', 'status')['guests'][0]['food']
for k in ('w', 'ctrl', 'space'):
guest.raw('key', k, 'down')
guest.wait(160)
for k in ('space', 'ctrl', 'w'):
guest.raw('key', k, 'up')
guest.wait(10)
fed = host.raw('lan', 'status')['guests'][0]['food']
hunger = {'before': food, 'after': fed}
hurt = {}
hx, hy, hz = (int(v // 1) for v in pos_of(host))
x, y, z = hx + 3, hy, hz
for name, fill, ticks in (('lava', 'minecraft:lava', 60), ('wall', 'minecraft:stone', 60),
('drowning', 'minecraft:water', 500), ('void', None, 60)):
if remote(guest)['health'] <= 0:
guest.raw('respawn')
guest.wait(40)
# A stone box around the guest holds the lava and the water in.
guest('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:stone')
guest('command', command=f'fill {x} {y} {z} {x} {y + 1} {z} minecraft:air')
guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
guest.wait(100)
before = remote(guest)['health']
if fill:
guest('command', command=f'fill {x} {y} {z} {x} {y + 1} {z} {fill}')
else:
guest('command', command=f'tp @s {x + 0.5} -140 {z + 0.5}')
hurt[name] = (before, first_hurt(guest, before, ticks))
guest.shot(out, f'hazards-{name}')
# Water puts the lava's fire out.
guest('command', command=f'fill {x} {y} {z} {x} {y + 1} {z} minecraft:water')
guest.wait(5)
guest('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air')
guest('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y - 1} {z + 1} minecraft:stone')
guest.wait(20)
if remote(guest)['health'] <= 0:
guest.raw('respawn')
guest.wait(40)
# [food, saturation, exhaustion]: 8 s of sprint-jumping is about 2 of exhaustion; every 4
# of it takes a point of saturation, or of food once saturation is gone (FoodData.tick).
spent = 4 * (food[0] + food[1] - fed[0] - fed[1]) + fed[2] - food[2]
assert spent > 1.0, f'no hunger from moving: {hunger} ({spent:.2f} spent)'
for name, (before, after) in hurt.items():
assert after < before, f'{name} never hurt the guest: health {before} -> {after} (all: {hurt})'
return {'hunger': hunger, **hurt}
def check_pvp(host, guest, out):
for g in (host, guest):
g('command', command='gamemode survival')
g('command', command='item replace entity @s weapon.mainhand with minecraft:iron_sword')
face_each_other(host, guest)
hits = {}
try:
for name, rule, attacker in (('guest hits host', 'true', guest), ('host hits guest', 'true', host),
('pvp off', 'false', guest)):
host('command', command=f'gamerule pvp {rule}')
face_each_other(host, guest)
attacker.wait(30) # a full attack charge
victim = (lambda: host('state')['player']['health']) if attacker is guest else (lambda: remote(guest)['health'])
before = victim()
attacker.raw('attack')
attacker.wait(10)
hits[name] = (before, victim())
attacker.shot(out, 'pvp-' + name.replace(' ', '-'))
finally:
host('command', command='gamerule pvp true')
assert hits['guest hits host'][1] < hits['guest hits host'][0], f'the guest did not hurt the host: {hits}'
assert hits['host hits guest'][1] < hits['host hits guest'][0], f'the host did not hurt the guest: {hits}'
assert hits['pvp off'][1] == hits['pvp off'][0], f'pvp off still hurts: {hits}'
return hits
def container_items(game):
"""The open container's stacks by slot (Horizon's container slots are 300 and up) and its size."""
slots = [s for s in game('screen').get('slots', []) if s.get('slot', 0) >= 300]
return {s['slot'] - 300: s['item'] for s in slots if s.get('item')}, len(slots)
def open_container(guest, pos, out, label, take=None):
"""Open the container at `pos` and read it; `take` shift-clicks that container slot out first."""
guest.raw('interact', *pos)
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
# The server's menu (an ender or double chest has no stand-in block entity: key i32::MIN),
# then its contents, can come a few ticks after the screen.
for _ in range(20):
guest.wait(2)
screen = guest('screen')
items = {s['slot']: s.get('item') for s in screen.get('slots', [])}
if screen.get('container') == [-2**31, 0, 0] and (take is None or items.get(300 + take)):
break
guest.wait(5)
if take is not None:
guest.raw('click-slot', 300 + take, 'shift')
guest.wait(5)
items = container_items(guest)
guest.shot(out, label)
guest.raw('key', 'esc', 'tap')
guest.wait(5)
return items
def check_containers(host, guest, out):
host('command', command='item replace entity @s enderchest.0 with minecraft:diamond')
guest('command', command='item replace entity @s enderchest.4 with minecraft:emerald')
x, y, z = (int(v // 1) for v in pos_of(guest))
guest('command', command=f'setblock {x} {y} {z + 2} minecraft:ender_chest')
guest.wait(10)
ender, ender_size = open_container(guest, (x, y, z + 2), out, 'ender-chest')
# Facing north, a left half pairs with the block to its east (ChestBlock.getConnectedDirection).
guest('command', command=f'setblock {x} {y} {z - 2} minecraft:chest[facing=north,type=left]')
guest('command', command=f'setblock {x + 1} {y} {z - 2} minecraft:chest[facing=north,type=right]')
guest('command', command=f'item replace block {x + 1} {y} {z - 2} container.0 with minecraft:gold_ingot')
guest('command', command=f'item replace block {x} {y} {z - 2} container.0 with minecraft:iron_ingot')
guest.wait(10)
double, double_size = open_container(guest, (x, y, z - 2), out, 'double-chest')
# Taking from each writes back to the guest's ender inventory and to the right half.
guest('command', command='clear @s')
open_container(guest, (x, y, z + 2), out, 'ender-chest-take', take=4)
open_container(guest, (x, y, z - 2), out, 'double-chest-take', take=0)
taken = guest('inventory')['counts']
after = (open_container(guest, (x, y, z + 2), out, 'ender-chest-after')[0],
open_container(guest, (x, y, z - 2), out, 'double-chest-after')[0])
host_ender = host('command', command='data get entity @s EnderItems')
for at in ((x, y, z + 2), (x, y, z - 2), (x + 1, y, z - 2)):
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
assert ender == {4: 'minecraft:emerald'} and ender_size == 27, f'the guest\'s ender chest: {ender} ({ender_size})'
assert double_size == 54, f'the double chest opened with {double_size} slots'
assert double == {0: 'minecraft:gold_ingot', 27: 'minecraft:iron_ingot'}, f'the double chest: {double}'
assert 'emerald' not in json.dumps(host_ender), f'the guest\'s item went to the host: {host_ender}'
assert taken.get('minecraft:emerald') == 1 and taken.get('minecraft:gold_ingot') == 1, f'taken: {taken}'
assert after == ({}, {27: 'minecraft:iron_ingot'}), f'after taking: {after}'
return {'ender': ender, 'double': double, 'taken': taken}
def check_feedback(host, guest, out):
x, y, z = (round(v, 1) for v in pos_of(guest))
guest('command', command='item replace entity @s weapon.mainhand with minecraft:stick')
guest('command', command=f'tp @s {x:.1f} {y:.1f} {z:.1f}')
guest.wait(10)
chat = guest.raw('messages', 5)['chat']
guest.raw('key', 't', 'tap')
guest.wait(5)
guest.shot(out, 'feedback')
guest.raw('key', 'esc', 'tap')
guest.wait(5)
screen = guest('state').get('screen')
replaced = f'Replaced 1 slot(s) on {GUEST_NAME} with [Stick]'
assert any(replaced in line for line in chat), f'no "{replaced}" in {chat}'
assert any(line.startswith(f'Teleported {GUEST_NAME} to {x:.6f}') for line in chat), f'teleport feedback: {chat}'
assert screen in (None, 'playing'), f'the chat did not close: {screen}'
return chat
def png_rows(path):
"""The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel."""
data = Path(path).read_bytes()
pos, idat, head = 8, b'', None
while pos < len(data):
size = int.from_bytes(data[pos:pos + 4], 'big')
kind, body = data[pos + 4:pos + 8], data[pos + 8:pos + 8 + size]
if kind == b'IHDR':
head = body
elif kind == b'IDAT':
idat += body
pos += 12 + size
width, height = int.from_bytes(head[:4], 'big'), int.from_bytes(head[4:8], 'big')
assert head[8] == 8 and head[9] in (2, 6) and head[12] == 0, f'unsupported PNG {head.hex()}'
bpp = 4 if head[9] == 6 else 3
raw, stride, rows, prev = zlib.decompress(idat), width * bpp, [], bytearray(width * bpp)
for y in range(height):
kind, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
for i in range(stride):
a = line[i - bpp] if i >= bpp else 0
b, c = prev[i], prev[i - bpp] if i >= bpp else 0
if kind == 1:
line[i] = (line[i] + a) & 255
elif kind == 2:
line[i] = (line[i] + b) & 255
elif kind == 3:
line[i] = (line[i] + (a + b) // 2) & 255
elif kind == 4:
pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c)
line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
rows.append(bytes(line))
prev = line
return rows, bpp
def changed_pixels(a, b):
(ra, bpp), (rb, _) = png_rows(a), png_rows(b)
return sum(1 for la, lb in zip(ra, rb) for i in range(0, len(la), bpp)
if max(abs(la[i + k] - lb[i + k]) for k in range(3)) > 24)
def sneaking_on_host(host, want, ticks=40):
"""Whether the host sees the guest crouching, once it matches `want` or after `ticks`."""
for _ in range(ticks // 5):
sneaking = host.raw('lan', 'status')['guests'][0]['sneaking']
if sneaking == want:
return sneaking
host.wait(5)
return sneaking
def check_walls(host, guest, out):
# A stone wall between the two: the host still sees the guest's name through it
# (TEXT_SEE_THROUGH), but not once the guest crouches (Entity.isDiscrete).
for g in (host, guest):
back_to_game(g)
# The trial spawner's zombies may have killed the guest.
if guest('state').get('screen') == 'dead' or remote(guest)['health'] <= 0:
guest.raw('respawn')
guest.wait(40)
face_each_other(host, guest)
hx, hy, hz = pos_of(host)
gx, gy, gz = pos_of(guest)
# Halfway: the players stand 3 apart, so the wall's block touches neither.
wall = int((hx + gx) / 2 // 1)
host('command', command=f'fill {wall} {int(hy // 1)} {int(hz // 1) - 3} {wall} {int(hy // 1) + 4} '
f'{int(hz // 1) + 3} minecraft:stone')
try:
host.raw('look-at', f'{gx:.2f}', f'{gy + 2.3:.2f}', f'{gz:.2f}')
# Chat lines fade out after 200 ticks; let them go so only the name tag can differ.
host.wait(210)
standing = host.shot(out, 'walls-standing')
guest.raw('key', 'shift', 'down')
crouched = sneaking_on_host(host, True)
guest.wait(10)
crouching = host.shot(out, 'walls-crouching')
guest.raw('key', 'shift', 'up')
stood = not sneaking_on_host(host, False)
guest.wait(10)
again = host.shot(out, 'walls-standing-again')
finally:
guest.raw('key', 'shift', 'up')
host('command', command=f'fill {wall} {int(hy // 1)} {int(hz // 1) - 3} {wall} {int(hy // 1) + 4} '
f'{int(hz // 1) + 3} minecraft:air')
face_each_other(host, guest)
assert crouched and stood, f'the host never saw the guest crouch and stand: {crouched}, {stood}'
seen, steady = changed_pixels(standing, crouching), changed_pixels(standing, again)
assert seen > 50, f'no name tag through the wall: {seen} pixels differ standing vs crouching'
assert steady < seen // 4, f'the view itself changed: {steady} pixels between two standing shots ({seen})'
return {'standing_vs_crouching': seen, 'standing_twice': steady}
def state_of(game, pos, key):
state = game.raw('block', *pos)['state']
return dict(kv.split('=') for kv in state.partition('[')[2].rstrip(']').split(',') if kv).get(key)
def wait_state(game, pos, key, want, ticks):
for _ in range(ticks // 10):
if state_of(game, pos, key) == want:
return want
game.wait(10)
return state_of(game, pos, key)
def check_trials(host, guest, out):
# The host watches as a spectator, whom neither block detects: only the guest can wake them.
hx, hy, hz = pos_of(host)
host('command', command='gamemode spectator')
host('command', command='difficulty normal')
host('command', command='gamerule spawn_mobs true')
guest('command', command='gamemode survival')
x, y, z = (int(v // 1) for v in pos_of(guest))
spawner, vault = (x, y, z + 3), (x, y, z - 2)
# Open air from the vault to the spawner: the spawner wants to see the guest's eyes.
guest('command', command=f'fill {x - 1} {y} {z - 2} {x + 1} {y + 2} {z + 3} minecraft:air')
try:
guest('command', command=f'setblock {spawner[0]} {spawner[1]} {spawner[2]} minecraft:trial_spawner'
'{spawn_data:{entity:{id:"minecraft:zombie"}},required_player_range:6}')
guest('command', command=f'setblock {vault[0]} {vault[1]} {vault[2]} minecraft:vault'
'{config:{key_item:{id:"minecraft:trial_key",count:1}}}')
trial = wait_state(host, spawner, 'trial_spawner_state', 'active', 100)
active = wait_state(host, vault, 'vault_state', 'active', 60)
host.shot(out, 'trials-active')
guest('command', command='item replace entity @s weapon.mainhand with minecraft:trial_key')
guest.wait(5)
guest.raw('interact', *vault)
unlocking = wait_state(host, vault, 'vault_state', 'unlocking', 20)
guest.shot(out, 'trials-unlocking')
rewarded = host('command', command=f'data get block {vault[0]} {vault[1]} {vault[2]} server_data.rewarded_players')
host_uuid = host('command', command='data get entity @s UUID')
finally:
host('command', command='gamerule spawn_mobs false')
host('command', command='kill @e[type=minecraft:zombie]')
host('command', command='gamemode survival')
# Back where it stood: a spectator drifts, and may be inside the ground when it lands.
host('command', command=f'tp @s {hx:.2f} {hy:.2f} {hz:.2f}')
guest('command', command=f'setblock {spawner[0]} {spawner[1]} {spawner[2]} minecraft:air')
guest('command', command=f'setblock {vault[0]} {vault[1]} {vault[2]} minecraft:air')
uuid = lambda reply: re.findall(r'-?\d+', json.dumps(reply).partition('[I;')[2].partition(']')[0])
assert trial == 'active', f'the trial spawner never saw the guest: {trial}'
assert active == 'active', f'the vault never saw the guest: {active}'
assert unlocking == 'unlocking', f'the guest\'s key did not unlock the vault: {unlocking}'
assert uuid(rewarded) and uuid(rewarded) != uuid(host_uuid), f'rewarded {rewarded}, host {host_uuid}'
return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)}
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage}
'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage,
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials,
'walls': check_walls}
def run(ctl, out, resources, checks):
@@ -272,8 +634,12 @@ def run(ctl, out, resources, checks):
results = {}
try:
host('launch', wait=False, offscreen=sys.platform == 'darwin')
host.raw('open', 'Lan', 5)
# Guests' commands need the world's Allow Commands as well as the LAN's (#372): a creative
# world has them; everyone plays in survival.
host.raw('open', 'Lan', 5, 'creative')
host('wait_ready', seconds=400)
host('command', command='defaultgamemode survival')
host('command', command='gamemode survival')
host('command', command='time set day')
# An open stone floor around the host, so the players see each other and nothing is in the way.
host('command', command='fill ~-8 ~-1 ~-8 ~8 ~-1 ~8 minecraft:stone')
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""Compare block entity data on items with vanilla 26.3.
The Java oracle (VanillaPickBlockDataOracle) loads each block entity with
BlockEntity.loadStatic and runs ServerGamePacketListenerImpl.addBlockDataToItem
(Ctrl + Pick Block in creative) on the block's item, then places an item as a
block entity: BlockItem.updateCustomBlockEntityTag (op-only types only for a
game master) and BlockEntity.applyComponentsFromItemStack. The Rust example
(pick_block_data_fixture) runs horizon_client::block_entity_item on the
canonical saved NBT. The picked component patch and the placed block entity's
saveWithFullMetadata are compared for every block entity type that carries data:
containers with items, names, locks and loot tables, signs, banners, command
blocks, spawners, trial spawners, vaults, beehives, pots, skulls, lecterns and
more, picked and placed back, with hand-written patches (data of another type,
op-only data without permission, merges into a filled block entity, leftover
components).
"""
import argparse
import json
try:
from . import interaction_lab as lib
except ImportError:
import interaction_lab as lib
POS = 'x:0,y:64,z:0'
STONE = '{id:"minecraft:stone",count:5}'
NAME = 'CustomName:"Box"'
PIG = 'SpawnData:{entity:{id:"minecraft:pig"}}'
# A block entity that spawns from nothing: what loading it saves (a spawner's
# potentials and a trial spawner's next spawn come from its first spawn data).
FRESH = {'mob_spawner': PIG, 'trial_spawner': 'spawn_data:{entity:{}}'}
def be(type_id, body=''):
return '{id:"minecraft:%s",%s%s}' % (type_id, POS, ',' + body if body else '')
def items(*slots):
return 'Items:[%s]' % ','.join('{Slot:%db,id:"minecraft:%s",count:%d}' % s for s in slots)
# (block, block entity type, saved NBT bodies to pick and place back).
SAMPLES = [
('chest', 'chest', ['', items((0, 'stone', 5), (26, 'diamond', 1)), NAME, 'lock:{items:"minecraft:diamond"}',
'LootTable:"minecraft:chests/simple_dungeon",LootTableSeed:42L',
'LootTable:"minecraft:chests/igloo_chest"', items((3, 'dirt', 1)) + ',' + NAME]),
('trapped_chest', 'trapped_chest', [items((1, 'stone', 2))]),
('barrel', 'barrel', [items((5, 'apple', 3)) + ',' + NAME]),
('red_shulker_box', 'shulker_box', ['', items((0, 'stone', 64), (13, 'emerald', 2)) + ',' + NAME]),
('hopper', 'hopper', ['TransferCooldown:5', items((4, 'stone', 1)) + ',TransferCooldown:2']),
('dispenser', 'dispenser', [items((8, 'arrow', 16))]),
('dropper', 'dropper', [items((0, 'stone', 1)) + ',' + NAME]),
('crafter', 'crafter', ['disabled_slots:[I;1,4],triggered:1,crafting_ticks_remaining:3',
items((2, 'stick', 1)) + ',disabled_slots:[I;0]']),
('furnace', 'furnace', ['cooking_time_spent:20,cooking_total_time:200,lit_time_remaining:100,lit_total_time:1600,'
+ items((0, 'iron_ore', 3), (1, 'coal', 4)) + ',RecipesUsed:{"minecraft:iron_ingot":2}']),
('smoker', 'smoker', [items((2, 'cooked_beef', 1))]),
('blast_furnace', 'blast_furnace', [NAME + ',lit_time_remaining:7']),
('brewing_stand', 'brewing_stand', ['BrewTime:30,Fuel:10,' + items((4, 'blaze_powder', 1))]),
# Levels is computed by the beacon's tick, never loaded.
('beacon', 'beacon', ['primary_effect:"minecraft:speed",secondary_effect:"minecraft:regeneration"',
NAME + ',lock:{items:"minecraft:stick"}']),
('enchanting_table', 'enchanting_table', ['', NAME]),
('command_block', 'command_block', ['Command:"say hi",auto:1b,powered:1b,conditionMet:1b,TrackOutput:0b,SuccessCount:3',
'Command:"time set day",' + NAME, 'LastOutput:"{\\"text\\":\\"x\\"}"',
'UpdateLastExecution:0b,LastExecution:20L']),
('repeating_command_block', 'command_block', ['Command:"say loop",auto:1b']),
('campfire', 'campfire', [items((0, 'beef', 1), (3, 'porkchop', 1)) + ',CookingTimes:[I;5,0,0,9],CookingTotalTimes:[I;600,0,0,600]']),
('chiseled_bookshelf', 'chiseled_bookshelf', [items((0, 'book', 1), (5, 'enchanted_book', 1)) + ',last_interacted_slot:5']),
('oak_shelf', 'shelf', [items((1, 'stone', 1)) + ',align_items_to_bottom:1b']),
('beehive', 'beehive', ['', 'bees:[{entity_data:{id:"minecraft:bee"},ticks_in_hive:5,min_ticks_in_hive:600}]',
'flower_pos:[I;1,2,3]']),
('white_banner', 'banner', ['', 'patterns:[{pattern:"minecraft:creeper",color:"red"}]',
'patterns:[{pattern:"minecraft:stripe_top",color:"blue"}],' + NAME]),
('decorated_pot', 'decorated_pot', ['', 'sherds:{back:{id:"minecraft:angler_pottery_sherd"},front:{id:"minecraft:skull_pottery_sherd"}}',
'item:{id:"minecraft:diamond",count:3}', 'LootTable:"minecraft:archaeology/desert_pyramid"']),
('oak_sign', 'sign', ['', 'front_text:{messages:["hello","world","",""]}',
'front_text:{messages:["a","","",""],color:"red",has_glowing_text:1b},back_text:{messages:["","b","",""]},is_waxed:1b']),
('oak_hanging_sign', 'hanging_sign', ['back_text:{messages:["x","","",""]}']),
('skeleton_skull', 'skull', ['', 'custom_name:"Bones"', 'note_block_sound:"minecraft:block.note_block.bell"']),
('spawner', 'mob_spawner', ['Delay:20,SpawnData:{entity:{id:"minecraft:zombie"}},MinSpawnDelay:200,MaxSpawnDelay:800',
'SpawnData:{entity:{id:"minecraft:pig"}},SpawnCount:2,RequiredPlayerRange:8']),
('trial_spawner', 'trial_spawner', ['spawn_data:{entity:{id:"minecraft:zombie"}}',
'normal_config:"minecraft:trial_chamber/melee/zombie/normal",required_player_range:10,spawn_data:{entity:{}}']),
('vault', 'vault', ['', 'config:{key_item:{id:"minecraft:ominous_trial_key",count:1}}']),
('jukebox', 'jukebox', ['', 'RecordItem:{id:"minecraft:music_disc_cat",count:1},ticks_since_song_started:40L']),
('lectern', 'lectern', ['', 'Book:{id:"minecraft:writable_book",count:1,components:{"minecraft:writable_book_content":{pages:[{raw:"a"},{raw:"b"}]}}},Page:1']),
('sculk_sensor', 'sculk_sensor', ['last_vibration_frequency:4']),
('creaking_heart', 'creaking_heart', ['']),
('bell', 'bell', ['']),
('structure_block', 'structure_block', ['name:"minecraft:house",mode:"SAVE",posY:2']),
]
# Patches placed as (block, block entity type, target body, patch SNBT, game master).
DATA = '"minecraft:block_entity_data"'
PATCHES = [
('command_block', 'command_block', '', '{%s:{id:"minecraft:command_block",Command:"say op"}}' % DATA, False),
('command_block', 'command_block', '', '{%s:{id:"minecraft:chest",Command:"say wrong"}}' % DATA, True),
('command_block', 'command_block', 'Command:"old",auto:1b', '{%s:{id:"minecraft:command_block",TrackOutput:0b}}' % DATA, True),
('oak_sign', 'sign', '', '{%s:{id:"minecraft:sign",is_waxed:1b}}' % DATA, False),
('oak_sign', 'sign', '', '{%s:{id:"minecraft:sign",is_waxed:1b}}' % DATA, True),
('chest', 'chest', items((0, 'stone', 1)), '{%s:{id:"minecraft:chest",Items:[{Slot:1b,id:"minecraft:dirt",count:1}]}}' % DATA, True),
('chest', 'chest', '', '{"minecraft:container":[{slot:30,item:%s},{slot:2,item:%s}]}' % (STONE, STONE), False),
('chest', 'chest', '', '{"minecraft:container_loot":{loot_table:"minecraft:chests/simple_dungeon",seed:7L}}', False),
('chest', 'chest', '', '{"minecraft:lore":["a"],"minecraft:custom_name":"Named"}', False),
('hopper', 'hopper', 'TransferCooldown:4', '{%s:{id:"minecraft:hopper",TransferCooldown:9}}' % DATA, False),
('spawner', 'mob_spawner', PIG, '{%s:{id:"minecraft:mob_spawner",SpawnData:{entity:{id:"minecraft:skeleton"}}}}' % DATA, True),
('spawner', 'mob_spawner', PIG, '{%s:{id:"minecraft:mob_spawner",SpawnData:{entity:{id:"minecraft:skeleton"}}}}' % DATA, False),
('trial_spawner', 'trial_spawner', 'spawn_data:{entity:{}}', '{%s:{id:"minecraft:trial_spawner",required_player_range:4}}' % DATA, True),
('vault', 'vault', '', '{%s:{id:"minecraft:vault",config:{key_item:{id:"minecraft:stick",count:1}}}}' % DATA, False),
('decorated_pot', 'decorated_pot', '', '{"minecraft:container":[{slot:1,item:%s}]}' % STONE, False),
('white_banner', 'banner', NAME, '{"minecraft:banner_patterns":[{pattern:"minecraft:flower",color:"lime"}]}', False),
('beehive', 'beehive', 'bees:[{entity_data:{id:"minecraft:bee"},ticks_in_hive:1,min_ticks_in_hive:2}]', '{}', False),
('decorated_pot', 'decorated_pot', '', '{"!minecraft:pot_decorations":{}}', False),
('hopper', 'hopper', items((0, 'stone', 1)), '{"minecraft:container":[{slot:4,item:%s},{slot:5,item:%s}]}' % (STONE, STONE), False),
('oak_sign', 'sign', '', '{"minecraft:waxed":{},"minecraft:sign_text_back":{messages:["","","","z"]}}', False),
]
def cases():
out = []
for block, type_id, bodies in SAMPLES:
for body in bodies:
for op in (True, False):
out.append({'block': 'minecraft:' + block, 'nbt': be(type_id, body),
'target': be(type_id, FRESH.get(type_id, '')), 'op': op})
for block, type_id, target, patch, op in PATCHES:
out.append({'block': 'minecraft:' + block, 'nbt': be(type_id, FRESH.get(type_id, '')), 'target': be(type_id, target), 'patch': patch, 'op': op})
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--limit', type=int, default=4)
args = parser.parse_args()
work = lib.work_dir('pick-block-data-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaPickBlockDataOracle')
all_cases = cases()
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in all_cases))
vanilla.run('VanillaPickBlockDataOracle', work / 'cases.jsonl', work / 'native.txt')
lib.cargo_example('horizon-client', 'pick_block_data_fixture', work / 'cases.jsonl', work / 'rust.txt')
errors = sum(line == 'error' for line in (work / 'native.txt').read_text().split('\n'))
if errors:
print(f'{errors} cases fail in vanilla')
total = lib.compare(all_cases, work / 'native.txt', work / 'rust.txt',
lambda case, line: case['block'] + (' patch' if 'patch' in case else ''),
lambda case: json.dumps(case), args.limit)
raise SystemExit(1 if total or errors else 0)
if __name__ == '__main__':
main()