Merge commit 'a4feb6516102eaffb9e82437f808e32f4d05bde0' into HEAD
This commit is contained in:
@@ -634,6 +634,15 @@ impl Game<'_> {
|
||||
v["craft_size"] = json!(self.craft_size);
|
||||
v["station"] = json!(self.station.as_ref().map(|s| format!("{:?}", s.kind)));
|
||||
v["container"] = json!(self.container);
|
||||
// The recipe book's buttons (GUI pixels): the book button, then
|
||||
// the recipe buttons of the page, page arrows, filter and tabs.
|
||||
let book = self.recipe_book_targets();
|
||||
if !book.is_empty() {
|
||||
v["recipe_book"] = json!({
|
||||
"targets": book.iter().map(|t| t.rect).collect::<Vec<_>>(),
|
||||
"known": self.recipe_book_known(),
|
||||
});
|
||||
}
|
||||
v["slot_ids"] = json!(
|
||||
"0-8 hotbar, 9-35 inventory, 100+ crafting grid (row-major), 200 crafting result, 300+ container, 500-503 armor, 504 offhand, 600+ station"
|
||||
);
|
||||
|
||||
@@ -663,6 +663,7 @@ impl Game<'_> {
|
||||
{
|
||||
self.guest_suggestions(host, conn, &payload);
|
||||
}
|
||||
S::PlaceRecipe(p) => self.lan_place_recipe(host, conn, &p),
|
||||
S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn),
|
||||
// ServerStatsCounter.sendStats.
|
||||
S::ClientCommand(c) if c.action == 1 => {
|
||||
|
||||
@@ -225,6 +225,86 @@ impl Game<'_> {
|
||||
true
|
||||
}
|
||||
|
||||
/// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe
|
||||
/// book places a known recipe in their inventory grid or crafting table
|
||||
/// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items
|
||||
/// are missing.
|
||||
pub(super) fn lan_place_recipe(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
p: &horizon_protocol::packets::recipes::PlaceRecipe,
|
||||
) {
|
||||
use horizon_client::menu::place::PostPlace;
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
return;
|
||||
};
|
||||
let g = &host.hub.guests[gi];
|
||||
if g.spectator() {
|
||||
return;
|
||||
}
|
||||
let Some(id) = self
|
||||
.res
|
||||
.stations
|
||||
.recipe_index
|
||||
.recipe_of_display(p.recipe)
|
||||
.map(str::to_owned)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
// An unknown or impossible recipe is refused outright.
|
||||
if !g.recipe_book.knows(&id)
|
||||
|| self
|
||||
.res
|
||||
.recipes
|
||||
.placement(&id)
|
||||
.is_none_or(|placement| placement.impossible())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let creative = g.creative();
|
||||
let placed = if p.container == 0 {
|
||||
let crafting = host.play.entry(conn).or_default();
|
||||
let mut menu = crafting
|
||||
.crafting
|
||||
.inventory
|
||||
.take()
|
||||
.unwrap_or_else(|| Box::new(Menu::new(Kind::Inventory)));
|
||||
let grid = host.hub.guests[gi].craft_grid.clone();
|
||||
let placed = self.guest_menu_op(host, gi, &mut menu, |menu, env| {
|
||||
for (k, s) in grid.into_iter().enumerate() {
|
||||
menu.set_slot(env, 1 + k, s);
|
||||
}
|
||||
menu.place_recipe(env, &id, p.use_max, creative, None)
|
||||
});
|
||||
let g = &mut host.hub.guests[gi];
|
||||
for k in 0..4 {
|
||||
g.craft_grid[k] = menu.slot(1 + k).cloned();
|
||||
}
|
||||
g.craft_result = menu.slot(0).cloned();
|
||||
host.play.entry(conn).or_default().crafting.inventory = Some(menu);
|
||||
host.hub.send_inventory(gi);
|
||||
placed
|
||||
} else {
|
||||
let Some((window, state, mut menu)) = host
|
||||
.play
|
||||
.get_mut(&conn)
|
||||
.and_then(|play| play.crafting.table.take_if(|(w, _, _)| *w == p.container))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let placed = self.guest_menu_op(host, gi, &mut menu, |menu, env| {
|
||||
menu.place_recipe(env, &id, p.use_max, creative, None)
|
||||
});
|
||||
host.play.entry(conn).or_default().crafting.table = Some((window, state, menu));
|
||||
self.lan_send_table_content(host, conn);
|
||||
placed
|
||||
};
|
||||
if placed == PostPlace::Ghost {
|
||||
host.hub.send_ghost_recipe(conn, p.container, &id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`).
|
||||
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) {
|
||||
self.lan_crafting_closed(host, conn, None);
|
||||
|
||||
@@ -110,7 +110,7 @@ fn sprite(name: &str) -> String {
|
||||
impl Game<'_> {
|
||||
/// The book the open screen has, if any.
|
||||
fn active_book(&self) -> Option<BookType> {
|
||||
if self.screen != Screen::Inventory || self.remote.is_some() || self.station.is_some() {
|
||||
if self.screen != Screen::Inventory || self.station.is_some() {
|
||||
return None;
|
||||
}
|
||||
if self.mount_active() {
|
||||
@@ -262,6 +262,33 @@ impl Game<'_> {
|
||||
/// The items the book counts (`RecipeBookComponent.updateStackedContents`):
|
||||
/// the inventory and the menu's crafting slots, as the menu engine counts them.
|
||||
fn book_available(&mut self, _book: BookType) -> Stacked {
|
||||
if self.remote.is_some() {
|
||||
// A server's menu: the slots it last sent, counted the same way.
|
||||
use horizon_client::menu::{Env, Kind, Menu};
|
||||
let table = self.craft_size == 3;
|
||||
let grid: Vec<_> = (0..self.craft_size * self.craft_size)
|
||||
.map(|k| self.slot_mut(100 + k).clone())
|
||||
.collect();
|
||||
let mut menu = Menu::new(if table {
|
||||
Kind::Crafting
|
||||
} else {
|
||||
Kind::Inventory
|
||||
});
|
||||
let env = Env {
|
||||
items: &self.res.items,
|
||||
recipes: &self.res.recipes,
|
||||
brewing: &self.res.stations.brewing,
|
||||
banners: &self.res.stations.banners,
|
||||
trade: None,
|
||||
};
|
||||
for i in 0..36 {
|
||||
menu.set_player_item(i, self.inventory[i].clone());
|
||||
}
|
||||
for (k, stack) in grid.into_iter().enumerate() {
|
||||
menu.set_slot(&env, 1 + k, stack);
|
||||
}
|
||||
return menu.stacked_contents(&env);
|
||||
}
|
||||
let mut out = Stacked::default();
|
||||
let stock = &mut out;
|
||||
self.menu_session(|menu, env, _| {
|
||||
@@ -274,6 +301,10 @@ impl Game<'_> {
|
||||
/// replacing batch (vanilla's server iterates an identity hash set; this
|
||||
/// one goes in id order), then each unlock and removal.
|
||||
fn sync_client_book(&mut self) {
|
||||
// On a server the book is the server's packets' (remote_recipe_book_*).
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let known = &self.level.recipe_book.recipes;
|
||||
let index = &self.res.stations.recipe_index;
|
||||
let ui = &mut self.recipe_ui;
|
||||
@@ -660,6 +691,10 @@ impl Game<'_> {
|
||||
}
|
||||
false
|
||||
}
|
||||
/// How many displays the client's book holds.
|
||||
pub(super) fn recipe_book_known(&self) -> usize {
|
||||
self.recipe_ui.client.displays().len()
|
||||
}
|
||||
/// The recipe book's buttons a controller can focus: the book button,
|
||||
/// recipes, page arrows, the craftable filter and the tabs (GUI pixels;
|
||||
/// the search box registers itself as a field).
|
||||
@@ -800,6 +835,18 @@ impl Game<'_> {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.remote.is_some() {
|
||||
// The server places it and answers with the slots, or a ghost.
|
||||
let container = self.remote_menu_id();
|
||||
self.send(horizon_protocol::packets::play::Serverbound::PlaceRecipe(
|
||||
horizon_protocol::packets::recipes::PlaceRecipe {
|
||||
container,
|
||||
recipe: entry.display_id,
|
||||
use_max,
|
||||
},
|
||||
));
|
||||
return;
|
||||
}
|
||||
let creative = self.creative;
|
||||
let mut post = None;
|
||||
let answer = &mut post;
|
||||
@@ -828,6 +875,80 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- a server's recipe book ----
|
||||
|
||||
/// ClientboundRecipeBookAddPacket (`ClientRecipeBook.add`): the
|
||||
/// displays join the book, highlighted when new, and the recipes whose
|
||||
/// entries ask for it show the toast.
|
||||
pub(super) fn remote_recipe_book_add(
|
||||
&mut self,
|
||||
p: horizon_protocol::packets::recipes::RecipeBookAdd,
|
||||
) {
|
||||
let ui = &mut self.recipe_ui;
|
||||
if p.replace {
|
||||
ui.client.clear();
|
||||
}
|
||||
let mut toast = Vec::new();
|
||||
for e in &p.entries {
|
||||
ui.client.add(e.id);
|
||||
if e.flags & 2 != 0 {
|
||||
ui.client.highlight.insert(e.id);
|
||||
}
|
||||
if e.flags & 1 != 0
|
||||
&& let Some(id) = self.res.stations.recipe_index.recipe_of_display(e.id)
|
||||
&& !toast.iter().any(|t| t == id)
|
||||
{
|
||||
toast.push(id.to_owned());
|
||||
}
|
||||
}
|
||||
// A local world opened later syncs its book from scratch.
|
||||
ui.client_known = None;
|
||||
ui.client_version += 1;
|
||||
self.recipe_toast(&toast);
|
||||
}
|
||||
/// ClientboundRecipeBookRemovePacket.
|
||||
pub(super) fn remote_recipe_book_remove(
|
||||
&mut self,
|
||||
p: horizon_protocol::packets::recipes::RecipeBookRemove,
|
||||
) {
|
||||
for id in p.ids {
|
||||
self.recipe_ui.client.remove(id);
|
||||
}
|
||||
self.recipe_ui.client_version += 1;
|
||||
}
|
||||
/// ClientboundRecipeBookSettingsPacket: each book's open and filter flags.
|
||||
pub(super) fn remote_recipe_book_settings(
|
||||
&mut self,
|
||||
p: horizon_protocol::packets::recipes::RecipeBookSettings,
|
||||
) {
|
||||
for (i, (open, filtering)) in p.books.into_iter().enumerate() {
|
||||
self.level.recipe_book.open[i] = open;
|
||||
self.level.recipe_book.filtering[i] = filtering;
|
||||
}
|
||||
}
|
||||
/// ClientboundPlaceGhostRecipePacket: the recipe last placed, faded into
|
||||
/// the open menu's grid.
|
||||
pub(super) fn remote_ghost_recipe(
|
||||
&mut self,
|
||||
p: horizon_protocol::packets::recipes::PlaceGhostRecipe,
|
||||
) {
|
||||
let open = self.remote_menu_id();
|
||||
let Some(book_type) = self.active_book() else {
|
||||
return;
|
||||
};
|
||||
if p.container != open {
|
||||
return;
|
||||
}
|
||||
let entry = self.recipe_ui.last_placed.as_ref().and_then(|id| {
|
||||
let book = self.recipe_ui.book.as_ref()?;
|
||||
book.entry(id).cloned()
|
||||
});
|
||||
if let Some(entry) = entry {
|
||||
self.recipe_ui.ghost.clear();
|
||||
self.fill_ghost(book_type, &entry);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ghost recipe ----
|
||||
|
||||
/// `fillGhostRecipe`: the recipe's ingredients faded into the slots.
|
||||
|
||||
@@ -478,6 +478,13 @@ impl Game<'_> {
|
||||
names.sort();
|
||||
Some(names)
|
||||
}
|
||||
/// The open menu's window id (0: the inventory).
|
||||
pub(super) fn remote_menu_id(&self) -> i32 {
|
||||
self.remote
|
||||
.as_ref()
|
||||
.and_then(|r| r.menu.as_ref())
|
||||
.map_or(0, |m| m.0)
|
||||
}
|
||||
/// 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()?;
|
||||
@@ -1525,6 +1532,10 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
C::OpenScreen(p) => self.remote_open_screen(p),
|
||||
C::RecipeBookAdd(p) => self.remote_recipe_book_add(p),
|
||||
C::RecipeBookRemove(p) => self.remote_recipe_book_remove(p),
|
||||
C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p),
|
||||
C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p),
|
||||
C::MerchantOffers(p) => self.remote_merchant_offers(p),
|
||||
C::ContainerClose(_) => {
|
||||
if self.screen == Screen::Inventory {
|
||||
|
||||
@@ -282,6 +282,20 @@ impl ServerAdvancements {
|
||||
book_add(entries, true)
|
||||
}
|
||||
|
||||
/// The recipe's display for ClientboundPlaceGhostRecipePacket (the
|
||||
/// recipes the book lists).
|
||||
pub fn ghost_display(
|
||||
&self,
|
||||
id: &str,
|
||||
sync: &SyncData,
|
||||
) -> Option<horizon_protocol::packets::recipes::RecipeDisplay> {
|
||||
let bytes = self.book_entries(id, sync, 0).into_iter().next()?;
|
||||
let mut r = horizon_protocol::buf::Reader::new(&bytes);
|
||||
horizon_protocol::packets::recipes::RecipeBookEntry::read(&mut r)
|
||||
.ok()
|
||||
.map(|e| e.display)
|
||||
}
|
||||
|
||||
/// ClientboundRecipeBookAddPacket.Entry for each display of a recipe:
|
||||
/// highlighted, and with a notification unless the recipe turns it off.
|
||||
fn book_entries(&self, id: &str, sync: &SyncData, flags: i8) -> Vec<Vec<u8>> {
|
||||
|
||||
@@ -838,6 +838,20 @@ impl Hub {
|
||||
}
|
||||
|
||||
/// ServerPlayer.initInventoryMenu / sendAllDataToRemote for the inventory menu.
|
||||
/// ClientboundPlaceGhostRecipePacket: the recipe `id` faded into the
|
||||
/// guest's menu `container`, whose items were missing.
|
||||
pub fn send_ghost_recipe(&mut self, conn: u32, container: i32, id: &str) {
|
||||
let Some(display) = self.sync.advancements.ghost_display(id, &self.sync) else {
|
||||
return;
|
||||
};
|
||||
self.send_to(
|
||||
conn,
|
||||
&C::PlaceGhostRecipe(horizon_protocol::packets::recipes::PlaceGhostRecipe {
|
||||
container,
|
||||
display,
|
||||
}),
|
||||
);
|
||||
}
|
||||
pub fn send_inventory(&mut self, i: usize) {
|
||||
let items: Vec<Option<ItemStack>> = (0..46).map(|s| self.guests[i].menu_slot(s)).collect();
|
||||
let net: Vec<_> = items.iter().map(|s| self.stack(s)).collect();
|
||||
|
||||
@@ -756,6 +756,15 @@ impl RecipeIndex {
|
||||
r.first_display..r.first_display + r.displays as i32
|
||||
})
|
||||
}
|
||||
/// The recipe a display id belongs to (`RecipeManager.getRecipeFromDisplay`).
|
||||
pub fn recipe_of_display(&self, display: i32) -> Option<&str> {
|
||||
self.recipes
|
||||
.iter()
|
||||
.find(|(_, r)| {
|
||||
(r.first_display..r.first_display + r.displays as i32).contains(&display)
|
||||
})
|
||||
.map(|(id, _)| id.as_str())
|
||||
}
|
||||
pub fn first_display(&self, id: &str) -> Option<i32> {
|
||||
self.recipes
|
||||
.get(id)
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod configuration;
|
||||
pub mod handshake;
|
||||
pub mod login;
|
||||
pub mod play;
|
||||
pub mod recipes;
|
||||
pub mod status;
|
||||
|
||||
use crate::buf::{Codec, Reader, Writer};
|
||||
|
||||
@@ -1363,6 +1363,10 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
ChunkBatchStart(Empty) = CHUNK_BATCH_START,
|
||||
ClearTitles(Bool1) = CLEAR_TITLES,
|
||||
Commands(Commands) = COMMANDS,
|
||||
RecipeBookAdd(super::recipes::RecipeBookAdd) = RECIPE_BOOK_ADD,
|
||||
RecipeBookRemove(super::recipes::RecipeBookRemove) = RECIPE_BOOK_REMOVE,
|
||||
RecipeBookSettings(super::recipes::RecipeBookSettings) = RECIPE_BOOK_SETTINGS,
|
||||
PlaceGhostRecipe(super::recipes::PlaceGhostRecipe) = PLACE_GHOST_RECIPE,
|
||||
ContainerClose(ContainerClose) = CONTAINER_CLOSE,
|
||||
ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT,
|
||||
ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA,
|
||||
@@ -1684,6 +1688,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
|
||||
ChangeGameMode(ChangeGameMode) = CHANGE_GAME_MODE,
|
||||
Chat(Chat) = CHAT,
|
||||
ChatCommand(ChatCommand) = CHAT_COMMAND,
|
||||
PlaceRecipe(super::recipes::PlaceRecipe) = PLACE_RECIPE,
|
||||
ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED,
|
||||
ClientCommand(ClientCommand) = CLIENT_COMMAND,
|
||||
ClientInformation(ClientInformation) = CLIENT_INFORMATION,
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
//! The recipe book's packets and the recipe displays they carry
|
||||
//! (`RecipeDisplay`, `SlotDisplay`, `RecipeDisplayEntry`): the 26.3
|
||||
//! `minecraft:recipe_display` and `minecraft:slot_display` types in id order.
|
||||
use crate::{
|
||||
Result,
|
||||
buf::{Codec, Reader, Writer},
|
||||
item::{Stack, Template},
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// `HolderSet<Item>` on the network: a tag by name, or item ids.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum HolderSet {
|
||||
Tag(String),
|
||||
Items(Vec<i32>),
|
||||
}
|
||||
impl HolderSet {
|
||||
pub fn read(r: &mut Reader) -> Result<Self> {
|
||||
let n = r.varint()? - 1;
|
||||
if n == -1 {
|
||||
return Ok(Self::Tag(r.string(32767)?));
|
||||
}
|
||||
let n = usize::try_from(n).map_err(|_| crate::Error::new("negative holder set size"))?;
|
||||
if n > r.remaining() {
|
||||
return Err(crate::Error::new("holder set larger than the packet"));
|
||||
}
|
||||
Ok(Self::Items(
|
||||
(0..n).map(|_| r.varint()).collect::<Result<_>>()?,
|
||||
))
|
||||
}
|
||||
pub fn write(&self, w: &mut Writer) {
|
||||
match self {
|
||||
Self::Tag(name) => {
|
||||
w.varint(0);
|
||||
w.string(name);
|
||||
}
|
||||
Self::Items(ids) => {
|
||||
w.varint(ids.len() as i32 + 1);
|
||||
ids.iter().for_each(|id| w.varint(*id));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trim pattern as `ByteBufCodecs.holder` sends it: a registry id, or
|
||||
/// the pattern itself.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TrimPattern {
|
||||
Id(i32),
|
||||
Direct {
|
||||
asset: String,
|
||||
description: Tag,
|
||||
decal: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// `SlotDisplay`: what a recipe book slot shows.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SlotDisplay {
|
||||
Empty,
|
||||
AnyFuel,
|
||||
WithAnyPotion(Box<SlotDisplay>),
|
||||
/// The source, kept to the stacks with this data component type.
|
||||
OnlyWithComponent(Box<SlotDisplay>, i32),
|
||||
Item(i32),
|
||||
ItemStack(Stack),
|
||||
Tag(HolderSet),
|
||||
Dyed {
|
||||
dye: Box<SlotDisplay>,
|
||||
target: Box<SlotDisplay>,
|
||||
},
|
||||
SmithingTrim {
|
||||
base: Box<SlotDisplay>,
|
||||
material: Box<SlotDisplay>,
|
||||
pattern: TrimPattern,
|
||||
},
|
||||
WithRemainder {
|
||||
input: Box<SlotDisplay>,
|
||||
remainder: Box<SlotDisplay>,
|
||||
},
|
||||
Composite(Vec<SlotDisplay>),
|
||||
}
|
||||
|
||||
/// How deep slot displays may nest (composites of composites…).
|
||||
const MAX_DEPTH: u32 = 32;
|
||||
|
||||
impl SlotDisplay {
|
||||
pub fn read(r: &mut Reader) -> Result<Self> {
|
||||
Self::read_at(r, 0)
|
||||
}
|
||||
fn read_at(r: &mut Reader, depth: u32) -> Result<Self> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(crate::Error::new("slot displays nest too deep"));
|
||||
}
|
||||
let inner = |r: &mut Reader| Self::read_at(r, depth + 1).map(Box::new);
|
||||
Ok(match r.varint()? {
|
||||
0 => Self::Empty,
|
||||
1 => Self::AnyFuel,
|
||||
2 => Self::WithAnyPotion(inner(r)?),
|
||||
3 => {
|
||||
let source = inner(r)?;
|
||||
Self::OnlyWithComponent(source, r.varint()?)
|
||||
}
|
||||
4 => Self::Item(r.varint()?),
|
||||
5 => Self::ItemStack(Template::read(r)?),
|
||||
6 => Self::Tag(HolderSet::read(r)?),
|
||||
7 => Self::Dyed {
|
||||
dye: inner(r)?,
|
||||
target: inner(r)?,
|
||||
},
|
||||
8 => {
|
||||
let base = inner(r)?;
|
||||
let material = inner(r)?;
|
||||
let pattern = match r.varint()? {
|
||||
0 => TrimPattern::Direct {
|
||||
asset: r.string(32767)?,
|
||||
description: r.nbt()?,
|
||||
decal: r.bool()?,
|
||||
},
|
||||
id => TrimPattern::Id(id - 1),
|
||||
};
|
||||
Self::SmithingTrim {
|
||||
base,
|
||||
material,
|
||||
pattern,
|
||||
}
|
||||
}
|
||||
9 => Self::WithRemainder {
|
||||
input: inner(r)?,
|
||||
remainder: inner(r)?,
|
||||
},
|
||||
10 => {
|
||||
let n = r.count(r.remaining())?;
|
||||
let mut out = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
out.push(Self::read_at(r, depth + 1)?);
|
||||
}
|
||||
Self::Composite(out)
|
||||
}
|
||||
id => return Err(crate::Error::new(format!("unknown slot display {id}"))),
|
||||
})
|
||||
}
|
||||
pub fn write(&self, w: &mut Writer) {
|
||||
match self {
|
||||
Self::Empty => w.varint(0),
|
||||
Self::AnyFuel => w.varint(1),
|
||||
Self::WithAnyPotion(d) => {
|
||||
w.varint(2);
|
||||
d.write(w);
|
||||
}
|
||||
Self::OnlyWithComponent(d, component) => {
|
||||
w.varint(3);
|
||||
d.write(w);
|
||||
w.varint(*component);
|
||||
}
|
||||
Self::Item(id) => {
|
||||
w.varint(4);
|
||||
w.varint(*id);
|
||||
}
|
||||
Self::ItemStack(stack) => {
|
||||
w.varint(5);
|
||||
Template::write(stack, w);
|
||||
}
|
||||
Self::Tag(set) => {
|
||||
w.varint(6);
|
||||
set.write(w);
|
||||
}
|
||||
Self::Dyed { dye, target } => {
|
||||
w.varint(7);
|
||||
dye.write(w);
|
||||
target.write(w);
|
||||
}
|
||||
Self::SmithingTrim {
|
||||
base,
|
||||
material,
|
||||
pattern,
|
||||
} => {
|
||||
w.varint(8);
|
||||
base.write(w);
|
||||
material.write(w);
|
||||
match pattern {
|
||||
TrimPattern::Id(id) => w.varint(id + 1),
|
||||
TrimPattern::Direct {
|
||||
asset,
|
||||
description,
|
||||
decal,
|
||||
} => {
|
||||
w.varint(0);
|
||||
w.string(asset);
|
||||
w.nbt(description);
|
||||
w.bool(*decal);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::WithRemainder { input, remainder } => {
|
||||
w.varint(9);
|
||||
input.write(w);
|
||||
remainder.write(w);
|
||||
}
|
||||
Self::Composite(list) => {
|
||||
w.varint(10);
|
||||
w.varint(list.len() as i32);
|
||||
list.iter().for_each(|d| d.write(w));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_list(r: &mut Reader) -> Result<Vec<SlotDisplay>> {
|
||||
let n = r.count(r.remaining())?;
|
||||
let mut out = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
out.push(SlotDisplay::read(r)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn write_list(list: &[SlotDisplay], w: &mut Writer) {
|
||||
w.varint(list.len() as i32);
|
||||
list.iter().for_each(|d| d.write(w));
|
||||
}
|
||||
|
||||
/// `RecipeDisplay`: a recipe as the recipe book draws it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum RecipeDisplay {
|
||||
Shapeless {
|
||||
ingredients: Vec<SlotDisplay>,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
},
|
||||
Shaped {
|
||||
width: i32,
|
||||
height: i32,
|
||||
ingredients: Vec<SlotDisplay>,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
},
|
||||
Furnace {
|
||||
ingredient: SlotDisplay,
|
||||
fuel: SlotDisplay,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
duration: i32,
|
||||
experience: f32,
|
||||
},
|
||||
Stonecutter {
|
||||
input: SlotDisplay,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
},
|
||||
Smithing {
|
||||
template: SlotDisplay,
|
||||
base: SlotDisplay,
|
||||
addition: SlotDisplay,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
},
|
||||
}
|
||||
impl RecipeDisplay {
|
||||
pub fn result(&self) -> &SlotDisplay {
|
||||
match self {
|
||||
Self::Shapeless { result, .. }
|
||||
| Self::Shaped { result, .. }
|
||||
| Self::Furnace { result, .. }
|
||||
| Self::Stonecutter { result, .. }
|
||||
| Self::Smithing { result, .. } => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Codec<RecipeDisplay> for RecipeDisplay {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
let slot = SlotDisplay::read;
|
||||
Ok(match r.varint()? {
|
||||
0 => Self::Shapeless {
|
||||
ingredients: read_list(r)?,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
},
|
||||
1 => {
|
||||
let (width, height) = (r.varint()?, r.varint()?);
|
||||
let ingredients = read_list(r)?;
|
||||
if i64::from(width) * i64::from(height) != ingredients.len() as i64 {
|
||||
return Err(crate::Error::new("shaped display size mismatch"));
|
||||
}
|
||||
Self::Shaped {
|
||||
width,
|
||||
height,
|
||||
ingredients,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
}
|
||||
}
|
||||
2 => Self::Furnace {
|
||||
ingredient: slot(r)?,
|
||||
fuel: slot(r)?,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
duration: r.varint()?,
|
||||
experience: r.f32()?,
|
||||
},
|
||||
3 => Self::Stonecutter {
|
||||
input: slot(r)?,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
},
|
||||
4 => Self::Smithing {
|
||||
template: slot(r)?,
|
||||
base: slot(r)?,
|
||||
addition: slot(r)?,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
},
|
||||
id => return Err(crate::Error::new(format!("unknown recipe display {id}"))),
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
match v {
|
||||
Self::Shapeless {
|
||||
ingredients,
|
||||
result,
|
||||
station,
|
||||
} => {
|
||||
w.varint(0);
|
||||
write_list(ingredients, w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
}
|
||||
Self::Shaped {
|
||||
width,
|
||||
height,
|
||||
ingredients,
|
||||
result,
|
||||
station,
|
||||
} => {
|
||||
w.varint(1);
|
||||
w.varint(*width);
|
||||
w.varint(*height);
|
||||
write_list(ingredients, w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
}
|
||||
Self::Furnace {
|
||||
ingredient,
|
||||
fuel,
|
||||
result,
|
||||
station,
|
||||
duration,
|
||||
experience,
|
||||
} => {
|
||||
w.varint(2);
|
||||
ingredient.write(w);
|
||||
fuel.write(w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
w.varint(*duration);
|
||||
w.f32(*experience);
|
||||
}
|
||||
Self::Stonecutter {
|
||||
input,
|
||||
result,
|
||||
station,
|
||||
} => {
|
||||
w.varint(3);
|
||||
input.write(w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
}
|
||||
Self::Smithing {
|
||||
template,
|
||||
base,
|
||||
addition,
|
||||
result,
|
||||
station,
|
||||
} => {
|
||||
w.varint(4);
|
||||
template.write(w);
|
||||
base.write(w);
|
||||
addition.write(w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `RecipeDisplayEntry` with `ClientboundRecipeBookAddPacket.Entry`'s flags
|
||||
/// (1 show a notification, 2 highlight as new).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RecipeBookEntry {
|
||||
pub id: i32,
|
||||
pub display: RecipeDisplay,
|
||||
/// The recipe group (0 none, else the group's index + 1).
|
||||
pub group: i32,
|
||||
/// `minecraft:recipe_book_category` id.
|
||||
pub category: i32,
|
||||
/// The ingredients the "craftable" filter checks, if the recipe has any.
|
||||
pub requirements: Option<Vec<HolderSet>>,
|
||||
pub flags: i8,
|
||||
}
|
||||
|
||||
/// ClientboundRecipeBookAddPacket: the entries, and whether they replace the
|
||||
/// client's book.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RecipeBookAdd {
|
||||
pub entries: Vec<RecipeBookEntry>,
|
||||
pub replace: bool,
|
||||
}
|
||||
impl RecipeBookEntry {
|
||||
pub fn read(r: &mut Reader) -> Result<Self> {
|
||||
let id = r.varint()?;
|
||||
let display = RecipeDisplay::read(r)?;
|
||||
let group = r.varint()?;
|
||||
let category = r.varint()?;
|
||||
let requirements = if r.bool()? {
|
||||
let k = r.count(r.remaining())?;
|
||||
let mut list = Vec::with_capacity(k.min(64));
|
||||
for _ in 0..k {
|
||||
list.push(HolderSet::read(r)?);
|
||||
}
|
||||
Some(list)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Self {
|
||||
id,
|
||||
display,
|
||||
group,
|
||||
category,
|
||||
requirements,
|
||||
flags: r.i8()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Codec<RecipeBookAdd> for RecipeBookAdd {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
let n = r.count(r.remaining())?;
|
||||
let mut entries = Vec::with_capacity(n.min(4096));
|
||||
for _ in 0..n {
|
||||
entries.push(RecipeBookEntry::read(r)?);
|
||||
}
|
||||
Ok(Self {
|
||||
entries,
|
||||
replace: r.bool()?,
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
w.varint(v.entries.len() as i32);
|
||||
for e in &v.entries {
|
||||
w.varint(e.id);
|
||||
RecipeDisplay::write(&e.display, w);
|
||||
w.varint(e.group);
|
||||
w.varint(e.category);
|
||||
w.bool(e.requirements.is_some());
|
||||
if let Some(list) = &e.requirements {
|
||||
w.varint(list.len() as i32);
|
||||
list.iter().for_each(|s| s.write(w));
|
||||
}
|
||||
w.i8(e.flags);
|
||||
}
|
||||
w.bool(v.replace);
|
||||
}
|
||||
}
|
||||
|
||||
/// ClientboundRecipeBookRemovePacket: the display ids.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RecipeBookRemove {
|
||||
pub ids: Vec<i32>,
|
||||
}
|
||||
impl Codec<RecipeBookRemove> for RecipeBookRemove {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
let n = r.count(r.remaining())?;
|
||||
Ok(Self {
|
||||
ids: (0..n).map(|_| r.varint()).collect::<Result<_>>()?,
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
w.varint(v.ids.len() as i32);
|
||||
v.ids.iter().for_each(|id| w.varint(*id));
|
||||
}
|
||||
}
|
||||
|
||||
/// RecipeBookSettings: each book's (open, filtering), in `RecipeBookType`
|
||||
/// order (crafting, furnace, blast furnace, smoker).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RecipeBookSettings {
|
||||
pub books: [(bool, bool); 4],
|
||||
}
|
||||
impl Codec<RecipeBookSettings> for RecipeBookSettings {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
let mut books = [(false, false); 4];
|
||||
for b in &mut books {
|
||||
*b = (r.bool()?, r.bool()?);
|
||||
}
|
||||
Ok(Self { books })
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
for (open, filtering) in v.books {
|
||||
w.bool(open);
|
||||
w.bool(filtering);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ClientboundPlaceGhostRecipePacket: the recipe to show faded in a menu
|
||||
/// whose items were missing.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PlaceGhostRecipe {
|
||||
pub container: i32,
|
||||
pub display: RecipeDisplay,
|
||||
}
|
||||
impl Codec<PlaceGhostRecipe> for PlaceGhostRecipe {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
Ok(Self {
|
||||
container: r.varint()?,
|
||||
display: RecipeDisplay::read(r)?,
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
w.varint(v.container);
|
||||
RecipeDisplay::write(&v.display, w);
|
||||
}
|
||||
}
|
||||
|
||||
/// ServerboundPlaceRecipePacket: place the recipe with this display id in
|
||||
/// the open menu, as many times as possible when `use_max` (shift).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PlaceRecipe {
|
||||
pub container: i32,
|
||||
pub recipe: i32,
|
||||
pub use_max: bool,
|
||||
}
|
||||
impl Codec<PlaceRecipe> for PlaceRecipe {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
Ok(Self {
|
||||
container: r.varint()?,
|
||||
recipe: r.varint()?,
|
||||
use_max: r.bool()?,
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
w.varint(v.container);
|
||||
w.varint(v.recipe);
|
||||
w.bool(v.use_max);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn book_entries_round_trip() {
|
||||
let add = RecipeBookAdd {
|
||||
entries: vec![
|
||||
RecipeBookEntry {
|
||||
id: 7,
|
||||
display: RecipeDisplay::Shaped {
|
||||
width: 2,
|
||||
height: 1,
|
||||
ingredients: vec![
|
||||
SlotDisplay::Tag(HolderSet::Tag("minecraft:planks".into())),
|
||||
SlotDisplay::Empty,
|
||||
],
|
||||
result: SlotDisplay::ItemStack(Stack::new(12, 4)),
|
||||
station: SlotDisplay::Item(300),
|
||||
},
|
||||
group: 3,
|
||||
category: 3,
|
||||
requirements: Some(vec![HolderSet::Items(vec![1, 2])]),
|
||||
flags: 3,
|
||||
},
|
||||
RecipeBookEntry {
|
||||
id: 8,
|
||||
display: RecipeDisplay::Smithing {
|
||||
template: SlotDisplay::Composite(vec![SlotDisplay::Item(1)]),
|
||||
base: SlotDisplay::WithRemainder {
|
||||
input: Box::new(SlotDisplay::AnyFuel),
|
||||
remainder: Box::new(SlotDisplay::Item(2)),
|
||||
},
|
||||
addition: SlotDisplay::OnlyWithComponent(
|
||||
Box::new(SlotDisplay::WithAnyPotion(Box::new(SlotDisplay::Item(3)))),
|
||||
9,
|
||||
),
|
||||
result: SlotDisplay::SmithingTrim {
|
||||
base: Box::new(SlotDisplay::Item(4)),
|
||||
material: Box::new(SlotDisplay::Dyed {
|
||||
dye: Box::new(SlotDisplay::Item(5)),
|
||||
target: Box::new(SlotDisplay::Item(6)),
|
||||
}),
|
||||
pattern: TrimPattern::Id(2),
|
||||
},
|
||||
station: SlotDisplay::Item(7),
|
||||
},
|
||||
group: 0,
|
||||
category: 11,
|
||||
requirements: None,
|
||||
flags: 0,
|
||||
},
|
||||
],
|
||||
replace: true,
|
||||
};
|
||||
let mut w = Writer::new();
|
||||
RecipeBookAdd::write(&add, &mut w);
|
||||
let mut r = Reader::new(&w.data);
|
||||
assert_eq!(RecipeBookAdd::read(&mut r).unwrap(), add);
|
||||
assert_eq!(r.remaining(), 0);
|
||||
}
|
||||
}
|
||||
+41
-2
@@ -21,7 +21,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
opens as 9x6 with the right half first;
|
||||
- feedback: the guest's command feedback names the guest and shows the numbers;
|
||||
- commands: the guest's chat completes commands and their arguments over the server's command
|
||||
tree (Tab), and runs what it completed.
|
||||
tree (Tab), and runs what it completed;
|
||||
- recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it
|
||||
places a log in the inventory's crafting grid (the server places it).
|
||||
|
||||
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).
|
||||
@@ -50,7 +52,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', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'trials']
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -515,6 +517,42 @@ def check_commands(host, guest, out):
|
||||
return {'literal': literal, 'argument': argument, 'mode': mode}
|
||||
|
||||
|
||||
def centre(rect):
|
||||
x, y, w, h = rect
|
||||
return x + w / 2, y + h / 2
|
||||
|
||||
|
||||
def grid_items(game):
|
||||
slots = game('screen').get('slots') or []
|
||||
return {s['slot']: s.get('item') for s in slots if 100 <= s['slot'] < 109 and s.get('item')}
|
||||
|
||||
|
||||
def check_recipes(host, guest, out):
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='give @s minecraft:oak_log 4')
|
||||
guest.wait(40)
|
||||
guest.raw('key', 'e', 'tap')
|
||||
guest.wait(5)
|
||||
try:
|
||||
book = guest('screen').get('recipe_book')
|
||||
assert book, 'the guest\'s inventory has no recipe book'
|
||||
if len(book['targets']) == 1:
|
||||
guest.raw('click-at', *centre(book['targets'][0]))
|
||||
guest.wait(5)
|
||||
book = guest('screen').get('recipe_book')
|
||||
known = book['known']
|
||||
assert known > 0, f'the guest\'s book is empty: {book}'
|
||||
guest.raw('click-at', *centre(book['targets'][1]))
|
||||
guest.wait(10)
|
||||
grid = grid_items(guest)
|
||||
guest.shot(out, 'recipes')
|
||||
finally:
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(5)
|
||||
assert any('oak_log' in str(item) for item in grid.values()), f'nothing placed in the grid: {grid}'
|
||||
return {'known': known, 'grid': grid}
|
||||
|
||||
|
||||
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()
|
||||
@@ -666,6 +704,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
|
||||
'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage,
|
||||
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'commands': check_commands,
|
||||
'recipes': check_recipes,
|
||||
'trials': check_trials,
|
||||
'walls': check_walls}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user