Merge origin/main into feat/campfire-cooking
Keeps both new block entities: BlockEntity::Campfire (this branch) and BlockEntity::Skull (main), in containers.rs's enum, id() and the menu lists in game.rs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+229
-310
File diff suppressed because it is too large
Load Diff
@@ -210,7 +210,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
|
||||
}),
|
||||
// The GUI of a 1280 x 720 window at scale 3.
|
||||
gui_size: (427.0, 240.0),
|
||||
held: None,
|
||||
..Snapshot::default()
|
||||
});
|
||||
mods.tick(t);
|
||||
for _ in 0..FRAMES_PER_TICK {
|
||||
|
||||
@@ -367,6 +367,7 @@ pub fn main() -> Result<()> {
|
||||
lid: &|_| open,
|
||||
sign: &|_| sign.as_ref(),
|
||||
banner: &|_| layers.clone(),
|
||||
skull: &|_| None,
|
||||
glyph: &|c| atlas.glyph_cell(c),
|
||||
};
|
||||
let mut verts = Vec::new();
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT
|
||||
use crate::pack_screen_fixture;
|
||||
use horizon_client::{
|
||||
chat::{ChatAction, ChatScreen, Commands},
|
||||
chat::{ChatAbilities, ChatAction, ChatScreen, ChatVisibility, Commands},
|
||||
command::vanilla,
|
||||
hud::HudAtlas,
|
||||
lang,
|
||||
@@ -53,6 +53,7 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
history.len(),
|
||||
w,
|
||||
h,
|
||||
ChatAbilities::new(ChatVisibility::Full),
|
||||
);
|
||||
screen.auto_suggestions = case["autoSuggest"] == true;
|
||||
let mut closed = false;
|
||||
|
||||
@@ -319,6 +319,7 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
|
||||
atlas,
|
||||
comp(&m["text"]),
|
||||
indicator,
|
||||
horizon_client::chat::ChatSource::Client,
|
||||
m["at"].as_u64().unwrap_or(0),
|
||||
false,
|
||||
);
|
||||
|
||||
@@ -730,6 +730,10 @@ pub struct Scene<'a> {
|
||||
pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>,
|
||||
/// Banner layers at a position: pattern texture and RGB tint, bottom first.
|
||||
pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>,
|
||||
/// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer`
|
||||
/// profile → skin): a downloaded `skins/<sha1>` slot or the profile's
|
||||
/// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (`DefaultPlayerSkin.getDefaultTexture`, slim steve).
|
||||
pub skull: &'a dyn Fn([i32; 3]) -> Option<&'a str>,
|
||||
/// Font glyph cell (none for blank glyphs such as the space) and advance.
|
||||
pub glyph: &'a dyn Fn(char) -> (Option<Rect>, f32),
|
||||
}
|
||||
@@ -1279,6 +1283,13 @@ impl BlockEntityRenderer {
|
||||
SkullType::Piglin => ("piglin_head", "entity/piglin/piglin"),
|
||||
SkullType::Player => ("player_head", "entity/player/slim/steve"),
|
||||
};
|
||||
// SkullBlockRenderer.getRenderType: the profile's skin when it
|
||||
// resolves, `SKIN_BY_TYPE` (steve) otherwise.
|
||||
let texture = if *kind == SkullType::Player {
|
||||
(scene.skull)(pos).unwrap_or(texture)
|
||||
} else {
|
||||
texture
|
||||
};
|
||||
let (Some(model), Some(paint)) =
|
||||
(self.models.get(model), paint(texture, 0xFFFFFF, packed))
|
||||
else {
|
||||
@@ -1886,6 +1897,7 @@ mod tests {
|
||||
lid: &|_| 0.0,
|
||||
sign: &|_| None,
|
||||
banner: &|_| Vec::new(),
|
||||
skull: &|_| None,
|
||||
glyph: &|_| (None, 0.0),
|
||||
};
|
||||
// Compare the cached world path with the original model renderer,
|
||||
|
||||
@@ -87,6 +87,19 @@ fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `LayeredCauldronBlock.handleEntityOnFireInside`: a burning entity in a
|
||||
/// water cauldron lowers it a level; a powder snow cauldron becomes a water
|
||||
/// cauldron of its level first, then lowers.
|
||||
pub fn extinguished(cauldron: &BlockState) -> BlockState {
|
||||
if cauldron.name == "minecraft:powder_snow_cauldron" {
|
||||
let mut water = cauldron.clone();
|
||||
water.name = "minecraft:water_cauldron".into();
|
||||
lowered(&water)
|
||||
} else {
|
||||
lowered(cauldron)
|
||||
}
|
||||
}
|
||||
|
||||
/// `LayeredCauldronBlock.lowerFillLevel`.
|
||||
fn lowered(cauldron: &BlockState) -> BlockState {
|
||||
let level: u8 = cauldron
|
||||
@@ -296,3 +309,24 @@ pub fn interact(
|
||||
_ => pass(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_burning_entity_lowers_water_and_melts_powder_snow() {
|
||||
let water = |l| state("minecraft:water_cauldron", Some(l));
|
||||
assert_eq!(extinguished(&water(3)), water(2));
|
||||
assert_eq!(extinguished(&water(1)), state("minecraft:cauldron", None));
|
||||
// Powder snow turns to water of its level, then lowers.
|
||||
assert_eq!(
|
||||
extinguished(&state("minecraft:powder_snow_cauldron", Some(3))),
|
||||
water(2)
|
||||
);
|
||||
assert_eq!(
|
||||
extinguished(&state("minecraft:powder_snow_cauldron", Some(1))),
|
||||
state("minecraft:cauldron", None)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,92 @@ mod tests;
|
||||
/// GuiMessageTag.systemSinglePlayer's indicator colour.
|
||||
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
|
||||
|
||||
/// `ChatVisiblity`: the Chat option's three values.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ChatVisibility {
|
||||
Full,
|
||||
System,
|
||||
Hidden,
|
||||
}
|
||||
impl ChatVisibility {
|
||||
/// Options.chatVisibility's saved value (0 full, 1 system, 2 hidden).
|
||||
pub fn from_option(value: u8) -> Self {
|
||||
match value {
|
||||
0 => Self::Full,
|
||||
1 => Self::System,
|
||||
_ => Self::Hidden,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ChatAbilities`: what the Chat option allows, as `Minecraft.computeChatAbilities`
|
||||
/// derives it from the visibility alone (`ChatRestriction`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ChatAbilities {
|
||||
pub send_messages: bool,
|
||||
pub send_commands: bool,
|
||||
pub receive_player_messages: bool,
|
||||
pub receive_system_messages: bool,
|
||||
}
|
||||
impl ChatAbilities {
|
||||
/// `ChatRestriction.CHAT_AND_COMMANDS_DISABLED_BY_OPTIONS` (Hidden) takes
|
||||
/// chat, commands, player messages and system messages;
|
||||
/// `CHAT_DISABLED_BY_OPTIONS` (System) takes the chat and player messages.
|
||||
pub fn new(visibility: ChatVisibility) -> Self {
|
||||
match visibility {
|
||||
ChatVisibility::Full => Self {
|
||||
send_messages: true,
|
||||
send_commands: true,
|
||||
receive_player_messages: true,
|
||||
receive_system_messages: true,
|
||||
},
|
||||
ChatVisibility::System => Self {
|
||||
send_messages: false,
|
||||
send_commands: true,
|
||||
receive_player_messages: false,
|
||||
receive_system_messages: true,
|
||||
},
|
||||
ChatVisibility::Hidden => Self {
|
||||
send_messages: false,
|
||||
send_commands: false,
|
||||
receive_player_messages: false,
|
||||
receive_system_messages: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
/// `visibleMessagesFilter`: the client's own lines always show.
|
||||
pub fn shows(&self, source: ChatSource) -> bool {
|
||||
match source {
|
||||
ChatSource::Player => self.receive_player_messages,
|
||||
ChatSource::Server => self.receive_system_messages,
|
||||
ChatSource::Client => true,
|
||||
}
|
||||
}
|
||||
/// Whether the chat screen may send `input` (`hasAllowedInput`).
|
||||
pub fn allows(&self, input: &str) -> bool {
|
||||
if input.starts_with('/') {
|
||||
self.send_commands
|
||||
} else {
|
||||
self.send_messages
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ChatAbilities {
|
||||
fn default() -> Self {
|
||||
Self::new(ChatVisibility::Full)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a chat line came from (`GuiMessageSource`): the visibility filters
|
||||
/// player messages and the server's, while the client's own always show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ChatSource {
|
||||
Player,
|
||||
Server,
|
||||
Client,
|
||||
}
|
||||
|
||||
/// The chat options (doubles, as vanilla keeps them).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ChatOptions {
|
||||
@@ -71,6 +157,7 @@ struct Message {
|
||||
added: u64,
|
||||
content: Text,
|
||||
indicator: Option<u32>,
|
||||
source: ChatSource,
|
||||
}
|
||||
/// A wrapped line (`GuiMessage.Line`).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -105,6 +192,8 @@ pub struct Chat {
|
||||
pub log: bool,
|
||||
/// Messages added since the start, for the control socket's events.
|
||||
pub received: u64,
|
||||
/// The Chat option's `visibleMessageFilter` (`set_abilities`).
|
||||
abilities: ChatAbilities,
|
||||
}
|
||||
impl Chat {
|
||||
pub fn lines_per_page(&self, focused: bool) -> usize {
|
||||
@@ -114,16 +203,32 @@ impl Chat {
|
||||
fn max_width(&self) -> i32 {
|
||||
(f64::from(self.options.width_px()) / self.options.scale).floor() as i32
|
||||
}
|
||||
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines.
|
||||
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. A
|
||||
/// message the Chat option hides is dropped, unlogged.
|
||||
pub fn add(
|
||||
&mut self,
|
||||
atlas: &HudAtlas,
|
||||
content: Text,
|
||||
indicator: Option<u32>,
|
||||
source: ChatSource,
|
||||
ticks: u64,
|
||||
focused: bool,
|
||||
) {
|
||||
// ChatComponent.logChatMessage: every message is in the log.
|
||||
self.add_message(&atlas.font, content, indicator, source, ticks, focused);
|
||||
}
|
||||
fn add_message(
|
||||
&mut self,
|
||||
font: &crate::font::Font,
|
||||
content: Text,
|
||||
indicator: Option<u32>,
|
||||
source: ChatSource,
|
||||
ticks: u64,
|
||||
focused: bool,
|
||||
) {
|
||||
if !self.abilities.shows(source) {
|
||||
return;
|
||||
}
|
||||
// ChatComponent.logChatMessage: every message shown is in the log.
|
||||
crate::logging::write_only(log::Level::Info, &format!("[CHAT] {}", content.plain()));
|
||||
if self.log {
|
||||
println!("[CHAT] {}", content.plain());
|
||||
@@ -132,16 +237,17 @@ impl Chat {
|
||||
added: ticks,
|
||||
content,
|
||||
indicator,
|
||||
source,
|
||||
};
|
||||
self.add_lines(atlas, &message, focused);
|
||||
self.add_lines(font, &message, focused);
|
||||
self.messages.insert(0, message);
|
||||
self.messages.truncate(100);
|
||||
self.received += 1;
|
||||
}
|
||||
fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) {
|
||||
fn add_lines(&mut self, font: &crate::font::Font, message: &Message, focused: bool) {
|
||||
let width = self.max_width();
|
||||
let content = self.displayed(&message.content);
|
||||
for line in atlas.font.wrap_components(&content, width) {
|
||||
for line in font.wrap_components(&content, width) {
|
||||
if focused && self.scroll > 0 {
|
||||
self.new_since_scroll = true;
|
||||
self.scroll_by(1, focused);
|
||||
@@ -167,16 +273,38 @@ impl Chat {
|
||||
content.strip_legacy()
|
||||
}
|
||||
}
|
||||
/// Re-wrap after a width or scale change (ChatComponent.rescaleChat).
|
||||
/// Re-wrap after a width or scale change (ChatComponent.rescaleChat),
|
||||
/// keeping only the messages the Chat option shows.
|
||||
pub fn rescale(&mut self, atlas: &HudAtlas) {
|
||||
self.rewrap(&atlas.font);
|
||||
}
|
||||
fn rewrap(&mut self, font: &crate::font::Font) {
|
||||
self.scroll = 0;
|
||||
self.new_since_scroll = false;
|
||||
self.lines.clear();
|
||||
let messages: Vec<Message> = self.messages.iter().rev().cloned().collect();
|
||||
let messages: Vec<Message> = self
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|m| self.abilities.shows(m.source))
|
||||
.cloned()
|
||||
.collect();
|
||||
for m in &messages {
|
||||
self.add_lines(atlas, m, false);
|
||||
self.add_lines(font, m, false);
|
||||
}
|
||||
}
|
||||
/// `ChatComponent.setVisibleMessageFilter`: the Chat option changed;
|
||||
/// the messages it now hides leave the chat, those it shows again return.
|
||||
pub fn set_abilities(&mut self, font: &crate::font::Font, abilities: ChatAbilities) {
|
||||
if self.abilities != abilities {
|
||||
self.abilities = abilities;
|
||||
self.rewrap(font);
|
||||
}
|
||||
}
|
||||
/// Whether a message from `source` would show (`visibleMessagesFilter`).
|
||||
pub fn shows(&self, source: ChatSource) -> bool {
|
||||
self.abilities.shows(source)
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.messages.clear();
|
||||
self.lines.clear();
|
||||
@@ -437,6 +565,8 @@ pub struct ChatScreen {
|
||||
allow_suggestions: bool,
|
||||
keep_suggestions: bool,
|
||||
pub auto_suggestions: bool,
|
||||
/// `CommandSuggestions.setRestrictions`: what the Chat option allows.
|
||||
pub abilities: ChatAbilities,
|
||||
}
|
||||
/// Local completions waiting for the server's reply to request `id`.
|
||||
struct Awaiting {
|
||||
@@ -482,6 +612,7 @@ impl ChatScreen {
|
||||
history_len: usize,
|
||||
width: i32,
|
||||
height: i32,
|
||||
abilities: ChatAbilities,
|
||||
) -> Self {
|
||||
let mut input = TextField::new(4, height - 12, width - 4, 12);
|
||||
input.max_length = 256;
|
||||
@@ -505,6 +636,7 @@ impl ChatScreen {
|
||||
allow_suggestions: false,
|
||||
keep_suggestions: false,
|
||||
auto_suggestions: true,
|
||||
abilities,
|
||||
};
|
||||
s.update_command_info(m, c);
|
||||
s
|
||||
@@ -522,7 +654,8 @@ impl ChatScreen {
|
||||
if (width, height) != (self.width, self.height) {
|
||||
let value = self.input.value.clone();
|
||||
let auto = self.auto_suggestions;
|
||||
*self = Self::new(m, c, &value, self.history_pos, width, height);
|
||||
let abilities = self.abilities;
|
||||
*self = Self::new(m, c, &value, self.history_pos, width, height, abilities);
|
||||
self.auto_suggestions = auto;
|
||||
}
|
||||
}
|
||||
@@ -604,6 +737,14 @@ impl ChatScreen {
|
||||
self.pending = Some((range.0, list));
|
||||
self.usage_width = 0;
|
||||
self.usage_position = 0;
|
||||
// CommandSuggestions.updateCommandInfo: the Chat option may take
|
||||
// the messages.
|
||||
if !self.abilities.send_messages {
|
||||
let line =
|
||||
Text::translate("chat_screen.messages_not_allowed", &[]).with_color(text::RED);
|
||||
self.usage_width = m.width(&line);
|
||||
self.usage.push(line);
|
||||
}
|
||||
} else {
|
||||
self.awaiting = None;
|
||||
self.pending = None;
|
||||
@@ -708,6 +849,15 @@ impl ChatScreen {
|
||||
}
|
||||
self.usage.extend(entries);
|
||||
}
|
||||
// CommandSuggestions.updateUsageInfo: the Chat option may take the
|
||||
// commands, under the usage. (Vanilla also counts a command with a
|
||||
// message argument, `/say hi`, as a message; Horizon's parse keeps no
|
||||
// argument kinds, so only a bare message does.)
|
||||
if !self.abilities.send_commands {
|
||||
self.usage.push(
|
||||
Text::translate("chat_screen.commands_not_allowed", &[]).with_color(text::RED),
|
||||
);
|
||||
}
|
||||
self.usage_width = self.usage.iter().map(|u| m.width(u)).max().unwrap_or(0);
|
||||
self.usage_position = if self.usage.is_empty() {
|
||||
0
|
||||
@@ -842,7 +992,14 @@ impl ChatScreen {
|
||||
}
|
||||
match key {
|
||||
K::Escape => return ChatAction::Close,
|
||||
K::Enter | K::NumpadEnter => return ChatAction::Submit(self.normalized()),
|
||||
K::Enter | K::NumpadEnter => {
|
||||
// ChatScreen.keyPressed: without `hasAllowedInput` the input
|
||||
// stays, unsent, and the screen stays open.
|
||||
if !self.abilities.allows(&self.input.value) {
|
||||
return ChatAction::None;
|
||||
}
|
||||
return ChatAction::Submit(self.normalized());
|
||||
}
|
||||
K::ArrowUp => self.move_in_history(m, c, history, -1),
|
||||
K::ArrowDown => self.move_in_history(m, c, history, 1),
|
||||
_ => {
|
||||
|
||||
@@ -2,6 +2,11 @@ use super::*;
|
||||
use crate::{font::Font, hud::Rect};
|
||||
use std::{collections::HashMap, path::Path};
|
||||
|
||||
/// The Chat option's default: no restriction.
|
||||
fn full() -> ChatAbilities {
|
||||
ChatAbilities::new(ChatVisibility::Full)
|
||||
}
|
||||
|
||||
fn font() -> Font {
|
||||
// The missing-glyph metrics let these tests run without game assets.
|
||||
Font::load(
|
||||
@@ -139,7 +144,7 @@ fn locate_coordinates_fill_chat_with_teleport_without_submitting() {
|
||||
assert_eq!(link.component()["click_event"]["command"], expected);
|
||||
let mut chat = Chat::default();
|
||||
add(&mut chat, &font, Text::literal("Found at ").append(link));
|
||||
let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360);
|
||||
let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360, full());
|
||||
let x = 4.0 + f64::from(font.width("Found at "));
|
||||
assert!(!screen.click(&m, &commands, x, 315.0));
|
||||
let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else {
|
||||
@@ -176,7 +181,15 @@ fn history_arrows_recall_messages_and_restore_the_draft() {
|
||||
registries: ®istries,
|
||||
};
|
||||
let history = vec!["first message".to_owned(), "latest message".to_owned()];
|
||||
let mut screen = ChatScreen::new(&m, &commands, "unfinished draft", history.len(), 640, 360);
|
||||
let mut screen = ChatScreen::new(
|
||||
&m,
|
||||
&commands,
|
||||
"unfinished draft",
|
||||
history.len(),
|
||||
640,
|
||||
360,
|
||||
full(),
|
||||
);
|
||||
for (key, expected) in [
|
||||
(ArrowUp, "latest message"),
|
||||
(ArrowUp, "first message"),
|
||||
@@ -213,7 +226,7 @@ fn mod_commands_are_coloured_and_complete_like_vanilla_ones() {
|
||||
dispatcher,
|
||||
registries: ®istries,
|
||||
};
|
||||
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
|
||||
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
|
||||
screen.type_text(&m, &c, line);
|
||||
screen
|
||||
};
|
||||
@@ -259,7 +272,7 @@ fn ask_server_nodes_wait_for_the_servers_completions() {
|
||||
let tab = |screen: &mut ChatScreen| {
|
||||
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false);
|
||||
};
|
||||
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
|
||||
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
|
||||
screen.type_text(&m, &c, "/bossbar get pt");
|
||||
let (request, sent) = screen.take_request().expect("the server is asked");
|
||||
assert_eq!(sent, "/bossbar get pt");
|
||||
@@ -281,7 +294,7 @@ fn ask_server_nodes_wait_for_the_servers_completions() {
|
||||
dispatcher: local,
|
||||
registries: ®istries,
|
||||
};
|
||||
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
|
||||
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
|
||||
screen.type_text(&m, &c, "/bossbar get pt");
|
||||
assert_eq!(screen.take_request(), None);
|
||||
}
|
||||
@@ -327,3 +340,99 @@ fn a_server_component_keeps_its_click_and_hover_events() {
|
||||
let past = 4.0 + f64::from(font.width("CLICK")) + 20.0;
|
||||
assert!(chat.hover_at(&font, 360, past, 315.0).is_none());
|
||||
}
|
||||
|
||||
/// `ChatVisiblity`: Commands Only keeps the chat out, Hidden takes the
|
||||
/// commands too (`ChatAbilities`), and Enter sends nothing the option hides.
|
||||
#[test]
|
||||
fn the_chat_option_decides_what_may_be_sent() {
|
||||
let font = font();
|
||||
let m = Measure(&font);
|
||||
let registries = Registries::default();
|
||||
let c = Commands {
|
||||
dispatcher: crate::command::vanilla::game_dispatcher(),
|
||||
registries: ®istries,
|
||||
};
|
||||
let enter = |screen: &mut ChatScreen| {
|
||||
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Enter, false, false)
|
||||
};
|
||||
for (visibility, chat, command) in [
|
||||
(ChatVisibility::Full, true, true),
|
||||
(ChatVisibility::System, false, true),
|
||||
(ChatVisibility::Hidden, false, false),
|
||||
] {
|
||||
let abilities = ChatAbilities::new(visibility);
|
||||
assert_eq!(abilities.allows("hi"), chat, "{visibility:?}");
|
||||
assert_eq!(abilities.allows("/time set day"), command, "{visibility:?}");
|
||||
for (line, allowed) in [("hi", chat), ("/time set day", command)] {
|
||||
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, abilities);
|
||||
screen.type_text(&m, &c, line);
|
||||
match enter(&mut screen) {
|
||||
ChatAction::Submit(sent) => {
|
||||
assert!(allowed, "{visibility:?} sent {sent}");
|
||||
assert_eq!(sent, line);
|
||||
}
|
||||
ChatAction::None => assert!(!allowed, "{visibility:?} kept {line}"),
|
||||
ChatAction::Close => panic!("Enter does not close the chat"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The restriction the option sets is a usage line: red, under the input, for
|
||||
/// a command the Chat option takes and for a message it takes.
|
||||
#[test]
|
||||
fn restricted_input_says_why_it_will_not_send() {
|
||||
let font = font();
|
||||
let m = Measure(&font);
|
||||
let registries = Registries::default();
|
||||
let c = Commands {
|
||||
dispatcher: crate::command::vanilla::game_dispatcher(),
|
||||
registries: ®istries,
|
||||
};
|
||||
let usage = |visibility, line: &str| {
|
||||
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, ChatAbilities::new(visibility));
|
||||
screen.type_text(&m, &c, line);
|
||||
screen.usage.iter().map(|t| t.plain()).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(usage(ChatVisibility::Full, "hi"), Vec::<String>::new());
|
||||
// The font has no language files here, so the line is its key.
|
||||
assert_eq!(
|
||||
usage(ChatVisibility::System, "hi"),
|
||||
["chat_screen.messages_not_allowed"]
|
||||
);
|
||||
// A command the option allows says nothing about the restriction.
|
||||
assert!(
|
||||
!usage(ChatVisibility::System, "/time set day")
|
||||
.iter()
|
||||
.any(|line| line == "chat_screen.commands_not_allowed")
|
||||
);
|
||||
assert!(
|
||||
usage(ChatVisibility::Hidden, "/time set day")
|
||||
.iter()
|
||||
.any(|line| line == "chat_screen.commands_not_allowed")
|
||||
);
|
||||
}
|
||||
|
||||
/// `ChatComponent.setVisibleMessageFilter`: a message the Chat option hides
|
||||
/// on arrival is dropped; one already in the chat leaves it while the option
|
||||
/// hides its kind and comes back when it shows it again.
|
||||
#[test]
|
||||
fn the_chat_option_filters_the_lines_both_ways() {
|
||||
let font = font();
|
||||
let mut chat = Chat::default();
|
||||
let says = |chat: &mut Chat, text: &str, source| {
|
||||
chat.add_message(&font, Text::literal(text), None, source, 0, false);
|
||||
};
|
||||
let shown =
|
||||
|chat: &Chat| -> Vec<String> { chat.lines.iter().map(|l| l.content.plain()).collect() };
|
||||
says(&mut chat, "player", ChatSource::Player);
|
||||
says(&mut chat, "server", ChatSource::Server);
|
||||
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::System));
|
||||
assert_eq!(shown(&chat), ["server"]);
|
||||
says(&mut chat, "dropped", ChatSource::Player);
|
||||
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Hidden));
|
||||
says(&mut chat, "client", ChatSource::Client);
|
||||
assert_eq!(shown(&chat), ["client"]);
|
||||
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Full));
|
||||
assert_eq!(shown(&chat), ["client", "server", "player"]);
|
||||
}
|
||||
|
||||
@@ -92,6 +92,13 @@ impl<W: BlockCollisionWorld> BlockCollisionWorld for EntityCollisions<'_, W> {
|
||||
) -> std::result::Result<bool, Self::Error> {
|
||||
self.blocks.is_suffocating(chunk, block, p)
|
||||
}
|
||||
fn may_reach_out(
|
||||
&mut self,
|
||||
chunk: Self::Chunk,
|
||||
section_y: i32,
|
||||
) -> std::result::Result<bool, Self::Error> {
|
||||
self.blocks.may_reach_out(chunk, section_y)
|
||||
}
|
||||
fn context_shape(
|
||||
&mut self,
|
||||
block: CollisionBlock,
|
||||
@@ -262,6 +269,17 @@ impl<'w> BlockCollisionWorld for SceneCollisions<'w, '_> {
|
||||
fn collision_block(&mut self, chunk: Self::Chunk, p: BlockPos) -> io::Result<CollisionBlock> {
|
||||
self.binding.collision_block(chunk.block(p.x, p.y, p.z))
|
||||
}
|
||||
/// From the section's palette, without reading its blocks; a palette
|
||||
/// of the whole registry reads every cell.
|
||||
fn may_reach_out(&mut self, chunk: Self::Chunk, section_y: i32) -> io::Result<bool> {
|
||||
let blocks = usize::try_from(section_y - (crate::chunk::MIN_Y >> 4))
|
||||
.ok()
|
||||
.and_then(|s| chunk.sections.get(s))
|
||||
.map(|section| §ion.blocks);
|
||||
Ok(blocks.is_none_or(|blocks| {
|
||||
blocks.is_global() || blocks.maybe_has(|v| self.binding.reaches_out(BlockStateId(v)))
|
||||
}))
|
||||
}
|
||||
fn is_suffocating(
|
||||
&mut self,
|
||||
_: Self::Chunk,
|
||||
|
||||
@@ -85,6 +85,8 @@ pub enum BlockEntity {
|
||||
CommandBlock(Box<crate::command_block::CommandBlock>),
|
||||
/// `CampfireBlockEntity` of campfires and soul campfires.
|
||||
Campfire(Box<Campfire>),
|
||||
/// `SkullBlockEntity` of every skull and head block.
|
||||
Skull(Skull),
|
||||
}
|
||||
/// `CampfireBlockEntity`: four cooking slots, each with its
|
||||
/// `cookingProgress` and `cookingTime` (the recipe's).
|
||||
@@ -141,6 +143,58 @@ impl Campfire {
|
||||
changed
|
||||
}
|
||||
}
|
||||
/// `SkullBlockEntity`: the player profile the head shows (kept as loaded:
|
||||
/// a compound, or a string when it names a player only), the note block
|
||||
/// sound and `custom_name`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Skull {
|
||||
pub profile: Option<horizon_world::nbt::Tag>,
|
||||
pub note_block_sound: Option<String>,
|
||||
pub custom_name: Option<horizon_world::nbt::Tag>,
|
||||
/// What `profile` draws, read from it once rather than every frame.
|
||||
pub skin: Option<SkullSkin>,
|
||||
}
|
||||
impl Skull {
|
||||
pub fn new(
|
||||
profile: Option<horizon_world::nbt::Tag>,
|
||||
note_block_sound: Option<String>,
|
||||
custom_name: Option<horizon_world::nbt::Tag>,
|
||||
) -> Self {
|
||||
let skin = profile.as_ref().map(SkullSkin::of);
|
||||
Self {
|
||||
profile,
|
||||
note_block_sound,
|
||||
custom_name,
|
||||
skin,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `SkullBlockRenderer.getPlayerSkin` of a head's profile: its skin's URL
|
||||
/// with the `skins/<sha1>` sprite it downloads to, and the
|
||||
/// `DefaultPlayerSkin` drawn until that sprite is there (steve for a
|
||||
/// profile with no id).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SkullSkin {
|
||||
pub download: Option<(String, String)>,
|
||||
pub fallback: &'static str,
|
||||
}
|
||||
impl SkullSkin {
|
||||
pub fn of(profile: &horizon_world::nbt::Tag) -> Self {
|
||||
let download = crate::skins::profile_skin_url_nbt(profile).and_then(|url| {
|
||||
let location = crate::skins::skin_location(&crate::skins::texture_hash(&url)?);
|
||||
Some((url, location))
|
||||
});
|
||||
// DefaultPlayerSkin.get(id), or getDefaultSkin (slim steve) without an id.
|
||||
let fallback = crate::skins::profile_uuid_nbt(profile)
|
||||
.map_or("entity/player/slim/steve", crate::tab_list::default_skin);
|
||||
Self { download, fallback }
|
||||
}
|
||||
}
|
||||
/// The skull and head blocks (`SkullBlock`, `WallSkullBlock`): every
|
||||
/// `*_skull` and `*_head` but the piston's head.
|
||||
fn is_skull(name: &str) -> bool {
|
||||
name.ends_with("_skull") || (name.ends_with("_head") && name != "minecraft:piston_head")
|
||||
}
|
||||
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
|
||||
/// and the ticks left in the crafting animation.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -295,6 +349,9 @@ impl BlockEntity {
|
||||
if name.ends_with("_banner") {
|
||||
return Some(Self::Banner(Banner::default()));
|
||||
}
|
||||
if is_skull(name) {
|
||||
return Some(Self::Skull(Skull::default()));
|
||||
}
|
||||
if name == "minecraft:beacon" {
|
||||
return Some(Self::Beacon(Box::new(Beacon {
|
||||
last_check_y: i32::MIN / 2,
|
||||
@@ -343,6 +400,7 @@ impl BlockEntity {
|
||||
Self::Vault(_) => "minecraft:vault",
|
||||
Self::Beehive(_) => "minecraft:beehive",
|
||||
Self::CommandBlock(_) => "minecraft:command_block",
|
||||
Self::Skull(_) => "minecraft:skull",
|
||||
Self::Campfire(_) => "minecraft:campfire",
|
||||
}
|
||||
}
|
||||
@@ -359,7 +417,8 @@ impl BlockEntity {
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Vault(_)
|
||||
| Self::Beehive(_)
|
||||
| Self::CommandBlock(_) => Vec::new(),
|
||||
| Self::CommandBlock(_)
|
||||
| Self::Skull(_) => Vec::new(),
|
||||
Self::Lectern(l) => l.book.iter().cloned().collect(),
|
||||
Self::Sculk(_) => Vec::new(),
|
||||
Self::Banner(_) => Vec::new(),
|
||||
@@ -377,7 +436,8 @@ impl BlockEntity {
|
||||
| Self::Beacon(_)
|
||||
| Self::Lectern(_)
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_) => &[],
|
||||
| Self::Banner(_)
|
||||
| Self::Skull(_) => &[],
|
||||
Self::Crafter(c) => &c.items,
|
||||
Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
@@ -399,7 +459,8 @@ impl BlockEntity {
|
||||
| Self::Beacon(_)
|
||||
| Self::Lectern(_)
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_) => &mut [],
|
||||
| Self::Banner(_)
|
||||
| Self::Skull(_) => &mut [],
|
||||
Self::Crafter(c) => &mut c.items,
|
||||
Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! `Player.getCooldowns()` (`ItemCooldowns`) as the game keeps it: the
|
||||
//! `use_cooldown` component's entries by cooldown group, counted down once a
|
||||
//! tick, and the percent `GuiGraphicsExtractor.itemCooldown` shades a slot
|
||||
//! by. The world crate's `item_cooldowns` models vanilla's hash map and its
|
||||
//! observers for the parity harness; this is the same data with the lookup a
|
||||
//! slot needs, and no observer (vanilla's own player uses the plain class).
|
||||
use crate::items::ItemStack;
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A stack's `minecraft:use_cooldown` component.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct UseCooldown {
|
||||
pub seconds: f32,
|
||||
/// `cooldown_group`: the group the entry is filed under, else the item.
|
||||
pub group: Option<Arc<str>>,
|
||||
}
|
||||
impl UseCooldown {
|
||||
/// `UseCooldown.ticks`: the seconds in ticks, truncated.
|
||||
pub fn ticks(&self) -> i32 {
|
||||
(self.seconds * 20.0) as i32
|
||||
}
|
||||
/// The component as `items.json` holds it.
|
||||
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
|
||||
let seconds = v.get("seconds")?.as_f64()? as f32;
|
||||
Some(Self {
|
||||
seconds,
|
||||
group: v
|
||||
.get("cooldown_group")
|
||||
.and_then(|g| g.as_str())
|
||||
.map(Arc::from),
|
||||
})
|
||||
}
|
||||
/// The component as a stack's saved `components` holds it.
|
||||
pub fn from_tag(t: &Tag) -> Option<Self> {
|
||||
let Tag::Compound(c) = t else {
|
||||
return None;
|
||||
};
|
||||
let text = |k: &str| match c.get(&horizon_world::nbt::JavaString::from(k)) {
|
||||
Some(Tag::String(s)) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
};
|
||||
let seconds = match c.get(&horizon_world::nbt::JavaString::from("seconds")) {
|
||||
Some(Tag::Float(bits)) => f32::from_bits(*bits),
|
||||
Some(Tag::Double(bits)) => f64::from_bits(*bits) as f32,
|
||||
_ => return None,
|
||||
};
|
||||
Some(Self {
|
||||
seconds,
|
||||
group: text("cooldown_group").map(Arc::from),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The component a stack carries: its own patch first (`ItemStack.get`), then
|
||||
/// the item's default from `items.json` (`ItemInfo::use_cooldown`).
|
||||
pub fn component(stack: &ItemStack, default: Option<&UseCooldown>) -> Option<UseCooldown> {
|
||||
stack
|
||||
.data()
|
||||
.and_then(|d| d.other("minecraft:use_cooldown"))
|
||||
.and_then(UseCooldown::from_tag)
|
||||
.or_else(|| default.cloned())
|
||||
}
|
||||
|
||||
/// `ItemCooldowns.getCooldownGroup`: the component's group, else the item id.
|
||||
pub fn group(stack: &ItemStack, default: Option<&UseCooldown>) -> Arc<str> {
|
||||
component(stack, default)
|
||||
.and_then(|c| c.group)
|
||||
.unwrap_or_else(|| Arc::clone(&stack.item))
|
||||
}
|
||||
|
||||
/// `ItemCooldowns`: start and end ticks by group, and the tick counter.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Cooldowns {
|
||||
tick_count: i32,
|
||||
entries: HashMap<Arc<str>, (i32, i32)>,
|
||||
}
|
||||
impl Cooldowns {
|
||||
/// `getCooldownPercent`: what is left of the entry, from 1 to 0.
|
||||
pub fn percent(&self, group: &str, partial_tick: f32) -> f32 {
|
||||
let Some((start, end)) = self.entries.get(group) else {
|
||||
return 0.0;
|
||||
};
|
||||
let duration = end.wrapping_sub(*start) as f32;
|
||||
let remaining = *end as f32 - (self.tick_count as f32 + partial_tick);
|
||||
(remaining / duration).clamp(0.0, 1.0)
|
||||
}
|
||||
/// `isOnCooldown`: whether the group still has time to run.
|
||||
pub fn is_on_cooldown(&self, group: &str) -> bool {
|
||||
self.percent(group, 0.0) > 0.0
|
||||
}
|
||||
/// `addCooldown`.
|
||||
pub fn add(&mut self, group: Arc<str>, ticks: i32) {
|
||||
self.entries.insert(
|
||||
group,
|
||||
(self.tick_count, self.tick_count.wrapping_add(ticks)),
|
||||
);
|
||||
}
|
||||
/// `ItemCooldowns.tick`: the counter, then every entry that has run out,
|
||||
/// which it hands back (`onCooldownEnded`).
|
||||
pub fn tick(&mut self) -> Vec<Arc<str>> {
|
||||
self.tick_count = self.tick_count.wrapping_add(1);
|
||||
let done: Vec<Arc<str>> = self
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|(_, (_, end))| *end <= self.tick_count)
|
||||
.map(|(group, _)| Arc::clone(group))
|
||||
.collect();
|
||||
self.entries.retain(|_, (_, end)| *end > self.tick_count);
|
||||
done
|
||||
}
|
||||
/// `removeCooldown`.
|
||||
pub fn remove(&mut self, group: &str) {
|
||||
self.entries.remove(group);
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn stack(item: &str) -> ItemStack {
|
||||
ItemStack::new(item, 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_percent_falls_from_one_to_zero_over_the_entry() {
|
||||
let mut c = Cooldowns::default();
|
||||
c.add(Arc::from("minecraft:ender_pearl"), 20);
|
||||
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
|
||||
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 1.0);
|
||||
for _ in 0..10 {
|
||||
assert!(c.tick().is_empty());
|
||||
}
|
||||
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.5);
|
||||
// The partial tick moves it within the tick.
|
||||
assert_eq!(c.percent("minecraft:ender_pearl", 0.5), 0.475);
|
||||
for _ in 0..9 {
|
||||
c.tick();
|
||||
}
|
||||
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
|
||||
// ItemCooldowns.tick drops the entry at its end tick, and says so.
|
||||
assert_eq!(c.tick(), [Arc::<str>::from("minecraft:ender_pearl")]);
|
||||
assert!(!c.is_on_cooldown("minecraft:ender_pearl"));
|
||||
assert!(c.is_empty());
|
||||
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_group_comes_from_the_stack_then_the_item() {
|
||||
let pearl = stack("minecraft:ender_pearl");
|
||||
let default = UseCooldown::from_json(&json!({"seconds": 1.0})).expect("the component");
|
||||
assert_eq!(&*group(&pearl, Some(&default)), "minecraft:ender_pearl");
|
||||
// A stack's own component overrides the item's, group included.
|
||||
let mut grouped = stack("minecraft:ender_pearl");
|
||||
grouped.data_mut().set_other(
|
||||
"minecraft:use_cooldown",
|
||||
Some(Tag::compound([
|
||||
("seconds", Tag::Float(2.0f32.to_bits())),
|
||||
("cooldown_group", Tag::String("minecraft:pearls".into())),
|
||||
])),
|
||||
);
|
||||
let c = component(&grouped, Some(&default)).expect("the stack's component");
|
||||
assert_eq!(c.ticks(), 40);
|
||||
assert_eq!(&*group(&grouped, Some(&default)), "minecraft:pearls");
|
||||
// An item without the component has no cooldown.
|
||||
assert!(component(&stack("minecraft:dirt"), None).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,794 @@
|
||||
//! Server dialogs (`net.minecraft.server.dialog`): what `Dialog.DIRECT_CODEC`
|
||||
//! decodes from a `show_dialog` packet, the values its inputs hold, and the
|
||||
//! click event an action makes of them (`Action.createAction`).
|
||||
use crate::text::Text;
|
||||
use horizon_world::nbt::Tag;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// `CommonDialogData` and the type's own fields.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Dialog {
|
||||
pub kind: Kind,
|
||||
pub title: Text,
|
||||
pub external_title: Option<Text>,
|
||||
pub can_close_with_escape: bool,
|
||||
pub pause: bool,
|
||||
pub after_action: AfterAction,
|
||||
pub body: Vec<Body>,
|
||||
pub inputs: Vec<Input>,
|
||||
}
|
||||
|
||||
/// The dialog types (`DialogTypes`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Kind {
|
||||
/// `NoticeDialog`: one button, "OK" when the server names none.
|
||||
Notice(Button),
|
||||
Confirmation {
|
||||
yes: Button,
|
||||
no: Button,
|
||||
},
|
||||
MultiAction {
|
||||
actions: Vec<Button>,
|
||||
exit: Option<Button>,
|
||||
columns: i32,
|
||||
},
|
||||
ServerLinks {
|
||||
exit: Option<Button>,
|
||||
columns: i32,
|
||||
button_width: i32,
|
||||
},
|
||||
/// `DialogListDialog`: its dialogs as sent (ids, a tag or inline dialogs).
|
||||
DialogList {
|
||||
dialogs: Tag,
|
||||
exit: Option<Button>,
|
||||
columns: i32,
|
||||
button_width: i32,
|
||||
},
|
||||
}
|
||||
|
||||
/// `DialogAction`: the screen after an action runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AfterAction {
|
||||
Close,
|
||||
None,
|
||||
WaitForResponse,
|
||||
}
|
||||
|
||||
/// `ActionButton`: `CommonButtonData` and what it does.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Button {
|
||||
pub label: Text,
|
||||
pub tooltip: Option<Text>,
|
||||
pub width: i32,
|
||||
pub action: Option<Action>,
|
||||
}
|
||||
|
||||
/// `Action`: a fixed click event, or one made from the inputs' values.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Action {
|
||||
/// `StaticAction`: a click event as it is.
|
||||
Static(Click),
|
||||
/// `CommandTemplate`: a command with `$(key)` replaced by input values.
|
||||
RunCommand(String),
|
||||
/// `CustomAll`: a custom click event whose payload is `additions` plus
|
||||
/// every input's value under its key.
|
||||
Custom { id: String, additions: Option<Tag> },
|
||||
}
|
||||
|
||||
/// `ClickEvent`, the kinds a server may send (`isAllowedFromServer`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Click {
|
||||
OpenUrl(String),
|
||||
RunCommand(String),
|
||||
SuggestCommand(String),
|
||||
/// The dialog: an id of the `minecraft:dialog` registry or the dialog itself.
|
||||
ShowDialog(Tag),
|
||||
ChangePage(i32),
|
||||
CopyToClipboard(String),
|
||||
Custom {
|
||||
id: String,
|
||||
payload: Option<Tag>,
|
||||
},
|
||||
}
|
||||
|
||||
/// `DialogBody`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Body {
|
||||
/// `PlainMessage`: centred text wrapped to `width`.
|
||||
Message { contents: Text, width: i32 },
|
||||
/// `ItemBody`: the item as `ItemStackTemplate` sent it.
|
||||
Item {
|
||||
item: Tag,
|
||||
description: Option<(Text, i32)>,
|
||||
show_decorations: bool,
|
||||
show_tooltip: bool,
|
||||
width: i32,
|
||||
height: i32,
|
||||
},
|
||||
}
|
||||
|
||||
/// `Input`: the key its value goes by, and its control.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Input {
|
||||
pub key: String,
|
||||
pub control: Control,
|
||||
}
|
||||
|
||||
/// `InputControl`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Control {
|
||||
Text {
|
||||
width: i32,
|
||||
label: Text,
|
||||
label_visible: bool,
|
||||
initial: String,
|
||||
max_length: i32,
|
||||
/// `MultilineOptions`: the most lines and the height, when set.
|
||||
multiline: Option<(Option<i32>, Option<i32>)>,
|
||||
},
|
||||
Boolean {
|
||||
label: Text,
|
||||
initial: bool,
|
||||
on_true: String,
|
||||
on_false: String,
|
||||
},
|
||||
SingleOption {
|
||||
width: i32,
|
||||
/// Each option's id, its label and whether it is the initial one.
|
||||
options: Vec<(String, Option<Text>, bool)>,
|
||||
label: Text,
|
||||
label_visible: bool,
|
||||
},
|
||||
NumberRange {
|
||||
width: i32,
|
||||
label: Text,
|
||||
label_format: String,
|
||||
start: f32,
|
||||
end: f32,
|
||||
initial: Option<f32>,
|
||||
step: Option<f32>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What an input holds while the dialog is open.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum InputValue {
|
||||
Text(String),
|
||||
Bool(bool),
|
||||
/// The chosen option's index.
|
||||
Option(usize),
|
||||
/// The slider's position, 0 to 1.
|
||||
Slider(f32),
|
||||
}
|
||||
|
||||
fn text(t: &Tag) -> Text {
|
||||
crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t))
|
||||
}
|
||||
fn string(t: Option<&Tag>) -> Option<String> {
|
||||
match t? {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn number(t: Option<&Tag>) -> Option<f64> {
|
||||
Some(match t? {
|
||||
Tag::Byte(v) => f64::from(*v),
|
||||
Tag::Short(v) => f64::from(*v),
|
||||
Tag::Int(v) => f64::from(*v),
|
||||
Tag::Long(v) => *v as f64,
|
||||
Tag::Float(v) => f64::from(f32::from_bits(*v)),
|
||||
Tag::Double(v) => f64::from_bits(*v),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn int(t: &Tag, key: &str, default: i32) -> i32 {
|
||||
number(t.get(key)).map_or(default, |v| v as i32)
|
||||
}
|
||||
fn boolean(t: &Tag, key: &str, default: bool) -> bool {
|
||||
number(t.get(key)).map_or(default, |v| v != 0.0)
|
||||
}
|
||||
fn list(t: Option<&Tag>) -> &[Tag] {
|
||||
match t {
|
||||
Some(Tag::List(items)) => items,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
/// A registry name without its default namespace.
|
||||
fn path(id: &str) -> &str {
|
||||
id.strip_prefix("minecraft:").unwrap_or(id)
|
||||
}
|
||||
|
||||
impl Button {
|
||||
/// `ActionButton.CODEC`.
|
||||
fn parse(t: &Tag) -> Option<Self> {
|
||||
Some(Self {
|
||||
label: text(t.get("label")?),
|
||||
tooltip: t.get("tooltip").map(text),
|
||||
width: int(t, "width", 150),
|
||||
action: t.get("action").and_then(Action::parse),
|
||||
})
|
||||
}
|
||||
/// `NoticeDialog.DEFAULT_ACTION`.
|
||||
fn ok() -> Self {
|
||||
Self {
|
||||
label: Text::translate("gui.ok", &[]),
|
||||
tooltip: None,
|
||||
width: 150,
|
||||
action: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Click {
|
||||
/// `ClickEvent.CODEC`, from its `action` (a click event in a component)
|
||||
/// or `type` (an action) field.
|
||||
pub fn parse(t: &Tag, kind: &str) -> Option<Self> {
|
||||
let s = |key| string(t.get(key));
|
||||
Some(match path(kind) {
|
||||
"open_url" => Self::OpenUrl(s("url")?),
|
||||
"run_command" => Self::RunCommand(s("command")?),
|
||||
"suggest_command" => Self::SuggestCommand(s("command")?),
|
||||
"show_dialog" => Self::ShowDialog(t.get("dialog")?.clone()),
|
||||
"change_page" => Self::ChangePage(int(t, "page", 1)),
|
||||
"copy_to_clipboard" => Self::CopyToClipboard(s("value")?),
|
||||
"custom" => Self::Custom {
|
||||
id: s("id")?,
|
||||
payload: t.get("payload").cloned(),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Action {
|
||||
/// `Action.CODEC`, dispatched on `type`.
|
||||
fn parse(t: &Tag) -> Option<Self> {
|
||||
let kind = string(t.get("type"))?;
|
||||
Some(match path(&kind) {
|
||||
"dynamic/run_command" => Self::RunCommand(string(t.get("template"))?),
|
||||
"dynamic/custom" => Self::Custom {
|
||||
id: string(t.get("id"))?,
|
||||
additions: t.get("additions").cloned(),
|
||||
},
|
||||
other => Self::Static(Click::parse(t, other)?),
|
||||
})
|
||||
}
|
||||
/// `createAction`: the click event, given each input's key, control and value.
|
||||
pub fn click(&self, inputs: &[Input], values: &[InputValue]) -> Option<Click> {
|
||||
let values = || inputs.iter().zip(values);
|
||||
Some(match self {
|
||||
Self::Static(click) => click.clone(),
|
||||
Self::RunCommand(template) => Click::RunCommand(substitute(template, &|key| {
|
||||
values()
|
||||
.find(|(i, _)| i.key == key)
|
||||
.map(|(i, v)| i.control.substitution(v))
|
||||
})),
|
||||
Self::Custom { id, additions } => {
|
||||
let mut tag = match additions {
|
||||
Some(t @ Tag::Compound(_)) => t.clone(),
|
||||
_ => Tag::Compound(Default::default()),
|
||||
};
|
||||
for (input, value) in values() {
|
||||
if let Tag::Compound(map) = &mut tag {
|
||||
map.insert(input.key.as_str().into(), input.control.tag(value));
|
||||
}
|
||||
}
|
||||
Click::Custom {
|
||||
id: id.clone(),
|
||||
payload: Some(tag),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `ParsedTemplate.instantiate`: each `$(key)` replaced by its value, or by
|
||||
/// nothing for a key no input has.
|
||||
fn substitute(template: &str, value: &dyn Fn(&str) -> Option<String>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = template;
|
||||
while let Some(at) = rest.find("$(") {
|
||||
let Some(end) = rest[at..].find(')') else {
|
||||
break;
|
||||
};
|
||||
out.push_str(&rest[..at]);
|
||||
out.push_str(&value(&rest[at + 2..at + end]).unwrap_or_default());
|
||||
rest = &rest[at + end + 1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// `StringTag.escapeWithoutQuotes`.
|
||||
fn escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' | '\'' | '\\' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
'\u{8}' => out.push_str("\\b"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\u{c}' => out.push_str("\\f"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
c if c < ' ' => out.push_str(&format!("\\x{:02x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Control {
|
||||
/// `InputControl.MAP_CODEC`, dispatched on `type`.
|
||||
fn parse(t: &Tag) -> Option<Self> {
|
||||
let label = || t.get("label").map(text);
|
||||
Some(match path(&string(t.get("type"))?) {
|
||||
"text" => Self::Text {
|
||||
width: int(t, "width", 200),
|
||||
label: label()?,
|
||||
label_visible: boolean(t, "label_visible", true),
|
||||
initial: string(t.get("initial")).unwrap_or_default(),
|
||||
max_length: int(t, "max_length", 32),
|
||||
multiline: t.get("multiline").map(|m| {
|
||||
let get = |key| number(m.get(key)).map(|v| v as i32);
|
||||
(get("max_lines"), get("height"))
|
||||
}),
|
||||
},
|
||||
"boolean" => Self::Boolean {
|
||||
label: label()?,
|
||||
initial: boolean(t, "initial", false),
|
||||
on_true: string(t.get("on_true")).unwrap_or_else(|| "true".into()),
|
||||
on_false: string(t.get("on_false")).unwrap_or_else(|| "false".into()),
|
||||
},
|
||||
"single_option" => Self::SingleOption {
|
||||
width: int(t, "width", 200),
|
||||
// SingleOptionInput.Entry.CODEC: a full entry or just its id.
|
||||
options: list(t.get("options"))
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
Tag::String(id) => Some((id.to_string_lossy(), None, false)),
|
||||
o => Some((
|
||||
string(o.get("id"))?,
|
||||
o.get("display").map(text),
|
||||
boolean(o, "initial", false),
|
||||
)),
|
||||
})
|
||||
.collect(),
|
||||
label: label()?,
|
||||
label_visible: boolean(t, "label_visible", true),
|
||||
},
|
||||
"number_range" => {
|
||||
let float = |key| number(t.get(key)).map(|v| v as f32);
|
||||
Self::NumberRange {
|
||||
width: int(t, "width", 200),
|
||||
label: label()?,
|
||||
label_format: string(t.get("label_format"))
|
||||
.unwrap_or_else(|| "options.generic_value".into()),
|
||||
start: float("start")?,
|
||||
end: float("end")?,
|
||||
initial: float("initial"),
|
||||
step: float("step"),
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// The value it starts with.
|
||||
pub fn initial(&self) -> InputValue {
|
||||
match self {
|
||||
Self::Text { initial, .. } => InputValue::Text(initial.clone()),
|
||||
Self::Boolean { initial, .. } => InputValue::Bool(*initial),
|
||||
Self::SingleOption { options, .. } => {
|
||||
InputValue::Option(options.iter().position(|o| o.2).unwrap_or(0))
|
||||
}
|
||||
Self::NumberRange {
|
||||
start,
|
||||
end,
|
||||
initial,
|
||||
..
|
||||
} => InputValue::Slider(to_slider(
|
||||
initial.unwrap_or((start + end) / 2.0),
|
||||
*start,
|
||||
*end,
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// `ValueGetter.asTemplateSubstitution`.
|
||||
pub fn substitution(&self, value: &InputValue) -> String {
|
||||
match (self, value) {
|
||||
(Self::Text { .. }, InputValue::Text(s)) => escape(s),
|
||||
(
|
||||
Self::Boolean {
|
||||
on_true, on_false, ..
|
||||
},
|
||||
InputValue::Bool(b),
|
||||
) => if *b { on_true } else { on_false }.clone(),
|
||||
(Self::SingleOption { options, .. }, InputValue::Option(i)) => {
|
||||
options.get(*i).map(|o| o.0.clone()).unwrap_or_default()
|
||||
}
|
||||
(Self::NumberRange { .. }, InputValue::Slider(_)) => {
|
||||
number_string(self.scaled(value).unwrap_or(0.0))
|
||||
}
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
/// `ValueGetter.asTag`.
|
||||
pub fn tag(&self, value: &InputValue) -> Tag {
|
||||
match (self, value) {
|
||||
(Self::Boolean { .. }, InputValue::Bool(b)) => Tag::Byte(i8::from(*b)),
|
||||
(Self::NumberRange { .. }, _) => {
|
||||
Tag::Float(self.scaled(value).unwrap_or(0.0).to_bits())
|
||||
}
|
||||
(Self::Text { .. }, InputValue::Text(s)) => Tag::String(s.as_str().into()),
|
||||
_ => Tag::String(self.substitution(value).as_str().into()),
|
||||
}
|
||||
}
|
||||
/// `RangeInfo.computeScaledValue`: a number range's value at its slider position.
|
||||
pub fn scaled(&self, value: &InputValue) -> Option<f32> {
|
||||
let (
|
||||
Self::NumberRange {
|
||||
start,
|
||||
end,
|
||||
initial,
|
||||
step,
|
||||
..
|
||||
},
|
||||
InputValue::Slider(slider),
|
||||
) = (self, value)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let (start, end) = (*start, *end);
|
||||
let in_range = start + slider * (end - start);
|
||||
let Some(step) = step else {
|
||||
return Some(in_range);
|
||||
};
|
||||
let first = initial.unwrap_or((start + end) / 2.0);
|
||||
// Math.round: half up.
|
||||
let steps = ((in_range - first) / step + 0.5).floor() as i32;
|
||||
let result = first + steps as f32 * step;
|
||||
let position = to_slider(result, start, end);
|
||||
if (0.0..=1.0).contains(&position) {
|
||||
return Some(result);
|
||||
}
|
||||
Some(first + (steps - steps.signum()) as f32 * step)
|
||||
}
|
||||
}
|
||||
|
||||
/// `RangeInfo.scaledValueToSlider`.
|
||||
fn to_slider(value: f32, start: f32, end: f32) -> f32 {
|
||||
if start == end {
|
||||
0.5
|
||||
} else {
|
||||
(value - start) / (end - start)
|
||||
}
|
||||
}
|
||||
|
||||
/// `SliderImpl.valueToString`: whole numbers without a fraction, the rest as
|
||||
/// Java's `Float.toString`.
|
||||
pub fn number_string(v: f32) -> String {
|
||||
if v == (v as i32) as f32 {
|
||||
(v as i32).to_string()
|
||||
} else {
|
||||
crate::snbt::java_float(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl Body {
|
||||
/// `DialogBody.DIALOG_BODY_CODEC`.
|
||||
fn parse(t: &Tag) -> Option<Self> {
|
||||
let message = |t: &Tag| -> Option<(Text, i32)> {
|
||||
// PlainMessage.CODEC: the full form or just its contents.
|
||||
match t {
|
||||
Tag::Compound(_) if t.get("contents").is_some() => {
|
||||
Some((text(t.get("contents")?), int(t, "width", 200)))
|
||||
}
|
||||
t => Some((text(t), 200)),
|
||||
}
|
||||
};
|
||||
Some(match path(&string(t.get("type"))?) {
|
||||
"plain_message" => {
|
||||
let (contents, width) = message(t)?;
|
||||
Self::Message { contents, width }
|
||||
}
|
||||
"item" => Self::Item {
|
||||
item: t.get("item")?.clone(),
|
||||
description: t.get("description").and_then(message),
|
||||
show_decorations: boolean(t, "show_decorations", true),
|
||||
show_tooltip: boolean(t, "show_tooltip", true),
|
||||
width: int(t, "width", 16),
|
||||
height: int(t, "height", 16),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Dialog {
|
||||
/// `Dialog.DIRECT_CODEC`; `None` for a type or field it can't read
|
||||
/// (vanilla fails the whole packet then).
|
||||
pub fn parse(t: &Tag) -> Option<Self> {
|
||||
let button = |key: &str| t.get(key).and_then(Button::parse);
|
||||
let kind = match path(&string(t.get("type"))?) {
|
||||
"notice" => Kind::Notice(match t.get("action") {
|
||||
Some(b) => Button::parse(b)?,
|
||||
None => Button::ok(),
|
||||
}),
|
||||
"confirmation" => Kind::Confirmation {
|
||||
yes: button("yes")?,
|
||||
no: button("no")?,
|
||||
},
|
||||
"multi_action" => Kind::MultiAction {
|
||||
actions: list(t.get("actions"))
|
||||
.iter()
|
||||
.map(Button::parse)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.filter(|a| !a.is_empty())?,
|
||||
exit: button("exit_action"),
|
||||
columns: int(t, "columns", 2),
|
||||
},
|
||||
"server_links" => Kind::ServerLinks {
|
||||
exit: button("exit_action"),
|
||||
columns: int(t, "columns", 2),
|
||||
button_width: int(t, "button_width", 150),
|
||||
},
|
||||
"dialog_list" => Kind::DialogList {
|
||||
dialogs: t.get("dialogs")?.clone(),
|
||||
exit: button("exit_action"),
|
||||
columns: int(t, "columns", 2),
|
||||
button_width: int(t, "button_width", 150),
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
// DialogBody.COMPACT_LIST_CODEC: one body, or a list of them.
|
||||
let body = match t.get("body") {
|
||||
Some(Tag::List(items)) => items.iter().filter_map(Body::parse).collect(),
|
||||
Some(one) => Body::parse(one).into_iter().collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let inputs = list(t.get("inputs"))
|
||||
.iter()
|
||||
.filter_map(|i| {
|
||||
Some(Input {
|
||||
key: string(i.get("key"))?,
|
||||
control: Control::parse(i)?,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(Self {
|
||||
kind,
|
||||
title: text(t.get("title")?),
|
||||
external_title: t.get("external_title").map(text),
|
||||
can_close_with_escape: boolean(t, "can_close_with_escape", true),
|
||||
pause: boolean(t, "pause", true),
|
||||
after_action: match string(t.get("after_action")).as_deref() {
|
||||
Some("none") => AfterAction::None,
|
||||
Some("wait_for_response") => AfterAction::WaitForResponse,
|
||||
_ => AfterAction::Close,
|
||||
},
|
||||
body,
|
||||
inputs,
|
||||
})
|
||||
}
|
||||
/// `onCancel`: what Escape (or closing it) does.
|
||||
pub fn on_cancel(&self) -> Option<&Action> {
|
||||
match &self.kind {
|
||||
Kind::Notice(b) => b.action.as_ref(),
|
||||
Kind::Confirmation { no, .. } => no.action.as_ref(),
|
||||
Kind::MultiAction { exit, .. }
|
||||
| Kind::ServerLinks { exit, .. }
|
||||
| Kind::DialogList { exit, .. } => exit.as_ref().and_then(|b| b.action.as_ref()),
|
||||
}
|
||||
}
|
||||
/// The buttons it draws, in order: the list, then the footer's.
|
||||
pub fn buttons(&self) -> Vec<&Button> {
|
||||
match &self.kind {
|
||||
Kind::Notice(b) => vec![b],
|
||||
Kind::Confirmation { yes, no } => vec![yes, no],
|
||||
Kind::MultiAction { actions, exit, .. } => actions.iter().chain(exit).collect(),
|
||||
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => exit.iter().collect(),
|
||||
}
|
||||
}
|
||||
/// What `status` reports of it.
|
||||
pub fn json(&self, values: &[InputValue]) -> Value {
|
||||
let kind = match &self.kind {
|
||||
Kind::Notice(_) => "notice",
|
||||
Kind::Confirmation { .. } => "confirmation",
|
||||
Kind::MultiAction { .. } => "multi_action",
|
||||
Kind::ServerLinks { .. } => "server_links",
|
||||
Kind::DialogList { .. } => "dialog_list",
|
||||
};
|
||||
let inputs: Vec<Value> = self
|
||||
.inputs
|
||||
.iter()
|
||||
.zip(values)
|
||||
.map(|(i, v)| {
|
||||
let kind = match i.control {
|
||||
Control::Text { .. } => "text",
|
||||
Control::Boolean { .. } => "boolean",
|
||||
Control::SingleOption { .. } => "single_option",
|
||||
Control::NumberRange { .. } => "number_range",
|
||||
};
|
||||
json!({"key": i.key, "type": kind, "value": i.control.substitution(v)})
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"type": kind,
|
||||
"title": self.title.plain(),
|
||||
"body": self.body.iter().map(|b| match b {
|
||||
Body::Message { contents, .. } => contents.plain(),
|
||||
Body::Item { item, .. } => string(item.get("id")).unwrap_or_default(),
|
||||
}).collect::<Vec<_>>(),
|
||||
"inputs": inputs,
|
||||
"buttons": self.buttons().iter().map(|b| b.label.plain()).collect::<Vec<_>>(),
|
||||
"can_close_with_escape": self.can_close_with_escape,
|
||||
"after_action": match self.after_action {
|
||||
AfterAction::Close => "close",
|
||||
AfterAction::None => "none",
|
||||
AfterAction::WaitForResponse => "wait_for_response",
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn s(v: &str) -> Tag {
|
||||
Tag::String(v.into())
|
||||
}
|
||||
|
||||
/// The register dialog AuthMe 6 sends in configuration (the shape its
|
||||
/// `show_dialog` packet has on the test bed).
|
||||
fn register() -> Tag {
|
||||
Tag::compound([
|
||||
("type", s("minecraft:multi_action")),
|
||||
("title", s("Register")),
|
||||
("can_close_with_escape", Tag::Byte(0)),
|
||||
("after_action", s("wait_for_response")),
|
||||
(
|
||||
"body",
|
||||
Tag::compound([
|
||||
("type", s("minecraft:plain_message")),
|
||||
("contents", s("Choose a password")),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"inputs",
|
||||
Tag::List(vec![Tag::compound([
|
||||
("type", s("minecraft:text")),
|
||||
("key", s("password")),
|
||||
("label", s("Password")),
|
||||
])]),
|
||||
),
|
||||
(
|
||||
"actions",
|
||||
Tag::List(vec![
|
||||
Tag::compound([
|
||||
("label", s("Register")),
|
||||
(
|
||||
"action",
|
||||
Tag::compound([
|
||||
("type", s("minecraft:dynamic/custom")),
|
||||
("id", s("authme:prejoin-register/submit")),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
Tag::compound([
|
||||
("label", s("Cancel")),
|
||||
(
|
||||
"action",
|
||||
Tag::compound([
|
||||
("type", s("minecraft:dynamic/run_command")),
|
||||
("template", s("say $(password) $(missing)!")),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_a_multi_action_dialog_with_defaults() {
|
||||
let d = Dialog::parse(®ister()).unwrap();
|
||||
assert_eq!(d.title.plain(), "Register");
|
||||
assert!(!d.can_close_with_escape);
|
||||
assert!(d.pause);
|
||||
assert_eq!(d.after_action, AfterAction::WaitForResponse);
|
||||
assert!(matches!(&d.body[..], [Body::Message { width: 200, .. }]));
|
||||
let Kind::MultiAction {
|
||||
actions,
|
||||
exit,
|
||||
columns,
|
||||
} = &d.kind
|
||||
else {
|
||||
panic!("{:?}", d.kind)
|
||||
};
|
||||
assert_eq!((actions.len(), exit.is_none(), *columns), (2, true, 2));
|
||||
assert_eq!(actions[0].width, 150);
|
||||
assert!(d.on_cancel().is_none());
|
||||
let [
|
||||
Input {
|
||||
key,
|
||||
control:
|
||||
Control::Text {
|
||||
max_length: 32,
|
||||
width: 200,
|
||||
..
|
||||
},
|
||||
},
|
||||
] = &d.inputs[..]
|
||||
else {
|
||||
panic!("{:?}", d.inputs)
|
||||
};
|
||||
assert_eq!(key, "password");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actions_carry_the_input_values() {
|
||||
let d = Dialog::parse(®ister()).unwrap();
|
||||
let values = [InputValue::Text("p\"w".into())];
|
||||
let Kind::MultiAction { actions, .. } = &d.kind else {
|
||||
unreachable!()
|
||||
};
|
||||
let custom = actions[0]
|
||||
.action
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.click(&d.inputs, &values);
|
||||
assert_eq!(
|
||||
custom,
|
||||
Some(Click::Custom {
|
||||
id: "authme:prejoin-register/submit".into(),
|
||||
payload: Some(Tag::compound([("password", s("p\"w"))])),
|
||||
})
|
||||
);
|
||||
// The template escapes the text; a key no input has becomes nothing.
|
||||
let command = actions[1]
|
||||
.action
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.click(&d.inputs, &values);
|
||||
assert_eq!(command, Some(Click::RunCommand("say p\\\"w !".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_notice_without_an_action_has_ok() {
|
||||
let d = Dialog::parse(&Tag::compound([("type", s("notice")), ("title", s("Hi"))])).unwrap();
|
||||
let Kind::Notice(b) = &d.kind else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(b.label, Text::translate("gui.ok", &[]));
|
||||
// Without a title, or with an unknown type, there is no dialog.
|
||||
assert!(Dialog::parse(&Tag::compound([("type", s("notice"))])).is_none());
|
||||
assert!(Dialog::parse(&Tag::compound([("type", s("x")), ("title", s("Hi"))])).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_ranges_snap_to_their_step() {
|
||||
let mut range = Control::NumberRange {
|
||||
width: 200,
|
||||
label: Text::literal("n"),
|
||||
label_format: "options.generic_value".into(),
|
||||
start: 0.0,
|
||||
end: 10.0,
|
||||
initial: Some(4.0),
|
||||
step: Some(3.0),
|
||||
};
|
||||
assert_eq!(range.initial(), InputValue::Slider(0.4));
|
||||
assert_eq!(range.scaled(&InputValue::Slider(0.62)), Some(7.0));
|
||||
assert_eq!(range.scaled(&InputValue::Slider(1.0)), Some(10.0));
|
||||
let Control::NumberRange { step, .. } = &mut range else {
|
||||
unreachable!()
|
||||
};
|
||||
*step = Some(4.0);
|
||||
// 12 is out of range: one step less.
|
||||
assert_eq!(range.scaled(&InputValue::Slider(1.0)), Some(8.0));
|
||||
assert_eq!(range.substitution(&InputValue::Slider(0.0)), "0");
|
||||
assert_eq!(number_string(2.5), "2.5");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
//! `DialogScreen` and its kinds (`SimpleDialogScreen`, `MultiButtonDialogScreen`):
|
||||
//! where a server dialog's title, body, inputs and buttons go in a
|
||||
//! `HeaderAndFooterLayout` (a 33 high header, the body in a `ScrollableLayout`,
|
||||
//! the footer), and the `WaitingForResponseScreen` an answer can leave open.
|
||||
use crate::{
|
||||
dialog::{Body, Control, Dialog, Kind},
|
||||
font::Font,
|
||||
text::Text,
|
||||
};
|
||||
|
||||
/// `HeaderAndFooterLayout.DEFAULT_HEADER_AND_FOOTER_HEIGHT`.
|
||||
const BAR: f32 = 33.0;
|
||||
/// `Checkbox.getBoxSize`.
|
||||
pub const BOX: f32 = 17.0;
|
||||
/// `DialogScreen.WARNING_BUTTON_SPRITES`: normal, disabled, highlighted.
|
||||
pub const WARNING_SPRITES: [&str; 3] = [
|
||||
"gui/sprites/dialog/warning_button",
|
||||
"gui/sprites/dialog/warning_button_disabled",
|
||||
"gui/sprites/dialog/warning_button_highlighted",
|
||||
];
|
||||
|
||||
/// One drawn piece; `y` is from the top of the body (before it scrolls) for
|
||||
/// the body's parts, from the top of the screen for the footer's.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Part {
|
||||
/// A line of text and where it starts.
|
||||
Line(Text, f32, f32),
|
||||
/// A text input's box.
|
||||
Field { input: usize, rect: [f32; 4] },
|
||||
/// A boolean input: the box, its label right of it.
|
||||
Check { input: usize, rect: [f32; 4] },
|
||||
/// A button of `Dialog::buttons`.
|
||||
Button { index: usize, rect: [f32; 4] },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Layout {
|
||||
/// The title and where it is drawn.
|
||||
pub title: (f32, f32),
|
||||
pub warning: [f32; 4],
|
||||
/// The body's visible area (`ScrollableLayout`'s container): x, y, w, h.
|
||||
pub area: [f32; 4],
|
||||
/// The body's full height: more than the area's scrolls.
|
||||
pub content: f32,
|
||||
pub body: Vec<Part>,
|
||||
pub footer: Vec<Part>,
|
||||
}
|
||||
|
||||
/// A laid-out element of a `LinearLayout` before it is placed.
|
||||
struct Element {
|
||||
w: f32,
|
||||
h: f32,
|
||||
parts: Vec<Part>,
|
||||
}
|
||||
impl Element {
|
||||
/// Its parts moved to `(x, y)`.
|
||||
fn at(self, x: f32, y: f32) -> impl Iterator<Item = Part> {
|
||||
self.parts.into_iter().map(move |p| match p {
|
||||
Part::Line(t, px, py) => Part::Line(t, px + x, py + y),
|
||||
Part::Field { input, rect } => Part::Field {
|
||||
input,
|
||||
rect: shift(rect, x, y),
|
||||
},
|
||||
Part::Check { input, rect } => Part::Check {
|
||||
input,
|
||||
rect: shift(rect, x, y),
|
||||
},
|
||||
Part::Button { index, rect } => Part::Button {
|
||||
index,
|
||||
rect: shift(rect, x, y),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
fn shift([x, y, w, h]: [f32; 4], dx: f32, dy: f32) -> [f32; 4] {
|
||||
[x + dx, y + dy, w, h]
|
||||
}
|
||||
/// `FrameLayout.alignInDimension` at 0.5: the offset that centres `inner`.
|
||||
fn centre(outer: f32, inner: f32) -> f32 {
|
||||
((outer - inner) * 0.5).trunc()
|
||||
}
|
||||
|
||||
/// `FocusableTextWidget` with the body's settings: `width` wide, the text
|
||||
/// wrapped to `width - 8` and centred, 4 of padding all round.
|
||||
fn message(font: &Font, contents: &Text, width: f32) -> Element {
|
||||
let lines = font.split_lines(contents, width - 8.0);
|
||||
let mid = (width / 2.0).trunc();
|
||||
let parts = lines
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (line, _))| {
|
||||
let x = mid - (font.width_text(&line) / 2.0).trunc();
|
||||
Part::Line(line, x, 4.0 + 9.0 * i as f32)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Element {
|
||||
w: width,
|
||||
h: 9.0 * parts.len() as f32 + 8.0,
|
||||
parts,
|
||||
}
|
||||
}
|
||||
|
||||
/// `InputControlHandlers`: the control for input `i`, if Horizon has it.
|
||||
fn input(font: &Font, i: usize, control: &Control) -> Option<Element> {
|
||||
Some(match control {
|
||||
Control::Text {
|
||||
width,
|
||||
label,
|
||||
label_visible,
|
||||
..
|
||||
} => {
|
||||
let w = *width as f32;
|
||||
if !label_visible {
|
||||
return Some(Element {
|
||||
w,
|
||||
h: 20.0,
|
||||
parts: vec![Part::Field {
|
||||
input: i,
|
||||
rect: [0.0, 0.0, w, 20.0],
|
||||
}],
|
||||
});
|
||||
}
|
||||
// CommonLayouts.labeledElement: the label, 4 below it the box,
|
||||
// both on the left.
|
||||
Element {
|
||||
w: w.max(font.width_text(label)),
|
||||
h: 9.0 + 4.0 + 20.0,
|
||||
parts: vec![
|
||||
Part::Line(label.clone(), 0.0, 0.0),
|
||||
Part::Field {
|
||||
input: i,
|
||||
rect: [0.0, 13.0, w, 20.0],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
Control::Boolean { label, .. } => {
|
||||
let w = BOX + 4.0 + font.width_text(label);
|
||||
Element {
|
||||
w,
|
||||
h: BOX,
|
||||
parts: vec![Part::Check {
|
||||
input: i,
|
||||
rect: [0.0, 0.0, w, BOX],
|
||||
}],
|
||||
}
|
||||
}
|
||||
Control::SingleOption { .. } | Control::NumberRange { .. } => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `DialogScreen.packControlsIntoColumns`: full rows in a grid 2 apart, what
|
||||
/// is left in a centred row under them.
|
||||
fn columns(widths: &[f32], columns: usize, first: usize) -> Element {
|
||||
let columns = columns.max(1);
|
||||
let full = widths.len() / columns * columns;
|
||||
let row_width = |ws: &[f32]| ws.iter().sum::<f32>() + 2.0 * (ws.len().max(1) - 1) as f32;
|
||||
let mut col = vec![0.0f32; columns];
|
||||
for (i, w) in widths[..full].iter().enumerate() {
|
||||
col[i % columns] = col[i % columns].max(*w);
|
||||
}
|
||||
let last = &widths[full..];
|
||||
if !last.is_empty() {
|
||||
// GridLayout spreads a cell over every column it spans (Divisor).
|
||||
let spread = row_width(last) - 2.0 * (columns - 1) as f32;
|
||||
let (each, extra) = ((spread / columns as f32).floor(), spread % columns as f32);
|
||||
for (c, w) in col.iter_mut().enumerate() {
|
||||
*w = w.max(each + f32::from(u8::from((c as f32) < extra)));
|
||||
}
|
||||
}
|
||||
let x_of = |c: usize| col[..c].iter().sum::<f32>() + 2.0 * c as f32;
|
||||
let mut parts = Vec::new();
|
||||
for (i, w) in widths[..full].iter().enumerate() {
|
||||
let (r, c) = (i / columns, i % columns);
|
||||
parts.push(Part::Button {
|
||||
index: first + i,
|
||||
rect: [x_of(c) + centre(col[c], *w), 22.0 * r as f32, *w, 20.0],
|
||||
});
|
||||
}
|
||||
let width = x_of(columns - 1) + col[columns - 1];
|
||||
if !last.is_empty() {
|
||||
let y = 22.0 * (full / columns) as f32;
|
||||
let mut x = centre(width, row_width(last));
|
||||
for (i, w) in last.iter().enumerate() {
|
||||
parts.push(Part::Button {
|
||||
index: first + full + i,
|
||||
rect: [x, y, *w, 20.0],
|
||||
});
|
||||
x += w + 2.0;
|
||||
}
|
||||
}
|
||||
let rows = full / columns + usize::from(!last.is_empty());
|
||||
Element {
|
||||
w: width,
|
||||
h: (22.0 * rows as f32 - 2.0).max(0.0),
|
||||
parts,
|
||||
}
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// `DialogScreen.init` and `repositionElements` on a `w` by `h` screen.
|
||||
pub fn new(dialog: &Dialog, font: &Font, (w, h): (f32, f32)) -> Self {
|
||||
// The header: the title, 10 right of it the warning button, both
|
||||
// centred together.
|
||||
let tw = font.width_text(&dialog.title);
|
||||
let (hx, hy) = (centre(w, tw + 30.0), centre(BAR, 20.0));
|
||||
let title = (hx, hy + centre(20.0, 9.0));
|
||||
let warning = [hx + tw + 10.0, hy, 20.0, 20.0];
|
||||
|
||||
let mut elements: Vec<Element> = dialog
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| match b {
|
||||
Body::Message { contents, width } => Some(message(font, contents, *width as f32)),
|
||||
Body::Item { .. } => None,
|
||||
})
|
||||
.collect();
|
||||
elements.extend(
|
||||
dialog
|
||||
.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, input_)| input(font, i, &input_.control)),
|
||||
);
|
||||
let buttons = dialog.buttons();
|
||||
let (listed, footer_buttons, footer_h) = match &dialog.kind {
|
||||
Kind::MultiAction {
|
||||
actions,
|
||||
exit,
|
||||
columns: n,
|
||||
} => {
|
||||
let widths: Vec<f32> = actions.iter().map(|b| b.width as f32).collect();
|
||||
elements.push(columns(&widths, *n as usize, 0));
|
||||
// ButtonListDialogScreen: the exit button in the footer, else a 5 high one.
|
||||
let footer = exit.as_ref().map(|_| actions.len()).into_iter().collect();
|
||||
(
|
||||
actions.len(),
|
||||
footer,
|
||||
if exit.is_some() { BAR } else { 5.0 },
|
||||
)
|
||||
}
|
||||
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => {
|
||||
let footer = exit.as_ref().map(|_| 0).into_iter().collect();
|
||||
(0, footer, if exit.is_some() { BAR } else { 5.0 })
|
||||
}
|
||||
// SimpleDialogScreen: the buttons side by side, 8 apart.
|
||||
Kind::Notice(_) | Kind::Confirmation { .. } => {
|
||||
(0, (0..buttons.len()).collect::<Vec<_>>(), BAR)
|
||||
}
|
||||
};
|
||||
debug_assert!(listed + footer_buttons.len() <= buttons.len());
|
||||
|
||||
// The body: a column 10 apart, each element centred in it.
|
||||
let body_w = elements.iter().map(|e| e.w).fold(0.0, f32::max);
|
||||
let content = elements.iter().map(|e| e.h).sum::<f32>()
|
||||
+ 10.0 * elements.len().saturating_sub(1) as f32;
|
||||
// ScrollableLayout: 10 each side for the scrollbar (ReserveStrategy.BOTH),
|
||||
// no higher than what the header and footer leave.
|
||||
let area_w = body_w + 20.0;
|
||||
let area_h = content.min(h - BAR - footer_h).max(0.0);
|
||||
let area_y = (BAR + 30.0).min(h - footer_h - area_h);
|
||||
let area_x = centre(w, area_w);
|
||||
let mut body = Vec::new();
|
||||
let mut y = 0.0;
|
||||
for e in elements {
|
||||
let (x, eh) = (area_x + 10.0 + centre(body_w, e.w), e.h);
|
||||
body.extend(e.at(x, y));
|
||||
y += eh + 10.0;
|
||||
}
|
||||
|
||||
let widths: Vec<f32> = footer_buttons
|
||||
.iter()
|
||||
.map(|&i| buttons[i].width as f32)
|
||||
.collect();
|
||||
let row = widths.iter().sum::<f32>() + 8.0 * widths.len().saturating_sub(1) as f32;
|
||||
let (mut x, fy) = (centre(w, row), h - footer_h + centre(footer_h, 20.0));
|
||||
let mut footer = Vec::new();
|
||||
for (&i, bw) in footer_buttons.iter().zip(&widths) {
|
||||
footer.push(Part::Button {
|
||||
index: i,
|
||||
rect: [x, fy, *bw, 20.0],
|
||||
});
|
||||
x += bw + 8.0;
|
||||
}
|
||||
Self {
|
||||
title,
|
||||
warning: Self::in_bounds(warning, w, h),
|
||||
area: [area_x, area_y, area_w, area_h],
|
||||
content,
|
||||
body,
|
||||
footer,
|
||||
}
|
||||
}
|
||||
/// `makeSureWarningButtonIsInBounds`.
|
||||
fn in_bounds(r: [f32; 4], w: f32, h: f32) -> [f32; 4] {
|
||||
if r[0] < 0.0 || r[1] < 0.0 || r[0] > w - 20.0 || r[1] > h - 20.0 {
|
||||
[(w - 40.0).max(0.0), 5.0f32.min(h), 20.0, 20.0]
|
||||
} else {
|
||||
r
|
||||
}
|
||||
}
|
||||
/// Every part where it is drawn with the body scrolled by `scroll`, and
|
||||
/// whether it is in the body (clipped to its area).
|
||||
pub fn placed(&self, scroll: f32) -> impl Iterator<Item = (Part, bool)> + '_ {
|
||||
let dy = self.area[1] - scroll;
|
||||
let body = self.body.iter().map(move |p| {
|
||||
let p = match p.clone() {
|
||||
Part::Line(t, x, y) => Part::Line(t, x, y + dy),
|
||||
Part::Field { input, rect } => Part::Field {
|
||||
input,
|
||||
rect: shift(rect, 0.0, dy),
|
||||
},
|
||||
Part::Check { input, rect } => Part::Check {
|
||||
input,
|
||||
rect: shift(rect, 0.0, dy),
|
||||
},
|
||||
Part::Button { index, rect } => Part::Button {
|
||||
index,
|
||||
rect: shift(rect, 0.0, dy),
|
||||
},
|
||||
};
|
||||
(p, true)
|
||||
});
|
||||
body.chain(self.footer.iter().map(|p| (p.clone(), false)))
|
||||
}
|
||||
}
|
||||
|
||||
/// `WaitingForResponseScreen`: its Back button's label after `ticks`, and
|
||||
/// whether it shows and works (it shows after a second, works after five).
|
||||
pub fn waiting_button(ticks: u32) -> (Text, bool, bool) {
|
||||
let seconds = (ticks / 20).min(5);
|
||||
let label = match seconds {
|
||||
0 => Text::literal(""),
|
||||
5 => Text::translate("gui.back", &[]),
|
||||
s => Text::translate(
|
||||
"gui.waitingForResponse.button.inactive",
|
||||
&[Text::literal((5 - s).to_string())],
|
||||
),
|
||||
};
|
||||
(label, seconds >= 1, seconds == 5)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn grids_pack_full_rows_and_centre_the_rest() {
|
||||
// AuthMe's two buttons: one row, 2 apart.
|
||||
let two = columns(&[150.0, 150.0], 2, 0);
|
||||
assert_eq!((two.w, two.h), (302.0, 20.0));
|
||||
// Three in two columns: the third alone, centred under them.
|
||||
let three = columns(&[150.0, 150.0, 150.0], 2, 0);
|
||||
assert_eq!((three.w, three.h), (302.0, 42.0));
|
||||
assert_eq!(
|
||||
three.parts[2],
|
||||
Part::Button {
|
||||
index: 2,
|
||||
rect: [76.0, 22.0, 150.0, 20.0]
|
||||
}
|
||||
);
|
||||
// One in two columns spreads over both.
|
||||
let one = columns(&[100.0], 2, 0);
|
||||
assert_eq!(one.w, 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_waiting_screens_button_counts_down() {
|
||||
assert!(!waiting_button(0).1);
|
||||
assert_eq!(
|
||||
waiting_button(20).0,
|
||||
Text::translate(
|
||||
"gui.waitingForResponse.button.inactive",
|
||||
&[Text::literal("4")]
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
waiting_button(100),
|
||||
(Text::translate("gui.back", &[]), true, true)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,20 @@ impl Culler {
|
||||
vertices: &mut Vec<crate::mesher::Vertex>,
|
||||
start: usize,
|
||||
opaque: impl FnMut([i32; 3]) -> bool,
|
||||
) -> bool {
|
||||
let hidden = self.hidden(vertices, start, opaque);
|
||||
if hidden {
|
||||
vertices.truncate(start);
|
||||
}
|
||||
hidden
|
||||
}
|
||||
|
||||
/// Whether this entity's completed camera-relative mesh (`vertices[start..]`) is hidden.
|
||||
pub fn hidden(
|
||||
&self,
|
||||
vertices: &[crate::mesher::Vertex],
|
||||
start: usize,
|
||||
opaque: impl FnMut([i32; 3]) -> bool,
|
||||
) -> bool {
|
||||
if start >= vertices.len() || self.remaining.get() == 0 {
|
||||
return false;
|
||||
@@ -42,11 +56,7 @@ impl Culler {
|
||||
}
|
||||
}
|
||||
// Cover floating-point and rasterization edges as well as the vertices.
|
||||
if self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque) {
|
||||
vertices.truncate(start);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque)
|
||||
}
|
||||
|
||||
/// Returns true only when a complete opaque block plane covers the bounds.
|
||||
|
||||
@@ -38,6 +38,7 @@ mod debug_keys;
|
||||
mod decorated_pot;
|
||||
mod dedicated;
|
||||
mod deflect;
|
||||
mod dialogs;
|
||||
mod discord;
|
||||
mod dispense_fixture;
|
||||
mod dispenser;
|
||||
@@ -1146,6 +1147,7 @@ struct Game<'a> {
|
||||
pending_pack_reload: bool,
|
||||
/// A server's resource packs (game/server_packs.rs).
|
||||
server_packs: server_packs::ServerPackState,
|
||||
dialogs: dialogs::DialogState,
|
||||
world_renderer_ready: bool,
|
||||
collision: &'a BlockCollisionRegistry<'a>,
|
||||
motion: &'a MotionResources,
|
||||
@@ -1214,6 +1216,8 @@ struct Game<'a> {
|
||||
left: bool,
|
||||
right: bool,
|
||||
cursor: (f32, f32),
|
||||
/// The cursor icon the window shows (`widgets::take_cursor` each frame).
|
||||
cursor_icon: horizon_client::widgets::Cursor,
|
||||
captured: bool,
|
||||
focused: bool,
|
||||
/// The keyboard's modifier state (`KeyEvent.modifiers`).
|
||||
@@ -1336,6 +1340,10 @@ struct Game<'a> {
|
||||
hand: Hand,
|
||||
/// The shield's item cooldown after an axe disabled it (ticks).
|
||||
shield_cooldown: u32,
|
||||
/// `Player.getCooldowns()`: the `use_cooldown` component's entries, what
|
||||
/// `itemDecorations` shades a slot by. A server's players have their own
|
||||
/// (`GuestPlay::cooldowns`), swapped in for their turn.
|
||||
cooldowns: horizon_client::cooldowns::Cooldowns,
|
||||
/// The source of a command run through /execute (the player otherwise).
|
||||
command_source: Option<commands::execute::Source>,
|
||||
titles: titles::Titles,
|
||||
@@ -1508,6 +1516,9 @@ struct Game<'a> {
|
||||
/// This frame's view frustum, for culling entities and block entities.
|
||||
view_frustum: Option<horizon_client::gfx::Frustum>,
|
||||
entity_culler: Option<horizon_client::entity_culling::Culler>,
|
||||
/// `Renderer::pack_shadow_casters` for this frame's entities: (keep what the culler hides,
|
||||
/// build the player's model in first person); (false, false) without a shader pack.
|
||||
pack_shadow_casters: (bool, bool),
|
||||
/// A scripted flight from the control socket (`fly`).
|
||||
flight: Option<control::Flight>,
|
||||
/// The running agent action from the control socket (game/agent.rs).
|
||||
@@ -1576,6 +1587,9 @@ struct Game<'a> {
|
||||
chat_capture: Option<Vec<horizon_client::text::Text>>,
|
||||
/// Packets for the guest acting now, sent once its action returns.
|
||||
guest_packets: Vec<horizon_protocol::packets::play::Clientbound>,
|
||||
/// The acting guest's cooldowns, as (item, ticks): their packet needs the
|
||||
/// hub's item registry, which the guest's turn does not hold.
|
||||
guest_cooldowns: Vec<(Arc<str>, i32)>,
|
||||
/// `broadcastToAdmins` lines a guest's command queued, sent once it
|
||||
/// returns: the line, whether operators get it and whether the console
|
||||
/// logs it.
|
||||
@@ -2596,10 +2610,41 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// BigDripleafBlock.entityInside also asks whether the player stands on
|
||||
// the ground and how high its feet are: the leaves its box's feet
|
||||
// layer is inside (the host and the LAN guests).
|
||||
let mut standing = Vec::new();
|
||||
let feet = self
|
||||
.player
|
||||
.iter()
|
||||
.filter(|_| !self.spectator())
|
||||
.map(|p| {
|
||||
(
|
||||
[p.position.x, p.position.y, p.position.z],
|
||||
p.ground.on_ground,
|
||||
f64::from(p.dimensions.width) / 2.0,
|
||||
)
|
||||
})
|
||||
.chain(
|
||||
self.lan_guest_feet()
|
||||
.into_iter()
|
||||
.map(|(at, on_ground)| (at, on_ground, 0.3)),
|
||||
);
|
||||
for (at, on_ground, w) in feet {
|
||||
let y = (at[1] + 1e-7).floor() as i32;
|
||||
for x in (at[0] - w + 1e-7).floor() as i32..=(at[0] + w - 1e-7).floor() as i32 {
|
||||
for z in (at[2] - w + 1e-7).floor() as i32..=(at[2] + w - 1e-7).floor() as i32 {
|
||||
standing.push((BlockPos::new(x, y, z), on_ground, at[1]));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.with_level(|b, level, ticks| {
|
||||
for pos in inside {
|
||||
b.entity_inside(level, ticks, pos);
|
||||
}
|
||||
for (pos, on_ground, feet_y) in standing {
|
||||
b.entity_on_big_dripleaf(level, ticks, pos, on_ground, feet_y);
|
||||
}
|
||||
});
|
||||
self.process_level_events()?;
|
||||
self.tick_scheduled()?;
|
||||
@@ -3421,6 +3466,25 @@ impl Game<'_> {
|
||||
|| self.interact_mob()?
|
||||
|| self.interact_knot())
|
||||
}
|
||||
/// `ItemStack.applyAfterUseComponentSideEffects`: a used stack with a
|
||||
/// `use_cooldown` component starts its entry (`UseCooldown.apply`). A
|
||||
/// server's guest also gets `ClientboundCooldownPacket`
|
||||
/// (`ServerItemCooldowns.onCooldownStarted`), queued for their turn's end.
|
||||
pub(super) fn apply_use_cooldown(&mut self, stack: &ItemStack) {
|
||||
let default = self
|
||||
.res
|
||||
.items()
|
||||
.get(&stack.item)
|
||||
.and_then(|i| i.use_cooldown.clone());
|
||||
let Some(component) = horizon_client::cooldowns::component(stack, default.as_ref()) else {
|
||||
return;
|
||||
};
|
||||
let group = horizon_client::cooldowns::group(stack, default.as_ref());
|
||||
self.cooldowns.add(Arc::clone(&group), component.ticks());
|
||||
if self.lan_acting.is_some() {
|
||||
self.guest_cooldowns.push((group, component.ticks()));
|
||||
}
|
||||
}
|
||||
/// One hand's turn in `startUseItem`: `useItemOn` the block aimed at,
|
||||
/// then `useItem`. Whether the click ends here (it acted or failed).
|
||||
fn use_hand(&mut self, block_hit: Option<&Hit>) -> Result<bool> {
|
||||
@@ -3505,6 +3569,17 @@ impl Game<'_> {
|
||||
let Some(info) = self.res.items().get(&stack.item).cloned() else {
|
||||
return Ok(false);
|
||||
};
|
||||
// ServerPlayerGameMode.useItem and useItemOn: an item on cooldown is
|
||||
// not used (PASS, so the other hand may still act).
|
||||
if self
|
||||
.cooldowns
|
||||
.is_on_cooldown(&horizon_client::cooldowns::group(
|
||||
&stack,
|
||||
info.use_cooldown.as_ref(),
|
||||
))
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) {
|
||||
return Ok(true);
|
||||
}
|
||||
@@ -3831,6 +3906,8 @@ impl Game<'_> {
|
||||
}
|
||||
if ticks >= duration {
|
||||
self.using = None;
|
||||
// ItemStack.finishUsingItem's applyAfterUseComponentSideEffects.
|
||||
self.apply_use_cooldown(&stack);
|
||||
self.finish_consuming(&info, consumable, &stack);
|
||||
} else {
|
||||
self.using = Some((slot, ticks));
|
||||
@@ -4328,6 +4405,7 @@ impl Game<'_> {
|
||||
MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
|
||||
MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
|
||||
MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos),
|
||||
MotionEvent::CauldronExtinguish { pos } => self.cauldron_extinguish(pos),
|
||||
MotionEvent::InsideWitherRose => self.wither_rose_contact(),
|
||||
MotionEvent::SmashLanding {
|
||||
state,
|
||||
@@ -4433,6 +4511,7 @@ impl Game<'_> {
|
||||
// Player.tick's ItemCooldowns.tick for the window's player (a
|
||||
// server's players count theirs down in `tick_guests`).
|
||||
self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
|
||||
self.cooldowns.tick();
|
||||
horizon_client::spans::time("tick_using", || self.tick_using());
|
||||
horizon_client::spans::time("tick_hud", || self.tick_hud());
|
||||
// The player's digging comes in with its packets, before the level
|
||||
@@ -4710,6 +4789,24 @@ impl Game<'_> {
|
||||
}
|
||||
window.set_cursor_visible(!self.captured);
|
||||
}
|
||||
/// `GuiGraphicsExtractor.applyCursor` -> `Window.selectCursor` at the end
|
||||
/// of a frame: the cursor the frame's widgets asked for, set on the window
|
||||
/// only when it changes.
|
||||
fn apply_cursor_icon(&mut self) {
|
||||
use horizon_client::widgets::Cursor;
|
||||
let wanted = horizon_client::widgets::take_cursor();
|
||||
if wanted == self.cursor_icon {
|
||||
return;
|
||||
}
|
||||
if let Some(window) = &self.window {
|
||||
window.set_cursor(match wanted {
|
||||
Cursor::Arrow => winit::window::CursorIcon::Default,
|
||||
Cursor::PointingHand => winit::window::CursorIcon::Pointer,
|
||||
Cursor::NotAllowed => winit::window::CursorIcon::NotAllowed,
|
||||
});
|
||||
}
|
||||
self.cursor_icon = wanted;
|
||||
}
|
||||
/// LevelLoadingScreen.onClose -> Gui.setScreen(null) -> grabMouse.
|
||||
fn capture_loaded_world(&mut self) {
|
||||
// Loading may finish after focus was lost or another screen opened.
|
||||
@@ -4815,17 +4912,17 @@ impl Game<'_> {
|
||||
count_text: Option<String>,
|
||||
) {
|
||||
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
|
||||
// moved to (x, y). Horizon tracks no item cooldowns to shade yet.
|
||||
let max_damage = self
|
||||
.res
|
||||
.items()
|
||||
.get(&stack.item)
|
||||
.map_or(0, |info| info.max_damage as i32);
|
||||
// moved to (x, y): the damage bar, the cooldown shade and the count.
|
||||
let info = self.res.items().get(&stack.item);
|
||||
let max_damage = info.map_or(0, |info| info.max_damage as i32);
|
||||
let cooldown =
|
||||
horizon_client::cooldowns::group(stack, info.and_then(|i| i.use_cooldown.as_ref()));
|
||||
let partial = self.clock.fraction() as f32;
|
||||
let decorations = hud_overlays::ItemDecorations {
|
||||
count: stack.count,
|
||||
count_text,
|
||||
bar: hud_overlays::damage_bar(stack.damage as i32, max_damage),
|
||||
cooldown: 0.0,
|
||||
cooldown: self.cooldowns.percent(&cooldown, partial),
|
||||
};
|
||||
let mut draws = vec![hud_layout::GuiDraw::Push(vec![
|
||||
hud_layout::PoseOp::Translate(x, y),
|
||||
@@ -4842,11 +4939,14 @@ impl Game<'_> {
|
||||
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
|
||||
// The pack prompt replaces the connecting screen (setScreen), but
|
||||
// in game it opens over the world.
|
||||
let mut batch = if self.server_packs.prompt.is_some() && self.player.is_none() {
|
||||
let mut batch = if (self.server_packs.prompt.is_some() || self.dialog_open())
|
||||
&& self.player.is_none()
|
||||
{
|
||||
HudBatch::new(size)
|
||||
} else {
|
||||
self.hud_layers(size)
|
||||
};
|
||||
self.draw_dialog(&mut batch);
|
||||
self.draw_pack_prompt(&mut batch);
|
||||
// Gui.extractRenderState: the debug overlay comes after the screen
|
||||
// and the toasts, so it is over everything, menus included.
|
||||
@@ -5161,6 +5261,7 @@ impl Game<'_> {
|
||||
| BlockEntity::Vault(_)
|
||||
| BlockEntity::Beehive(_)
|
||||
| BlockEntity::CommandBlock(_)
|
||||
| BlockEntity::Skull(_)
|
||||
| BlockEntity::Campfire(_),
|
||||
) => {}
|
||||
None => {
|
||||
@@ -5431,6 +5532,7 @@ impl Game<'_> {
|
||||
| BlockEntity::Vault(_)
|
||||
| BlockEntity::Beehive(_)
|
||||
| BlockEntity::CommandBlock(_)
|
||||
| BlockEntity::Skull(_)
|
||||
| BlockEntity::Campfire(_),
|
||||
) => {}
|
||||
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
|
||||
@@ -6876,8 +6978,10 @@ impl Game<'_> {
|
||||
self.ominous_item_spawner_geometry(camera, alpha, &mut out);
|
||||
// Mobs and their projectiles (a span each).
|
||||
self.mob_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:player");
|
||||
// In first person only a shader pack's shadow pass draws the player.
|
||||
self.mark_player(out.len(), self.camera_type.first_person());
|
||||
self.player_model_geometry(camera, self.clock.camera_fraction(), &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:player");
|
||||
self.guest_model_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:evoker_fangs");
|
||||
self.fangs_geometry(camera, alpha, &mut out);
|
||||
@@ -6951,6 +7055,7 @@ impl Game<'_> {
|
||||
_ => None,
|
||||
},
|
||||
banner: &|p| self.banner_layers_at(p),
|
||||
skull: &|p| self.skull_skin_at(p),
|
||||
glyph: &|c| self.gui.atlas.glyph_cell(c),
|
||||
};
|
||||
// Block entities outside the view frustum are skipped (with a
|
||||
@@ -8477,6 +8582,35 @@ impl Game<'_> {
|
||||
self.level_set(pos, id)?;
|
||||
Ok(true)
|
||||
}
|
||||
/// `LayeredCauldronBlock.handleEntityOnFireInside` for a burning player
|
||||
/// in the cauldron at `pos` (`mayInteract`: not a spectator): the fill
|
||||
/// level drops (`lowerFillLevel`, a `block_change` with no source). A
|
||||
/// server's cauldron is the server's.
|
||||
pub(super) fn cauldron_extinguish(&mut self, pos: BlockPos) {
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let at = [pos.x, pos.y, pos.z];
|
||||
let registry = self.pack.assets.registry;
|
||||
let Some(old) = registry
|
||||
.state(self.world.block(at[0], at[1], at[2]))
|
||||
.filter(|s| {
|
||||
matches!(
|
||||
s.name.as_str(),
|
||||
"minecraft:water_cauldron" | "minecraft:powder_snow_cauldron"
|
||||
)
|
||||
})
|
||||
.cloned()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Ok(new) = registry.resolve(&horizon_client::cauldron::extinguished(&old)) else {
|
||||
return;
|
||||
};
|
||||
if self.level_set(at, new).is_ok() {
|
||||
self.post_block_game_event("minecraft:block_change", at, None, Some(new));
|
||||
}
|
||||
}
|
||||
fn damage_held(&mut self, amount: u32) {
|
||||
if self.creative {
|
||||
return;
|
||||
@@ -9264,6 +9398,9 @@ impl Game<'_> {
|
||||
)
|
||||
}
|
||||
fn apply_settings(&mut self) {
|
||||
// LocalPlayer.refreshChatAbilities: the chat shows what the Chat option allows.
|
||||
let abilities = self.chat_abilities();
|
||||
self.ui.chat.set_abilities(&self.gui.atlas.font, abilities);
|
||||
self.streaming.radius = self.settings.render_distance;
|
||||
// Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves:
|
||||
// LevelExtractor.allChanged when they change.
|
||||
@@ -10447,6 +10584,7 @@ impl Game<'_> {
|
||||
|| (self.title.is_none()
|
||||
&& self.player.is_some()
|
||||
&& (self.screen.blurs_background(self.pause_menu)
|
||||
|| self.dialog_open()
|
||||
|| (self.screen == Screen::Win && self.win_screen_pauses())));
|
||||
let radius = self.settings.menu_blur as f32;
|
||||
(blurred && radius >= 1.0).then_some(radius)
|
||||
@@ -11149,7 +11287,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
}) * wheel_sensitivity
|
||||
};
|
||||
let d = scaled(raw_y) as f32;
|
||||
if let Some(title) = &mut self.title
|
||||
if self.dialog_open() {
|
||||
self.dialog_scroll(d);
|
||||
} else if let Some(title) = &mut self.title
|
||||
&& self.screen != Screen::Win
|
||||
{
|
||||
let size = self
|
||||
@@ -11219,6 +11359,11 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.pack_prompt_click()?;
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } if self.dialog_open() => {
|
||||
if state == ElementState::Pressed && button == MouseButton::Left {
|
||||
self.dialog_click()?;
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { .. } if self.screen == Screen::Win => {}
|
||||
WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => {
|
||||
if self.options_waiting_for_key() && state == ElementState::Pressed {
|
||||
@@ -11433,6 +11578,14 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.answer_pack_prompt(false)?;
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } if self.dialog_open() => {
|
||||
let shortcut = self.edit_shortcut(&event);
|
||||
if event.state == ElementState::Pressed
|
||||
&& let PhysicalKey::Code(key) = event.physical_key
|
||||
{
|
||||
self.dialog_key(key, shortcut, event.text.as_deref())?
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if self.screen == Screen::Chat && self.title.is_none() =>
|
||||
{
|
||||
@@ -11661,6 +11814,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.advance_flight();
|
||||
let ticked = Instant::now();
|
||||
let rendered = self.render()?;
|
||||
self.apply_cursor_icon();
|
||||
if let Some(threshold) = self.options.spikes
|
||||
&& let Some(r) = self.renderer.as_ref()
|
||||
{
|
||||
@@ -11914,6 +12068,7 @@ impl<'a> Game<'a> {
|
||||
world_loader: None,
|
||||
pending_pack_reload: false,
|
||||
server_packs: Default::default(),
|
||||
dialogs: Default::default(),
|
||||
world_renderer_ready: false,
|
||||
collision: res.collision(),
|
||||
motion: res.motion(),
|
||||
@@ -11968,6 +12123,7 @@ impl<'a> Game<'a> {
|
||||
left: false,
|
||||
right: false,
|
||||
cursor: (0.0, 0.0),
|
||||
cursor_icon: horizon_client::widgets::Cursor::Arrow,
|
||||
captured: false,
|
||||
focused: true,
|
||||
modifiers: winit::keyboard::ModifiersState::empty(),
|
||||
@@ -12045,6 +12201,7 @@ impl<'a> Game<'a> {
|
||||
offhand: None,
|
||||
hand: Hand::Main,
|
||||
shield_cooldown: 0,
|
||||
cooldowns: Default::default(),
|
||||
command_source: None,
|
||||
titles: Default::default(),
|
||||
tool_highlight: Default::default(),
|
||||
@@ -12160,6 +12317,7 @@ impl<'a> Game<'a> {
|
||||
agent: agent::Agent::default(),
|
||||
view_frustum: None,
|
||||
entity_culler: None,
|
||||
pack_shadow_casters: (false, false),
|
||||
pending_uploads: Vec::new(),
|
||||
frame_graph: Default::default(),
|
||||
extras: Default::default(),
|
||||
@@ -12194,6 +12352,7 @@ impl<'a> Game<'a> {
|
||||
lid_openers: HashMap::new(),
|
||||
lan_acting: None,
|
||||
guest_packets: Vec::new(),
|
||||
guest_cooldowns: Vec::new(),
|
||||
lan_acting_name: None,
|
||||
lan_acting_uuid: None,
|
||||
chat_capture: None,
|
||||
|
||||
@@ -390,6 +390,9 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn screen_label(&self) -> &'static str {
|
||||
if self.dialog_open() {
|
||||
return "dialog";
|
||||
}
|
||||
if self.title.is_some() {
|
||||
return "title";
|
||||
}
|
||||
@@ -485,6 +488,7 @@ impl Game<'_> {
|
||||
})
|
||||
});
|
||||
json!({
|
||||
"dialog": self.dialog_status(),
|
||||
"screen": self.screen_label(),
|
||||
"menu": self.title.as_ref().map(|_| self.title_value()),
|
||||
"world": (self.title.is_none()).then(|| match &self.integrated {
|
||||
@@ -682,6 +686,18 @@ 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 title a server gave the menu, span by span as it is drawn.
|
||||
if let Some(title) = self.remote_menu_title() {
|
||||
let spans = title.spans.iter().map(|s| {
|
||||
json!({
|
||||
"text": s.text,
|
||||
"color": s.style.color.map(|c| format!("#{c:06X}")),
|
||||
"bold": s.style.is_bold(),
|
||||
"italic": s.style.is_italic(),
|
||||
})
|
||||
});
|
||||
v["title"] = json!(spans.collect::<Vec<_>>());
|
||||
}
|
||||
// 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();
|
||||
|
||||
@@ -8,8 +8,10 @@ use horizon_client::{
|
||||
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
|
||||
block_entity_render::BlockAnim,
|
||||
collisions::{SceneCollisions, no_collision_empty},
|
||||
containers::BlockEntity,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
save::number,
|
||||
skins,
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
use horizon_world::nbt::Tag;
|
||||
@@ -392,4 +394,25 @@ impl Game<'_> {
|
||||
pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 {
|
||||
self.be_anims.lid(pos, partial)
|
||||
}
|
||||
/// `SkullBlockRenderer.getPlayerSkin`: the skin sprite of the profile of
|
||||
/// the player head at `pos`. The skin download is started here; while it
|
||||
/// is in flight (or when it cannot be got) the profile's default skin
|
||||
/// stands in. A head with no profile answers None: `SKIN_BY_TYPE`.
|
||||
pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<&str> {
|
||||
let Some(BlockEntity::Skull(skull)) =
|
||||
self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let skin = skull.skin.as_ref()?;
|
||||
if let Some((url, location)) = &skin.download {
|
||||
self.skin_downloads
|
||||
.borrow_mut()
|
||||
.state(skins::Kind::Skin, url);
|
||||
if self.gui.atlas.sprites.contains_key(location) {
|
||||
return Some(location);
|
||||
}
|
||||
}
|
||||
Some(skin.fallback)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
//! (game rules, the world clock, difficulty), bound to the game.
|
||||
use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR},
|
||||
chat::{
|
||||
Chat, ChatAbilities, ChatAction, ChatScreen, ChatSource, ChatVisibility, Commands,
|
||||
SYSTEM_INDICATOR,
|
||||
},
|
||||
command::Registries,
|
||||
gamerules::GameRules,
|
||||
hud::HudBatch,
|
||||
@@ -425,6 +428,7 @@ impl Game<'_> {
|
||||
self.ui.chat.recent.len(),
|
||||
b.width as i32,
|
||||
b.height as i32,
|
||||
self.chat_abilities(),
|
||||
);
|
||||
screen.auto_suggestions = self.settings.auto_suggestions;
|
||||
self.ui.chat_screen = Some(screen);
|
||||
@@ -443,6 +447,10 @@ impl Game<'_> {
|
||||
self.capture(true);
|
||||
}
|
||||
}
|
||||
/// `Minecraft.computeChatAbilities` from the Chat option.
|
||||
pub(super) fn chat_abilities(&self) -> ChatAbilities {
|
||||
ChatAbilities::new(ChatVisibility::from_option(self.settings.chat_visibility))
|
||||
}
|
||||
/// A chat message from the game (ChatComponent.addServerSystemMessage).
|
||||
pub(super) fn system_message(&mut self, text: Text) {
|
||||
if let Some(capture) = self.chat_capture.as_mut() {
|
||||
@@ -452,7 +460,11 @@ impl Game<'_> {
|
||||
// Connected to a server (single player's own included), the chat on
|
||||
// screen is the connection's: the game's own messages join it.
|
||||
if self.remote.is_some() {
|
||||
self.chat_line(text);
|
||||
self.chat_line(text, ChatSource::Server);
|
||||
return;
|
||||
}
|
||||
// The Chat option's Hidden level takes the server's messages too.
|
||||
if !self.ui.chat.shows(ChatSource::Server) {
|
||||
return;
|
||||
}
|
||||
let focused = self.screen == Screen::Chat;
|
||||
@@ -461,6 +473,7 @@ impl Game<'_> {
|
||||
&self.gui.atlas,
|
||||
text,
|
||||
Some(SYSTEM_INDICATOR),
|
||||
ChatSource::Server,
|
||||
self.ticks,
|
||||
focused,
|
||||
);
|
||||
@@ -570,7 +583,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// ChatScreen.handleChatInput: history, then a command or a chat line.
|
||||
/// The Chat option's restrictions stop the message here too, so a
|
||||
/// control-socket `chat` cannot send what the player's setting hides.
|
||||
pub(super) fn handle_chat_input(&mut self, message: &str) {
|
||||
if !self.chat_abilities().allows(message) {
|
||||
return;
|
||||
}
|
||||
self.ui.chat.add_recent(message);
|
||||
// On a server (single player's own included) the server runs it,
|
||||
// unless a client mod owns the command.
|
||||
@@ -592,9 +610,14 @@ impl Game<'_> {
|
||||
);
|
||||
let focused = self.screen == Screen::Chat;
|
||||
let heard = self.mods.running().then(|| line.plain());
|
||||
self.ui
|
||||
.chat
|
||||
.add(&self.gui.atlas, line, None, self.ticks, focused);
|
||||
self.ui.chat.add(
|
||||
&self.gui.atlas,
|
||||
line,
|
||||
None,
|
||||
ChatSource::Player,
|
||||
self.ticks,
|
||||
focused,
|
||||
);
|
||||
if let Some(line) = heard {
|
||||
self.mods_chat(&line);
|
||||
}
|
||||
@@ -898,9 +921,14 @@ impl Game<'_> {
|
||||
Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]),
|
||||
};
|
||||
let focused = self.screen == Screen::Chat;
|
||||
self.ui
|
||||
.chat
|
||||
.add(&self.gui.atlas, message, None, self.ticks, focused);
|
||||
self.ui.chat.add(
|
||||
&self.gui.atlas,
|
||||
message,
|
||||
None,
|
||||
ChatSource::Client,
|
||||
self.ticks,
|
||||
focused,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time
|
||||
|
||||
@@ -2841,9 +2841,14 @@ impl Game<'_> {
|
||||
capture.push(line.clone());
|
||||
}
|
||||
let focused = self.screen == Screen::Chat;
|
||||
self.ui
|
||||
.chat
|
||||
.add(&self.gui.atlas, line, None, self.ticks, focused);
|
||||
self.ui.chat.add(
|
||||
&self.gui.atlas,
|
||||
line,
|
||||
None,
|
||||
horizon_client::chat::ChatSource::Player,
|
||||
self.ticks,
|
||||
focused,
|
||||
);
|
||||
Ok(1)
|
||||
}
|
||||
/// MessageArgument: `@p`-style selectors in a message become names.
|
||||
|
||||
@@ -241,6 +241,13 @@ impl Game<'_> {
|
||||
"pad" => Ok(Some(self.pad_command(&words)?)),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
// A server's dialog takes the keys, in configuration too.
|
||||
if self.dialog_open() {
|
||||
if arg(2)? != "up" {
|
||||
self.dialog_key(key, None, None)?;
|
||||
}
|
||||
return ok();
|
||||
}
|
||||
self.require_world()?;
|
||||
// The sign editor takes raw presses (Enter, arrows, Backspace, Escape).
|
||||
if self.sign_edit.is_some() {
|
||||
@@ -538,13 +545,17 @@ impl Game<'_> {
|
||||
))
|
||||
}
|
||||
"type" => {
|
||||
self.require_world()?;
|
||||
let text = line
|
||||
.trim_start()
|
||||
.strip_prefix("type")
|
||||
.unwrap_or("")
|
||||
.strip_prefix(' ')
|
||||
.unwrap_or("");
|
||||
// A server's dialog, in configuration too.
|
||||
if self.dialog_type(text) {
|
||||
return ok();
|
||||
}
|
||||
self.require_world()?;
|
||||
if self.book.is_some() {
|
||||
self.book_type(text);
|
||||
return ok();
|
||||
|
||||
@@ -43,10 +43,6 @@ fn arrow_damage(arrow: &mut Projectile, fallback: &mut impl RandomSource) -> f32
|
||||
#[derive(Default)]
|
||||
pub(super) struct Creatures {
|
||||
pub projectiles: Vec<Projectile>,
|
||||
/// Player status effects applied by mobs: (effect, ticks left, amplifier).
|
||||
pub pearl_cooldown: u32,
|
||||
/// The wind charge's use cooldown (ticks).
|
||||
pub wind_cooldown: u32,
|
||||
/// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs).
|
||||
pub wind_bursts: Vec<super::wind::Burst>,
|
||||
/// Ticks left of the elder guardian's apparition (MobAppearanceParticle).
|
||||
@@ -642,7 +638,6 @@ impl Game<'_> {
|
||||
self.tick_allays();
|
||||
self.tick_breeze_effects();
|
||||
self.tick_sniffer_effects();
|
||||
self.tick_player_effects();
|
||||
self.piglin_pickups();
|
||||
self.sulfur_cube_pickups();
|
||||
// Hurt and death sounds of damage dealt outside the mob ticks.
|
||||
@@ -1572,13 +1567,6 @@ impl Game<'_> {
|
||||
}
|
||||
self.give_player_effect("minecraft:wither", 40, 0);
|
||||
}
|
||||
/// Burning applied to the player by mobs.
|
||||
fn tick_player_effects(&mut self) {
|
||||
self.creatures.wind_cooldown = self.creatures.wind_cooldown.saturating_sub(1);
|
||||
if self.creatures.pearl_cooldown > 0 {
|
||||
self.creatures.pearl_cooldown -= 1;
|
||||
}
|
||||
}
|
||||
pub(super) fn hurt_player_by(&mut self, damage_type: &str, amount: f32) {
|
||||
if self.creative {
|
||||
return;
|
||||
@@ -2879,14 +2867,14 @@ impl Game<'_> {
|
||||
let kind = match item {
|
||||
"minecraft:snowball" => ProjectileKind::Snowball,
|
||||
"minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => ProjectileKind::Egg,
|
||||
"minecraft:ender_pearl" => {
|
||||
if self.creatures.pearl_cooldown > 0 {
|
||||
return Ok(true);
|
||||
"minecraft:ender_pearl" => ProjectileKind::EnderPearl,
|
||||
"minecraft:wind_charge" => {
|
||||
let thrown = self.throw_wind_charge()?;
|
||||
if thrown {
|
||||
self.apply_use_cooldown(stack);
|
||||
}
|
||||
self.creatures.pearl_cooldown = 20;
|
||||
ProjectileKind::EnderPearl
|
||||
return Ok(thrown);
|
||||
}
|
||||
"minecraft:wind_charge" => return self.throw_wind_charge(),
|
||||
_ if item.ends_with("_spawn_egg") => return self.use_spawn_egg(stack),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
@@ -2911,6 +2899,9 @@ impl Game<'_> {
|
||||
);
|
||||
self.creatures.projectiles.push(proj);
|
||||
self.player_projectile_shot();
|
||||
// ItemStack.use's applyAfterUseComponentSideEffects: the pearl's
|
||||
// second is the `use_cooldown` component, as for any thrown item.
|
||||
self.apply_use_cooldown(stack);
|
||||
let sound = match kind {
|
||||
ProjectileKind::Snowball => "minecraft:entity.snowball.throw",
|
||||
ProjectileKind::Egg => "minecraft:entity.egg.throw",
|
||||
|
||||
@@ -0,0 +1,611 @@
|
||||
//! A server's dialogs bound to the game (`ClientCommonPacketListenerImpl.
|
||||
//! showDialog` and `clearDialog`, `DialogScreen`, its `WarningScreen` and the
|
||||
//! `WaitingForResponseScreen`): the screen over whatever is open (the
|
||||
//! connecting screen in configuration), its inputs, and the actions its
|
||||
//! buttons send back.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
clipboard::EditShortcut,
|
||||
confirm_screen::Confirm,
|
||||
dialog::{AfterAction, Click, Control, Dialog, InputValue},
|
||||
dialog_screen::{BOX, Layout, Part, WARNING_SPRITES, waiting_button},
|
||||
hud::{HudBatch, rgba},
|
||||
text::Text,
|
||||
ui,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::time::Instant;
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
/// An open `DialogScreen`.
|
||||
struct Open {
|
||||
dialog: Dialog,
|
||||
values: Vec<InputValue>,
|
||||
/// The box of each text input.
|
||||
fields: Vec<Option<ui::EditBox>>,
|
||||
focus: Option<usize>,
|
||||
scroll: ui::Scroll,
|
||||
}
|
||||
|
||||
/// The dialog screens a server can open.
|
||||
#[derive(Default)]
|
||||
pub(super) struct DialogState {
|
||||
open: Option<Open>,
|
||||
/// `WaitingForResponseScreen`, since when.
|
||||
waiting: Option<Instant>,
|
||||
/// `DialogScreen.WarningScreen`, over the dialog.
|
||||
warning: bool,
|
||||
}
|
||||
|
||||
fn warning_texts() -> (Text, Text, [Text; 2]) {
|
||||
let t = |key: &str| Text::translate(key, &[]);
|
||||
(
|
||||
t("menu.custom_screen_info.title"),
|
||||
t("menu.custom_screen_info.contents"),
|
||||
[t("menu.disconnect"), t("gui.back")],
|
||||
)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Whether a dialog screen takes the input.
|
||||
pub(super) fn dialog_open(&self) -> bool {
|
||||
let d = &self.dialogs;
|
||||
d.open.is_some() || d.waiting.is_some() || d.warning
|
||||
}
|
||||
|
||||
/// `showDialog`: the dialog replaces an open one (and a waiting screen);
|
||||
/// under the warning screen, it is what Back returns to.
|
||||
pub(super) fn show_dialog(&mut self, tag: &Tag) {
|
||||
let Some(dialog) = Dialog::parse(tag) else {
|
||||
log::warn!("Horizon: failed to show dialog for data {tag:?}");
|
||||
return;
|
||||
};
|
||||
let values = dialog.inputs.iter().map(|i| i.control.initial()).collect();
|
||||
let fields = dialog
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|i| match &i.control {
|
||||
Control::Text {
|
||||
width,
|
||||
initial,
|
||||
max_length,
|
||||
..
|
||||
} => {
|
||||
let mut edit = ui::EditBox::new(0.0, 0.0, *width as f32, 20.0);
|
||||
edit.max_length = (*max_length).max(1) as usize;
|
||||
edit.set_value(initial);
|
||||
edit.focused = false;
|
||||
Some(edit)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
self.dialogs.open = Some(Open {
|
||||
dialog,
|
||||
values,
|
||||
fields,
|
||||
focus: None,
|
||||
scroll: ui::Scroll::default(),
|
||||
});
|
||||
self.dialogs.waiting = None;
|
||||
self.capture(false);
|
||||
}
|
||||
|
||||
/// `clearDialog`: the dialog closes (under the warning screen, Back then
|
||||
/// returns to what was open before it).
|
||||
pub(super) fn clear_dialog(&mut self) {
|
||||
if self.dialogs.open.take().is_some() && !self.dialog_open() {
|
||||
self.dialog_closed();
|
||||
}
|
||||
}
|
||||
|
||||
/// Every dialog screen goes (a disconnect, or the level loading screen).
|
||||
pub(super) fn close_dialogs(&mut self) {
|
||||
self.dialogs = DialogState::default();
|
||||
}
|
||||
|
||||
fn dialog_closed(&mut self) {
|
||||
if self.player.is_some() && self.screen == super::Screen::Playing && self.title.is_none() {
|
||||
self.capture(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The input values as the controls hold them now.
|
||||
fn dialog_values(open: &mut Open) {
|
||||
for (value, field) in open.values.iter_mut().zip(&open.fields) {
|
||||
if let Some(f) = field {
|
||||
*value = InputValue::Text(f.value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `DialogScreen.runAction`: the click event, then the screen the dialog's
|
||||
/// `after_action` leaves.
|
||||
fn run_dialog_action(&mut self, click: Option<Click>, after: AfterAction) -> Result<()> {
|
||||
match after {
|
||||
AfterAction::None => {}
|
||||
AfterAction::Close => self.dialogs.open = None,
|
||||
AfterAction::WaitForResponse => {
|
||||
self.dialogs.open = None;
|
||||
self.dialogs.waiting = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
match click {
|
||||
Some(Click::Custom { id, payload }) => {
|
||||
if let Some(r) = &self.remote {
|
||||
r.session.send_custom_click(&id, payload);
|
||||
}
|
||||
}
|
||||
Some(Click::RunCommand(command)) => {
|
||||
// In configuration there is nothing to run it (vanilla warns).
|
||||
if self.player.is_some() {
|
||||
let command = command.strip_prefix('/').unwrap_or(&command);
|
||||
self.send_chat(&format!("/{command}"));
|
||||
} else {
|
||||
log::warn!(
|
||||
"Horizon: commands are not supported in configuration, trying to run '{command}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
Some(Click::ShowDialog(dialog)) => self.show_dialog_ref(&dialog),
|
||||
Some(Click::CopyToClipboard(value)) => {
|
||||
use horizon_client::clipboard::Clipboard;
|
||||
self.clipboard.set(&value);
|
||||
}
|
||||
Some(other) => log::info!("Horizon: dialog action {other:?} is not supported yet"),
|
||||
None => {}
|
||||
}
|
||||
if !self.dialog_open() {
|
||||
self.dialog_closed();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A `show_dialog` click event's dialog: a registry id or the dialog itself.
|
||||
fn show_dialog_ref(&mut self, dialog: &Tag) {
|
||||
match dialog {
|
||||
Tag::String(id) => {
|
||||
let id = id.to_string_lossy();
|
||||
let name = if id.contains(':') {
|
||||
id.clone()
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
};
|
||||
let found = self.remote.as_ref().and_then(|r| {
|
||||
let entries = r.registries.registries.get("minecraft:dialog")?;
|
||||
entries.iter().find(|(n, _)| *n == name)?.1.clone()
|
||||
});
|
||||
match found {
|
||||
Some(tag) => self.show_dialog(&tag),
|
||||
None => log::warn!("Horizon: unknown dialog {id}"),
|
||||
}
|
||||
}
|
||||
tag => self.show_dialog(tag),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ClientboundShowDialogPacket` in play: a registry entry or the dialog.
|
||||
pub(super) fn show_play_dialog(
|
||||
&mut self,
|
||||
dialog: &horizon_protocol::packets::play::DialogHolder,
|
||||
) {
|
||||
use horizon_protocol::packets::play::DialogHolder;
|
||||
match dialog {
|
||||
DialogHolder::Direct(tag) => self.show_dialog(tag),
|
||||
DialogHolder::Registry(id) => {
|
||||
let tag = self
|
||||
.remote
|
||||
.as_ref()
|
||||
.and_then(|r| r.registries.data("minecraft:dialog", *id).cloned());
|
||||
match tag {
|
||||
Some(tag) => self.show_dialog(&tag),
|
||||
None => log::warn!("Horizon: unknown dialog {id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dialog_layout(&self) -> Option<Layout> {
|
||||
let open = self.dialogs.open.as_ref()?;
|
||||
Some(Layout::new(
|
||||
&open.dialog,
|
||||
&self.gui.atlas.font,
|
||||
self.gui_size(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn draw_dialog(&mut self, batch: &mut HudBatch) {
|
||||
if !self.dialog_open() {
|
||||
return;
|
||||
}
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let cursor = self.cursor;
|
||||
let atlas = &self.gui.atlas;
|
||||
if self.player.is_none() {
|
||||
// In place of the connecting screen, on its background.
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255));
|
||||
}
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.player.is_some());
|
||||
if self.dialogs.warning {
|
||||
let (title, message, [disconnect, back]) = warning_texts();
|
||||
Confirm::new(&atlas.font, (w, h), &title, &message).draw(
|
||||
batch,
|
||||
atlas,
|
||||
cursor,
|
||||
[&disconnect, &back],
|
||||
);
|
||||
return;
|
||||
}
|
||||
if let Some(since) = self.dialogs.waiting {
|
||||
// HeaderAndFooterLayout(33, 0) centred: the title, the button 33 below.
|
||||
let ticks = (since.elapsed().as_millis() / 50) as u32;
|
||||
let (label, visible, active) = waiting_button(ticks);
|
||||
let title = Text::translate("gui.waitingForResponse.title", &[]);
|
||||
let top = ((h - 53.0) / 2.0).trunc();
|
||||
let tw = atlas.font.width_text(&title);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&title,
|
||||
((w - tw) / 2.0).trunc(),
|
||||
top + 12.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
if visible {
|
||||
let (bx, by) = (((w - 200.0) / 2.0).trunc(), top + 33.0);
|
||||
let hover = ui::hovered(cursor, bx, by, 200.0, 20.0);
|
||||
ui::button(batch, atlas, bx, by, 200.0, 20.0, &label, active, hover);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(layout) = self.dialog_layout() else {
|
||||
return;
|
||||
};
|
||||
let Some(open) = self.dialogs.open.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.gui.atlas;
|
||||
let [ax, ay, aw, ah] = layout.area;
|
||||
open.scroll.clamp(ay, ay + ah, layout.content);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&open.dialog.title,
|
||||
layout.title.0,
|
||||
layout.title.1,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
let [wx, wy, ww, wh] = layout.warning;
|
||||
let warn_hover = ui::hovered(cursor, wx, wy, ww, wh);
|
||||
horizon_client::widgets::record("warning", layout.warning, true);
|
||||
batch.sprite_scaled(
|
||||
atlas,
|
||||
WARNING_SPRITES[if warn_hover { 2 } else { 0 }],
|
||||
wx,
|
||||
wy,
|
||||
ww,
|
||||
wh,
|
||||
u32::MAX,
|
||||
);
|
||||
let buttons = open.dialog.buttons();
|
||||
let in_area = |y: f32| y >= ay && y < ay + ah;
|
||||
let mut tooltip = None;
|
||||
let mut start = None;
|
||||
for (part, clipped) in layout.placed(open.scroll.amount) {
|
||||
if clipped && start.is_none() {
|
||||
start = Some(batch.vertices.len());
|
||||
} else if !clipped && let Some(s) = start.take() {
|
||||
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
|
||||
}
|
||||
match part {
|
||||
Part::Line(text, x, y) => {
|
||||
batch.text_styled(atlas, &text, x, y, u32::MAX, true);
|
||||
}
|
||||
Part::Field { input, rect } => {
|
||||
if let Some(Some(edit)) = open.fields.get_mut(input) {
|
||||
[edit.x, edit.y, edit.width, edit.height] = rect;
|
||||
edit.focused = open.focus == Some(input);
|
||||
edit.draw(batch, atlas, None);
|
||||
}
|
||||
}
|
||||
Part::Check { input, rect } => {
|
||||
let [x, y, cw, ch] = rect;
|
||||
let hover = in_area(cursor.1) && ui::hovered(cursor, x, y, cw, ch);
|
||||
let on = open.values.get(input) == Some(&InputValue::Bool(true));
|
||||
let sprite = match (on, hover) {
|
||||
(true, true) => "gui/sprites/widget/checkbox_selected_highlighted",
|
||||
(true, false) => "gui/sprites/widget/checkbox_selected",
|
||||
(false, true) => "gui/sprites/widget/checkbox_highlighted",
|
||||
(false, false) => "gui/sprites/widget/checkbox",
|
||||
};
|
||||
let Control::Boolean { label, .. } = &open.dialog.inputs[input].control else {
|
||||
continue;
|
||||
};
|
||||
horizon_client::widgets::record(&label.plain(), rect, true);
|
||||
batch.sprite_scaled(atlas, sprite, x, y, BOX, BOX, u32::MAX);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
label,
|
||||
x + BOX + 4.0,
|
||||
y + 4.0,
|
||||
rgba(224, 224, 224, 255),
|
||||
true,
|
||||
);
|
||||
}
|
||||
Part::Button { index, rect } => {
|
||||
let [x, y, bw, bh] = rect;
|
||||
let hover =
|
||||
(!clipped || in_area(cursor.1)) && ui::hovered(cursor, x, y, bw, bh);
|
||||
let b = buttons[index];
|
||||
ui::button(batch, atlas, x, y, bw, bh, &b.label, true, hover);
|
||||
if hover && let Some(t) = &b.tooltip {
|
||||
tooltip = Some(t.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(s) = start {
|
||||
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
|
||||
}
|
||||
if layout.content > ah {
|
||||
ui::scrollbar(
|
||||
batch,
|
||||
atlas,
|
||||
ax + aw - 6.0,
|
||||
ay,
|
||||
ay + ah,
|
||||
layout.content,
|
||||
open.scroll.amount,
|
||||
);
|
||||
}
|
||||
if warn_hover {
|
||||
tooltip = Some(Text::translate("menu.custom_screen_info.tooltip", &[]));
|
||||
}
|
||||
if let Some(t) = tooltip {
|
||||
let lines: Vec<Text> = atlas
|
||||
.font
|
||||
.split_lines(&t, 170.0)
|
||||
.into_iter()
|
||||
.map(|l| l.0)
|
||||
.collect();
|
||||
ui::tooltip(batch, atlas, &lines, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
/// A left click on a dialog screen.
|
||||
pub(super) fn dialog_click(&mut self) -> Result<()> {
|
||||
let cursor = self.cursor;
|
||||
if self.dialogs.warning {
|
||||
let (title, message, _) = warning_texts();
|
||||
let answer = Confirm::new(&self.gui.atlas.font, self.gui_size(), &title, &message)
|
||||
.answer_at(cursor);
|
||||
match answer {
|
||||
Some(true) => {
|
||||
self.audio.play_button_click();
|
||||
let reason = Text::translate("menu.custom_screen_info.disconnect", &[]);
|
||||
return self.leave_server(Some(reason.plain()));
|
||||
}
|
||||
Some(false) => {
|
||||
self.audio.play_button_click();
|
||||
self.dialogs.warning = false;
|
||||
if !self.dialog_open() {
|
||||
self.dialog_closed();
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(since) = self.dialogs.waiting {
|
||||
let (w, h) = self.gui_size();
|
||||
let active = waiting_button((since.elapsed().as_millis() / 50) as u32).2;
|
||||
let (bx, by) = (
|
||||
((w - 200.0) / 2.0).trunc(),
|
||||
((h - 53.0) / 2.0).trunc() + 33.0,
|
||||
);
|
||||
if active && ui::hovered(cursor, bx, by, 200.0, 20.0) {
|
||||
self.audio.play_button_click();
|
||||
self.dialogs.waiting = None;
|
||||
self.dialog_closed();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(layout) = self.dialog_layout() else {
|
||||
return Ok(());
|
||||
};
|
||||
let [wx, wy, ww, wh] = layout.warning;
|
||||
if ui::hovered(cursor, wx, wy, ww, wh) {
|
||||
self.audio.play_button_click();
|
||||
self.dialogs.warning = true;
|
||||
return Ok(());
|
||||
}
|
||||
let Some(open) = self.dialogs.open.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
let [_, ay, _, ah] = layout.area;
|
||||
let mut action = None;
|
||||
open.focus = None;
|
||||
for (part, clipped) in layout.placed(open.scroll.amount) {
|
||||
if clipped && !(cursor.1 >= ay && cursor.1 < ay + ah) {
|
||||
continue;
|
||||
}
|
||||
match part {
|
||||
Part::Field {
|
||||
input,
|
||||
rect: [x, y, w, h],
|
||||
} if ui::hovered(cursor, x, y, w, h) => {
|
||||
open.focus = Some(input);
|
||||
if let Some(Some(edit)) = open.fields.get_mut(input) {
|
||||
edit.focused = true;
|
||||
edit.click(&self.gui.atlas, cursor.0, false, false);
|
||||
}
|
||||
}
|
||||
Part::Check {
|
||||
input,
|
||||
rect: [x, y, w, h],
|
||||
} if ui::hovered(cursor, x, y, w, h) => {
|
||||
if let Some(InputValue::Bool(b)) = open.values.get_mut(input) {
|
||||
*b = !*b;
|
||||
}
|
||||
action = Some(None);
|
||||
}
|
||||
Part::Button {
|
||||
index,
|
||||
rect: [x, y, w, h],
|
||||
} if ui::hovered(cursor, x, y, w, h) => {
|
||||
action = Some(Some(index));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let Some(action) = action else {
|
||||
return Ok(());
|
||||
};
|
||||
self.audio.play_button_click();
|
||||
let Some(index) = action else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(open) = self.dialogs.open.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
Self::dialog_values(open);
|
||||
let d = &open.dialog;
|
||||
let click = d.buttons()[index]
|
||||
.action
|
||||
.as_ref()
|
||||
.and_then(|a| a.click(&d.inputs, &open.values));
|
||||
let after = d.after_action;
|
||||
self.run_dialog_action(click, after)
|
||||
}
|
||||
|
||||
/// The mouse wheel over a dialog: its body scrolls 10 a step.
|
||||
pub(super) fn dialog_scroll(&mut self, delta: f32) {
|
||||
let Some(layout) = self.dialog_layout() else {
|
||||
return;
|
||||
};
|
||||
if let Some(open) = self.dialogs.open.as_mut() {
|
||||
let [_, ay, _, ah] = layout.area;
|
||||
open.scroll.wheel(delta, 10.0, ay, ay + ah, layout.content);
|
||||
}
|
||||
}
|
||||
|
||||
/// A key pressed on a dialog screen: Escape closes what allows it, Tab
|
||||
/// moves between the text inputs, the rest goes to the focused one
|
||||
/// (`shortcut`: the press as an edit shortcut; `text`: what it types).
|
||||
pub(super) fn dialog_key(
|
||||
&mut self,
|
||||
key: KeyCode,
|
||||
shortcut: Option<EditShortcut>,
|
||||
text: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let escape = key == KeyCode::Escape;
|
||||
if self.dialogs.warning {
|
||||
if escape {
|
||||
self.dialogs.warning = false;
|
||||
if !self.dialog_open() {
|
||||
self.dialog_closed();
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(since) = self.dialogs.waiting {
|
||||
// shouldCloseOnEsc: once Back works.
|
||||
if escape && waiting_button((since.elapsed().as_millis() / 50) as u32).2 {
|
||||
self.dialogs.waiting = None;
|
||||
self.dialog_closed();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let ctrl = self.modifiers.control_key() || self.modifiers.super_key();
|
||||
let shift = self.modifiers.shift_key();
|
||||
let Some(open) = self.dialogs.open.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
if escape {
|
||||
if !open.dialog.can_close_with_escape {
|
||||
return Ok(());
|
||||
}
|
||||
// onClose: the cancel action, and the screen closes.
|
||||
Self::dialog_values(open);
|
||||
let d = &open.dialog;
|
||||
let click = d.on_cancel().and_then(|a| a.click(&d.inputs, &open.values));
|
||||
return self.run_dialog_action(click, AfterAction::Close);
|
||||
}
|
||||
if key == KeyCode::Tab {
|
||||
let texts: Vec<usize> = (0..open.fields.len())
|
||||
.filter(|&i| open.fields[i].is_some())
|
||||
.collect();
|
||||
if !texts.is_empty() {
|
||||
let at = open.focus.and_then(|f| texts.iter().position(|&i| i == f));
|
||||
let next = match at {
|
||||
None if shift => texts.len() - 1,
|
||||
None => 0,
|
||||
Some(p) if shift => (p + texts.len() - 1) % texts.len(),
|
||||
Some(p) => (p + 1) % texts.len(),
|
||||
};
|
||||
open.focus = Some(texts[next]);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(Some(edit)) = open.focus.and_then(|f| open.fields.get_mut(f)) else {
|
||||
return Ok(());
|
||||
};
|
||||
if let Some(shortcut) = shortcut {
|
||||
edit.shortcut(shortcut, &mut self.clipboard);
|
||||
return Ok(());
|
||||
}
|
||||
if edit.key(key, ctrl, shift) {
|
||||
return Ok(());
|
||||
}
|
||||
let typed: String = text
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.collect();
|
||||
if !typed.is_empty() {
|
||||
edit.insert_text(&typed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `type TEXT` with a dialog open: into the focused text input, or the
|
||||
/// first one.
|
||||
pub(super) fn dialog_type(&mut self, text: &str) -> bool {
|
||||
let Some(open) = self.dialogs.open.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
let focus = open
|
||||
.focus
|
||||
.or_else(|| open.fields.iter().position(Option::is_some));
|
||||
let Some(Some(edit)) = focus.and_then(|f| open.fields.get_mut(f)) else {
|
||||
return false;
|
||||
};
|
||||
open.focus = focus;
|
||||
edit.insert_text(text);
|
||||
true
|
||||
}
|
||||
|
||||
/// What `state` reports: the open dialog and its values, or the waiting
|
||||
/// and warning screens.
|
||||
pub(super) fn dialog_status(&self) -> serde_json::Value {
|
||||
let d = &self.dialogs;
|
||||
let screen = if d.warning {
|
||||
Some("warning")
|
||||
} else if d.waiting.is_some() {
|
||||
Some("waiting_for_response")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let open = d.open.as_ref().map(|open| {
|
||||
let mut values = open.values.clone();
|
||||
for (value, field) in values.iter_mut().zip(&open.fields) {
|
||||
if let Some(f) = field {
|
||||
*value = InputValue::Text(f.value.clone());
|
||||
}
|
||||
}
|
||||
open.dialog.json(&values)
|
||||
});
|
||||
serde_json::json!({ "open": open, "screen": screen })
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,11 @@ fn opaque(facts: &StateFacts) -> bool {
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn prepare_entity_culling(&mut self, camera: glam::DVec3) {
|
||||
// Spans tell the pack's passes which entities are hidden; without them, nothing changes.
|
||||
self.pack_shadow_casters = match (&self.renderer, &self.pack_ids) {
|
||||
(Some(r), Some(_)) => r.pack_shadow_casters(),
|
||||
_ => (false, false),
|
||||
};
|
||||
let at = camera.to_array().map(|v| v.floor() as i32);
|
||||
self.entity_culler = (self.settings.horizon.entity_culling
|
||||
// Packs can replace an opaque block's model or texture.
|
||||
@@ -28,24 +33,29 @@ impl Game<'_> {
|
||||
/// Use complete generated geometry so equipment, animation and custom
|
||||
/// models cannot stick out of an assumed collision-sized culling box.
|
||||
pub(super) fn cull_entity_vertices(&self, vertices: &mut Vec<Vertex>, start: usize) {
|
||||
if let Some(culler) = &self.entity_culler {
|
||||
culler.cull_vertices(vertices, start, |pos| {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
if !opaque(self.res.facts().get(state)) {
|
||||
return false;
|
||||
}
|
||||
let Some(y) = pos[1].checked_sub(MIN_Y) else {
|
||||
return false;
|
||||
};
|
||||
let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4);
|
||||
// Newly edited or not-yet-uploaded terrain is not an occluder.
|
||||
self.renderer
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.has_section(section))
|
||||
&& !self.world.dirty_sections.contains(§ion)
|
||||
&& !self.streaming.is_meshing(section)
|
||||
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
|
||||
});
|
||||
let Some(culler) = &self.entity_culler else {
|
||||
return;
|
||||
};
|
||||
let hidden = culler.hidden(vertices, start, |pos| {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
if !opaque(self.res.facts().get(state)) {
|
||||
return false;
|
||||
}
|
||||
let Some(y) = pos[1].checked_sub(MIN_Y) else {
|
||||
return false;
|
||||
};
|
||||
let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4);
|
||||
// Newly edited or not-yet-uploaded terrain is not an occluder.
|
||||
self.renderer
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.has_section(section))
|
||||
&& !self.world.dirty_sections.contains(§ion)
|
||||
&& !self.streaming.is_meshing(section)
|
||||
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
|
||||
});
|
||||
// A shader pack's shadow pass still draws what the camera cannot see.
|
||||
if hidden && !(self.pack_shadow_casters.0 && self.hide_spans_from(start, vertices.len())) {
|
||||
vertices.truncate(start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,8 @@ impl Game<'_> {
|
||||
_ => return,
|
||||
};
|
||||
self.extras.mouse[i] = pressed;
|
||||
if pressed && self.settings.extras.keystrokes {
|
||||
// Mods read the clicks too (`input.clicks-per-second`).
|
||||
if pressed && (self.settings.extras.keystrokes || self.mods.running()) {
|
||||
let now = self.extras_now();
|
||||
self.extras.cps[i].click(now);
|
||||
}
|
||||
@@ -87,13 +88,28 @@ impl Game<'_> {
|
||||
self.extras.mouse = [false; 2];
|
||||
}
|
||||
self.update_minimap();
|
||||
if self.settings.extras.fps {
|
||||
// Mods read the counter too (`render.frame-stats`).
|
||||
if self.settings.extras.fps || self.mods.running() {
|
||||
let now = self.extras_now();
|
||||
self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0);
|
||||
} else {
|
||||
self.extras.fps.clear();
|
||||
}
|
||||
}
|
||||
/// The frame counter for mods: fps, min, 1% low.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) fn frame_reading(&self) -> (u32, u32, u32) {
|
||||
let r = self.extras.fps.reading();
|
||||
(r.fps, r.min, r.low)
|
||||
}
|
||||
/// Attack and use clicks in the last second, and whether each is held.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) fn mouse_reading(&mut self) -> ((u32, u32), [bool; 2]) {
|
||||
let now = self.extras_now();
|
||||
let [l, r] = &mut self.extras.cps;
|
||||
let cps = (l.per_second(now) as u32, r.per_second(now) as u32);
|
||||
(cps, self.extras.mouse)
|
||||
}
|
||||
/// Auto-reconnect: a connection to `address` as `name` starts.
|
||||
pub(super) fn extras_connecting(&mut self, address: &str, name: &str) {
|
||||
self.extras.reconnect.connecting(address, name);
|
||||
|
||||
@@ -38,6 +38,8 @@ pub(super) struct GuestPlay {
|
||||
use_delay: u32,
|
||||
/// The shield's ItemCooldowns entry: an axe disabled it for this many ticks.
|
||||
pub(super) shield_cooldown: u32,
|
||||
/// The guest's `Player.getCooldowns()` (`Game::cooldowns` for its turn).
|
||||
pub(super) cooldowns: horizon_client::cooldowns::Cooldowns,
|
||||
attack_ticks: u32,
|
||||
/// The main hand's item at the guest's last tick (`Game::attack_item`).
|
||||
attack_item: Option<std::sync::Arc<str>>,
|
||||
@@ -84,6 +86,7 @@ pub(super) struct GuestPlay {
|
||||
equipped: Option<Vec<Option<ItemStack>>>,
|
||||
/// The guest's cast fishing hook (`Player.fishing`).
|
||||
pub(super) hook: Option<super::fishing::Hook>,
|
||||
sculk: super::sculk::PlayerEvents,
|
||||
}
|
||||
|
||||
/// A guest's command waiting for the hub (`LanHost::commands`).
|
||||
@@ -125,6 +128,8 @@ pub(super) struct GuestSwap {
|
||||
using: Option<(usize, u32)>,
|
||||
use_delay: u32,
|
||||
pub(super) shield_cooldown: u32,
|
||||
/// The guest's item cooldowns (`Game::cooldowns` for its turn).
|
||||
cooldowns: horizon_client::cooldowns::Cooldowns,
|
||||
attack_ticks: u32,
|
||||
attack_item: Option<std::sync::Arc<str>>,
|
||||
swing: horizon_client::first_person::SwingState,
|
||||
@@ -252,6 +257,7 @@ impl Game<'_> {
|
||||
if fresh {
|
||||
// A new body (joined, respawned, changed level): nothing on it yet.
|
||||
play.equipped = None;
|
||||
play.sculk = Default::default();
|
||||
}
|
||||
let g = &mut host.hub.guests[i];
|
||||
// The guest's body.
|
||||
@@ -259,6 +265,7 @@ impl Game<'_> {
|
||||
host.play.insert(conn, play);
|
||||
return None;
|
||||
};
|
||||
self.sculk.swap_player(&mut play.sculk);
|
||||
// The guest's own CombatTracker: damage to them is not the host's.
|
||||
// A new body starts with no record of the last one.
|
||||
let guest_combat = if fresh {
|
||||
@@ -328,6 +335,7 @@ impl Game<'_> {
|
||||
let using = std::mem::replace(&mut self.using, play.using.take());
|
||||
let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay);
|
||||
let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown);
|
||||
let cooldowns = std::mem::replace(&mut self.cooldowns, std::mem::take(&mut play.cooldowns));
|
||||
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
|
||||
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
|
||||
let swing = std::mem::replace(&mut self.swing, play.swing);
|
||||
@@ -412,6 +420,7 @@ impl Game<'_> {
|
||||
using,
|
||||
use_delay,
|
||||
shield_cooldown,
|
||||
cooldowns,
|
||||
attack_ticks,
|
||||
attack_item,
|
||||
swing,
|
||||
@@ -469,6 +478,7 @@ impl Game<'_> {
|
||||
using,
|
||||
use_delay,
|
||||
shield_cooldown,
|
||||
cooldowns,
|
||||
attack_ticks,
|
||||
attack_item,
|
||||
swing,
|
||||
@@ -492,6 +502,7 @@ impl Game<'_> {
|
||||
projectiles,
|
||||
modifiers,
|
||||
} = swap;
|
||||
self.sculk.swap_player(&mut play.sculk);
|
||||
// The guest's damage record back into their slot, the host's in place.
|
||||
let guest_combat = std::mem::replace(&mut self.combat, combat);
|
||||
self.guest_combat.insert(conn, guest_combat);
|
||||
@@ -508,6 +519,16 @@ impl Game<'_> {
|
||||
for packet in std::mem::replace(&mut self.guest_packets, packets) {
|
||||
host.hub.send_to(conn, &packet);
|
||||
}
|
||||
// ServerItemCooldowns.onCooldownStarted: the guest's own cooldown.
|
||||
for (group, duration) in std::mem::take(&mut self.guest_cooldowns) {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::Cooldown(play::Cooldown {
|
||||
group: group.to_string(),
|
||||
duration,
|
||||
}),
|
||||
);
|
||||
}
|
||||
(self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting;
|
||||
play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause);
|
||||
// An ender chest the guest opened: the menu shows their inventory
|
||||
@@ -537,6 +558,7 @@ impl Game<'_> {
|
||||
play.using = std::mem::replace(&mut self.using, using);
|
||||
play.use_delay = std::mem::replace(&mut self.use_delay, use_delay);
|
||||
play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown);
|
||||
play.cooldowns = std::mem::replace(&mut self.cooldowns, cooldowns);
|
||||
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
|
||||
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
|
||||
play.swing = std::mem::replace(&mut self.swing, swing);
|
||||
@@ -1781,8 +1803,19 @@ impl Game<'_> {
|
||||
}
|
||||
let play = host.play.entry(conn).or_default();
|
||||
// Player.tick's ItemCooldowns.tick, once a tick for each player
|
||||
// (the shield an axe disabled).
|
||||
// (the shield an axe disabled, a thrown pearl).
|
||||
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
|
||||
// ServerItemCooldowns.onCooldownEnded: a finished entry is told to
|
||||
// the guest (a duration of 0 removes it).
|
||||
for group in play.cooldowns.tick() {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::Cooldown(play::Cooldown {
|
||||
group: group.to_string(),
|
||||
duration: 0,
|
||||
}),
|
||||
);
|
||||
}
|
||||
let digging = play.digging;
|
||||
let using = play.using.is_some();
|
||||
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
|
||||
@@ -2111,6 +2144,12 @@ impl Game<'_> {
|
||||
let _ = w.apply_fire_contact();
|
||||
let _ = w.server_hazards_tick(in_wall);
|
||||
let mut events = std::mem::take(&mut w.player.events);
|
||||
// LayeredCauldronBlock.handleEntityOnFireInside along those moves.
|
||||
for event in &events {
|
||||
if let MotionEvent::CauldronExtinguish { pos } = event {
|
||||
game.cauldron_extinguish(*pos);
|
||||
}
|
||||
}
|
||||
// WitherRoseBlock.entityInside along those moves.
|
||||
for event in &events {
|
||||
if matches!(event, MotionEvent::InsideWitherRose) {
|
||||
@@ -2152,6 +2191,7 @@ impl Game<'_> {
|
||||
let Some((events, marked)) = events else {
|
||||
return;
|
||||
};
|
||||
self.as_guest(host, conn, |game| game.tick_player_sculk_events());
|
||||
for event in events {
|
||||
match event {
|
||||
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at),
|
||||
|
||||
@@ -171,6 +171,19 @@ impl Game<'_> {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// The same guests' feet and whether they stand on the ground, for the
|
||||
/// blocks that also ask that (`BigDripleafBlock.canEntityTilt`).
|
||||
pub(super) fn lan_guest_feet(&self) -> Vec<([f64; 3], bool)> {
|
||||
let Some(host) = self.lan.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
host.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
|
||||
.map(|g| (g.position, g.on_ground))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The guests a projectile can hit, under their entity ids.
|
||||
pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> {
|
||||
|
||||
@@ -388,7 +388,10 @@ impl Restrictions {
|
||||
1 => Some("chat_restriction.chat_disabled_by_options"),
|
||||
_ => None,
|
||||
};
|
||||
let (chat, commands) = (chat_visibility == 0, chat_visibility < 2);
|
||||
let abilities = horizon_client::chat::ChatAbilities::new(
|
||||
horizon_client::chat::ChatVisibility::from_option(chat_visibility),
|
||||
);
|
||||
let (chat, commands) = (abilities.send_messages, abilities.send_commands);
|
||||
// The body's widgets: text blocks (lines, top) and the action's top.
|
||||
let mut blocks = Vec::new();
|
||||
let mut action = None;
|
||||
|
||||
@@ -923,15 +923,16 @@ impl Game<'_> {
|
||||
batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX);
|
||||
}
|
||||
let grey = horizon_client::hud::rgba(64, 64, 64, 255);
|
||||
let title = self
|
||||
.remote_menu_title()
|
||||
.unwrap_or_else(|| self.container_title(self.translate(key, fallback)));
|
||||
let title = &self.remote_menu_title().unwrap_or_else(|| {
|
||||
horizon_client::text::Text::literal(self.container_title(self.translate(key, fallback)))
|
||||
.resolve_legacy()
|
||||
});
|
||||
let title_x = if screen == Screen::Hopper {
|
||||
8.0
|
||||
} else {
|
||||
(176.0 - horizon_client::hud::HudBatch::text_width(atlas, &title)) / 2.0
|
||||
(176.0 - atlas.font.width_text(title)) / 2.0
|
||||
};
|
||||
batch.text(atlas, &title, ox + title_x, oy + 6.0, grey, false);
|
||||
batch.text_styled(atlas, title, ox + title_x, oy + 6.0, grey, false);
|
||||
let inventory = self.translate("container.inventory", "Inventory");
|
||||
batch.text(atlas, &inventory, ox + 8.0, oy + height - 94.0, grey, false);
|
||||
true
|
||||
|
||||
@@ -1463,6 +1463,7 @@ impl Game<'_> {
|
||||
lid: &lid,
|
||||
sign: &|_| None,
|
||||
banner: &|_| Vec::new(),
|
||||
skull: &|_| None,
|
||||
glyph: &|c| self.gui.atlas.glyph_cell(c),
|
||||
};
|
||||
self.res
|
||||
|
||||
@@ -86,23 +86,29 @@ impl Game<'_> {
|
||||
impl Game<'_> {
|
||||
/// The running mods' HUD shapes, in order, over the HUD.
|
||||
pub(super) fn draw_mod_shapes(&self, batch: &mut HudBatch) {
|
||||
let atlas = &self.gui.atlas;
|
||||
for shape in self.mods.mods.hud_shapes() {
|
||||
self.draw_shapes(batch, std::slice::from_ref(shape), (0.0, 0.0));
|
||||
}
|
||||
}
|
||||
/// Shapes with their GUI coordinates moved by `(ox, oy)`.
|
||||
pub(super) fn draw_shapes(&self, batch: &mut HudBatch, shapes: &[Shape], (ox, oy): (f32, f32)) {
|
||||
let atlas = &self.gui.atlas;
|
||||
for shape in shapes {
|
||||
match shape {
|
||||
Shape::Fill(f) => {
|
||||
let r = f.rect;
|
||||
batch.fill(atlas, r.x, r.y, r.w, r.h, argb(f.color));
|
||||
batch.fill(atlas, ox + r.x, oy + r.y, r.w, r.h, argb(f.color));
|
||||
}
|
||||
Shape::Quad(q) => {
|
||||
let (a, b, c, d) = q.corners;
|
||||
let corners = [[a.x, a.y], [b.x, b.y], [c.x, c.y], [d.x, d.y]];
|
||||
let corners = [a, b, c, d].map(|p| [ox + p.x, oy + p.y]);
|
||||
batch.fill_quad(atlas, corners, argb(q.color));
|
||||
}
|
||||
Shape::Sprite(s) => {
|
||||
let r = s.rect;
|
||||
let name = s.sprite.strip_prefix("minecraft:").unwrap_or(&s.sprite);
|
||||
let name = format!("gui/sprites/{name}");
|
||||
batch.sprite_scaled(atlas, &name, r.x, r.y, r.w, r.h, argb(s.color));
|
||||
batch.sprite_scaled(atlas, &name, ox + r.x, oy + r.y, r.w, r.h, argb(s.color));
|
||||
}
|
||||
Shape::Item(i) => {
|
||||
if self.res.items().get(&i.item).is_none() {
|
||||
@@ -110,21 +116,23 @@ impl Game<'_> {
|
||||
}
|
||||
let start = batch.vertices.len();
|
||||
let stack = ItemStack::new(i.item.as_str(), 1);
|
||||
self.draw_item_model(batch, &stack, i.at.x, i.at.y);
|
||||
batch.scale_since(start, i.at.x, i.at.y, i.scale, i.scale);
|
||||
let (x, y) = (ox + i.at.x, oy + i.at.y);
|
||||
self.draw_item_model(batch, &stack, x, y);
|
||||
batch.scale_since(start, x, y, i.scale, i.scale);
|
||||
}
|
||||
Shape::Text(t) => {
|
||||
let text = Text::literal(t.text.clone());
|
||||
let x = if t.centered {
|
||||
t.at.x - (HudBatch::text_width(atlas, &t.text) / 2.0).floor()
|
||||
let centre = if t.centered {
|
||||
(HudBatch::text_width(atlas, &t.text) / 2.0).floor()
|
||||
} else {
|
||||
t.at.x
|
||||
0.0
|
||||
};
|
||||
let x = ox + t.at.x - centre;
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&text,
|
||||
x,
|
||||
t.at.y,
|
||||
oy + t.at.y,
|
||||
argb(t.color | 0xFF00_0000),
|
||||
t.shadow,
|
||||
);
|
||||
|
||||
@@ -21,6 +21,7 @@ use {
|
||||
extras::Corner,
|
||||
extras_hud,
|
||||
items::ItemStack,
|
||||
keybinds,
|
||||
mod_list::Installed,
|
||||
options_ui::Page,
|
||||
text::{self, Text},
|
||||
@@ -59,8 +60,32 @@ pub(super) struct ModsState {
|
||||
/// A `ui` mod's screen or settings page while it is up.
|
||||
#[cfg(feature = "mods")]
|
||||
screen: Option<ModScreen>,
|
||||
/// The HUD font's advances for `render.text-width`, made once.
|
||||
#[cfg(feature = "mods")]
|
||||
font_widths: std::sync::Arc<[f32]>,
|
||||
}
|
||||
|
||||
/// The mappings `input.mapping` answers for, with the default key their
|
||||
/// binding is translated to (none: a mouse button, attack or use).
|
||||
#[cfg(feature = "mods")]
|
||||
const MAPPINGS: [(&str, Option<winit::keyboard::KeyCode>); 9] = {
|
||||
use winit::keyboard::KeyCode as K;
|
||||
[
|
||||
("key.forward", Some(K::KeyW)),
|
||||
("key.left", Some(K::KeyA)),
|
||||
("key.back", Some(K::KeyS)),
|
||||
("key.right", Some(K::KeyD)),
|
||||
("key.jump", Some(K::Space)),
|
||||
("key.sneak", Some(K::ShiftLeft)),
|
||||
("key.sprint", Some(K::ControlLeft)),
|
||||
("key.attack", None),
|
||||
("key.use", None),
|
||||
]
|
||||
};
|
||||
/// Characters `render.text-width` knows exactly: U+0000 to U+024F.
|
||||
#[cfg(feature = "mods")]
|
||||
const FONT_CHARS: u32 = 0x250;
|
||||
|
||||
/// A `ui` mod's own screen, or its settings page from Options > Mods: the
|
||||
/// widgets the mod pushed, laid out and drawn with the menus' own widgets.
|
||||
#[cfg(feature = "mods")]
|
||||
@@ -99,10 +124,10 @@ impl ModsState {
|
||||
}
|
||||
false
|
||||
}
|
||||
/// Whether a mod draws a HUD panel.
|
||||
/// Whether a mod draws a HUD panel or a corner panel.
|
||||
pub(super) fn has_panels(&self) -> bool {
|
||||
#[cfg(feature = "mods")]
|
||||
if self.mods.panels().next().is_some() {
|
||||
if self.mods.panels().next().is_some() || self.mods.corner_panels().next().is_some() {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
@@ -328,8 +353,8 @@ impl Game<'_> {
|
||||
self.start_mods();
|
||||
}
|
||||
}
|
||||
/// What mods read this tick.
|
||||
fn mod_snapshot(&self) -> Snapshot {
|
||||
/// What mods read this tick (or frame, for mods with a `frame` hook).
|
||||
fn mod_snapshot(&mut self) -> Snapshot {
|
||||
let player = self.player.as_ref().map(|p| Player {
|
||||
x: p.position.x,
|
||||
y: p.position.y,
|
||||
@@ -344,11 +369,35 @@ impl Game<'_> {
|
||||
game_time: self.world.game_time.max(0) as u64,
|
||||
day_time: self.world.day_time.max(0) as u64,
|
||||
});
|
||||
let (cps, mouse) = self.mouse_reading();
|
||||
// The movement and click mappings, as the keystroke overlay reads them:
|
||||
// keys by the default key their binding is translated to.
|
||||
let mappings = MAPPINGS
|
||||
.iter()
|
||||
.map(|&(name, key)| {
|
||||
let label = keybinds::display_name(self.settings.keys.get(name)).plain();
|
||||
let down = match key {
|
||||
Some(k) => self.keys.contains(&k),
|
||||
None => mouse[usize::from(name == "key.use")],
|
||||
};
|
||||
(name, label, down)
|
||||
})
|
||||
.collect();
|
||||
if self.mods.font_widths.is_empty() {
|
||||
let atlas = &self.gui.atlas;
|
||||
self.mods.font_widths = (0..FONT_CHARS)
|
||||
.map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1))
|
||||
.collect();
|
||||
}
|
||||
Snapshot {
|
||||
player,
|
||||
clock,
|
||||
gui_size: self.gui_size(),
|
||||
held: self.mod_held(),
|
||||
frame: self.frame_reading(),
|
||||
mappings,
|
||||
cps,
|
||||
font_widths: self.mods.font_widths.clone(),
|
||||
}
|
||||
}
|
||||
/// A game tick.
|
||||
@@ -385,6 +434,10 @@ impl Game<'_> {
|
||||
if !self.mods.mods.is_running() {
|
||||
return;
|
||||
}
|
||||
if self.mods.mods.wants_frames() {
|
||||
let snapshot = self.mod_snapshot();
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
}
|
||||
self.mods.mods.frame(elapsed.as_secs_f32());
|
||||
self.show_mod_output();
|
||||
}
|
||||
@@ -454,10 +507,16 @@ impl Game<'_> {
|
||||
}
|
||||
};
|
||||
// Not through system_message: a mod must not hear its own lines.
|
||||
// Written by this client, so the Chat option doesn't hide it.
|
||||
let focused = self.screen == Screen::Chat;
|
||||
self.ui
|
||||
.chat
|
||||
.add(&self.gui.atlas, line, None, self.ticks, focused);
|
||||
self.ui.chat.add(
|
||||
&self.gui.atlas,
|
||||
line,
|
||||
None,
|
||||
horizon_client::chat::ChatSource::Client,
|
||||
self.ticks,
|
||||
focused,
|
||||
);
|
||||
}
|
||||
// A mod may set or clear its settings page in any call, not only
|
||||
// while loading: its row's Settings button follows.
|
||||
@@ -486,6 +545,20 @@ impl Game<'_> {
|
||||
.collect();
|
||||
extras_hud::draw_lines(batch, &self.gui.atlas, corners, corner, &lines);
|
||||
}
|
||||
// Capability `render`'s corner panels, placed the same way.
|
||||
for panel in self.mods.mods.corner_panels() {
|
||||
let corner = match panel.corner {
|
||||
horizon_mods::RenderCorner::TopLeft => Corner::TopLeft,
|
||||
horizon_mods::RenderCorner::TopRight => Corner::TopRight,
|
||||
horizon_mods::RenderCorner::BottomLeft => Corner::BottomLeft,
|
||||
horizon_mods::RenderCorner::BottomRight => Corner::BottomRight,
|
||||
};
|
||||
if self.debug && corner == Corner::TopLeft {
|
||||
continue;
|
||||
}
|
||||
let at = corners.place(corner, panel.width, panel.height);
|
||||
self.draw_shapes(batch, &panel.shapes, at);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `ui` screen's title and widgets as the mod last pushed them; None
|
||||
@@ -516,7 +589,7 @@ impl Game<'_> {
|
||||
for w in widgets {
|
||||
let wh = match w {
|
||||
UiWidget::Text(_) => 12.0,
|
||||
UiWidget::Item(_) => 20.0,
|
||||
UiWidget::Item(_) | UiWidget::Button(_) => 20.0,
|
||||
UiWidget::List(l) => (l.rows.len().min(6) as f32 * 12.0) + 8.0,
|
||||
};
|
||||
// Nothing may cover Done; a crowded mod loses what won't fit.
|
||||
@@ -611,6 +684,21 @@ impl Game<'_> {
|
||||
let mut list_i = 0usize;
|
||||
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
|
||||
match w {
|
||||
UiWidget::Button(b) => {
|
||||
let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0);
|
||||
let label = Text::literal(b.label.clone());
|
||||
ui::button(
|
||||
batch,
|
||||
atlas,
|
||||
x,
|
||||
wy,
|
||||
MOD_UI_COLUMN,
|
||||
20.0,
|
||||
&label,
|
||||
true,
|
||||
hover,
|
||||
);
|
||||
}
|
||||
UiWidget::Text(t) => {
|
||||
let color = if t.color == 0 {
|
||||
u32::MAX
|
||||
@@ -733,6 +821,16 @@ impl Game<'_> {
|
||||
// The `ui_select` call needs `&mut`: find the pick first.
|
||||
let mut hit = None;
|
||||
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
|
||||
// A button is `select(id, 0)`.
|
||||
if let UiWidget::Button(b) = w
|
||||
&& ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0)
|
||||
{
|
||||
self.audio.play_button_click();
|
||||
let owner = self.mods.screen.as_ref().map_or(0, |ms| ms.owner);
|
||||
self.mods.mods.ui_select(owner, b.id, 0);
|
||||
self.show_mod_output();
|
||||
return;
|
||||
}
|
||||
let UiWidget::List(l) = w else { continue };
|
||||
let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default();
|
||||
list_i += 1;
|
||||
|
||||
@@ -412,7 +412,8 @@ impl Game<'_> {
|
||||
}
|
||||
/// Whether the player's own model shows in the world view.
|
||||
fn player_model_shown(&self) -> bool {
|
||||
!self.camera_type.first_person()
|
||||
// A shader pack's shadow pass draws the player in first person too (shadowPlayer).
|
||||
(!self.camera_type.first_person() || self.pack_shadow_casters.1)
|
||||
&& self.sleeping.is_none()
|
||||
&& !self.spectator()
|
||||
&& self.potions.effects.get("minecraft:invisibility").is_none()
|
||||
|
||||
@@ -58,6 +58,12 @@ fn remote_text(tag: &Tag) -> horizon_client::text::Text {
|
||||
comp_text(&tag_to_json(tag))
|
||||
}
|
||||
|
||||
/// `ClientboundOpenScreenPacket.title` as a container screen draws it: the
|
||||
/// component's styles, and the `§` codes a literal holds (`StringDecomposer`).
|
||||
fn menu_title(tag: &Tag) -> horizon_client::text::Text {
|
||||
remote_text(tag).resolve_legacy()
|
||||
}
|
||||
|
||||
/// A section's sky and block light layers from the wire.
|
||||
type LightLayers = (Option<Vec<u8>>, Option<Vec<u8>>);
|
||||
|
||||
@@ -123,6 +129,9 @@ pub(super) struct Remote {
|
||||
loaded_sent: bool,
|
||||
/// The view distance last sent in ClientInformation.
|
||||
sent_view: i8,
|
||||
/// The Chat option's visibility last sent in ClientInformation
|
||||
/// (`Options.broadcastOptions` sends it again when it changes).
|
||||
sent_chat_visibility: i32,
|
||||
/// BlockStatePredictionHandler: blocks changed ahead of the server (a predicted break),
|
||||
/// with the sequence of the last action that changed them and the state the server
|
||||
/// last said they have. Until the server acknowledges that sequence its block updates
|
||||
@@ -130,8 +139,8 @@ pub(super) struct Remote {
|
||||
predictions: HashMap<[i32; 3], (i32, i32)>,
|
||||
/// Open container: (window id, menu name).
|
||||
pub(super) menu: Option<(i32, String)>,
|
||||
/// The open menu's title as the server named it.
|
||||
pub(super) menu_title: Option<String>,
|
||||
/// The open menu's title as the server named it, with its styles.
|
||||
pub(super) menu_title: Option<horizon_client::text::Text>,
|
||||
state_id: i32,
|
||||
use_target: Option<[i32; 3]>,
|
||||
entities: HashMap<i32, Tracked>,
|
||||
@@ -422,6 +431,7 @@ impl Game<'_> {
|
||||
abilities: None,
|
||||
loaded_sent: false,
|
||||
sent_view: view,
|
||||
sent_chat_visibility: self.settings.chat_visibility as i32,
|
||||
predictions: HashMap::new(),
|
||||
menu: None,
|
||||
menu_title: None,
|
||||
@@ -489,6 +499,7 @@ impl Game<'_> {
|
||||
r.session.disconnect();
|
||||
}
|
||||
self.server_packs_disconnect();
|
||||
self.close_dialogs();
|
||||
// Single player's server thread saves the world before the title shows.
|
||||
let single_player = match self.integrated.take() {
|
||||
Some(server) => {
|
||||
@@ -630,14 +641,23 @@ impl Game<'_> {
|
||||
)
|
||||
}
|
||||
/// A line in the connection's chat, with its styles, click and hover
|
||||
/// events (ChatComponent.addMessage).
|
||||
pub(super) fn chat_line(&mut self, content: horizon_client::text::Text) {
|
||||
/// events (ChatComponent.addMessage). The lines the Chat option hides
|
||||
/// are dropped there (its `visibleMessageFilter`).
|
||||
pub(super) fn chat_line(
|
||||
&mut self,
|
||||
content: horizon_client::text::Text,
|
||||
source: horizon_client::chat::ChatSource,
|
||||
) {
|
||||
if !self.ui.chat.shows(source) {
|
||||
return;
|
||||
}
|
||||
let text = content.plain();
|
||||
log::info!("[chat] {text}");
|
||||
self.ui.chat.add(
|
||||
&self.gui.atlas,
|
||||
content,
|
||||
None,
|
||||
source,
|
||||
self.ticks,
|
||||
self.screen == Screen::Chat,
|
||||
);
|
||||
@@ -736,6 +756,8 @@ impl Game<'_> {
|
||||
} => {
|
||||
self.set_registries(registries);
|
||||
self.extras_joined();
|
||||
// handleLogin: the level loading screen replaces any dialog.
|
||||
self.close_dialogs();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.joined = true;
|
||||
r.profile = uuid;
|
||||
@@ -764,6 +786,8 @@ impl Game<'_> {
|
||||
}
|
||||
Event::PackPush(p) => self.handle_pack_push(p),
|
||||
Event::PackPop(id) => self.handle_pack_pop(id),
|
||||
Event::ShowDialog(dialog) => self.show_dialog(&dialog),
|
||||
Event::ClearDialog => self.clear_dialog(),
|
||||
Event::DecodeError(e) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.decode_errors += 1;
|
||||
@@ -1402,13 +1426,29 @@ impl Game<'_> {
|
||||
m.on_ground = on_ground;
|
||||
return;
|
||||
}
|
||||
if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| {
|
||||
p.id == id as u32
|
||||
&& matches!(
|
||||
p.kind,
|
||||
horizon_client::projectiles::ProjectileKind::LargeFireball { .. }
|
||||
)
|
||||
}) {
|
||||
if path.is_some() {
|
||||
p.position = Vec3::new(position[0], position[1], position[2]);
|
||||
}
|
||||
if let Some((yaw, pitch)) = rotation {
|
||||
p.yaw = yaw;
|
||||
p.pitch = pitch;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(p) = r.pending_items.get_mut(&id) {
|
||||
p.0 = position;
|
||||
}
|
||||
// ItemEntity and FallingBlockEntity keep Entity's NO_OP
|
||||
// InterpolationHandler: moveOrInterpolateTo puts them there at
|
||||
// once, and their own tick moves them on between the server's
|
||||
// updates (`tick_remote_entities`).
|
||||
// ItemEntity, FallingBlockEntity and PrimedTnt keep Entity's
|
||||
// NO_OP InterpolationHandler: moveOrInterpolateTo puts them there
|
||||
// at once, and their own tick moves them on between the server's
|
||||
// updates (`tick_remote_entities`, `tick_remote_projectiles`).
|
||||
let at = Vec3::new(position[0], position[1], position[2]);
|
||||
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
|
||||
d.position = at;
|
||||
@@ -1419,6 +1459,11 @@ impl Game<'_> {
|
||||
f.position = at;
|
||||
return;
|
||||
}
|
||||
if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id as u32) {
|
||||
t.position = at;
|
||||
t.on_ground = on_ground;
|
||||
return;
|
||||
}
|
||||
// AbstractInterpolationHandler.interpolateTo: without a rotation,
|
||||
// the one it was heading for.
|
||||
let rotation = rotation.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation));
|
||||
@@ -1612,9 +1657,10 @@ impl Game<'_> {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.sent_view = view;
|
||||
}
|
||||
self.send(S::ClientInformation(
|
||||
horizon_protocol::packets::configuration::ClientInformation::new(view),
|
||||
));
|
||||
let mut info =
|
||||
horizon_protocol::packets::configuration::ClientInformation::new(view);
|
||||
info.chat_visibility = self.settings.chat_visibility as i32;
|
||||
self.send(S::ClientInformation(info));
|
||||
}
|
||||
C::Respawn(p) => {
|
||||
// A new player, without effects: the server sends them again.
|
||||
@@ -2377,6 +2423,16 @@ impl Game<'_> {
|
||||
}
|
||||
self.merge_remote_tree();
|
||||
}
|
||||
C::Cooldown(p) => {
|
||||
// ClientPacketListener.handleItemCooldown: the server starts
|
||||
// (or confirms) a group's cooldown; 0 ends it.
|
||||
let group: Arc<str> = Arc::from(p.group.as_str());
|
||||
if p.duration == 0 {
|
||||
self.cooldowns.remove(&group);
|
||||
} else {
|
||||
self.cooldowns.add(group, p.duration);
|
||||
}
|
||||
}
|
||||
C::SystemChat(p) => {
|
||||
// The component as sent, translated in the client's own
|
||||
// language. ChatListener.handleOverlay for the action bar.
|
||||
@@ -2384,7 +2440,7 @@ impl Game<'_> {
|
||||
if p.overlay {
|
||||
self.titles.set_overlay(text, false);
|
||||
} else {
|
||||
self.chat_line(text);
|
||||
self.chat_line(text, horizon_client::chat::ChatSource::Server);
|
||||
}
|
||||
}
|
||||
C::PlayerChat(p) => {
|
||||
@@ -2394,12 +2450,12 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.map_or_else(|| serde_json::Value::from(p.content.as_str()), tag_to_json);
|
||||
let line = self.format_chat(&p.chat_type, content);
|
||||
self.chat_line(line);
|
||||
self.chat_line(line, horizon_client::chat::ChatSource::Player);
|
||||
}
|
||||
C::DisguisedChat(p) => {
|
||||
let content = horizon_client::scoreboard::tag_to_json(&p.message);
|
||||
let line = self.format_chat(&p.chat_type, content);
|
||||
self.chat_line(line);
|
||||
self.chat_line(line, horizon_client::chat::ChatSource::Player);
|
||||
}
|
||||
C::PlayerInfoUpdate(p) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
@@ -2614,6 +2670,9 @@ impl Game<'_> {
|
||||
C::SetTitleText(p) => self.titles.set_title(remote_text(&p.text)),
|
||||
C::SetSubtitleText(p) => self.titles.set_subtitle(remote_text(&p.text)),
|
||||
C::SetTitlesAnimation(p) => self.titles.set_times(p.fade_in, p.stay, p.fade_out),
|
||||
// ClientCommonPacketListenerImpl.handleShowDialog / handleClearDialog.
|
||||
C::ShowDialog(p) => self.show_play_dialog(&p.dialog),
|
||||
C::ClearDialog(_) => self.clear_dialog(),
|
||||
C::ClearTitles(p) => {
|
||||
self.titles.clear();
|
||||
if p.value {
|
||||
@@ -2912,14 +2971,23 @@ impl Game<'_> {
|
||||
});
|
||||
}
|
||||
/// `Entity.lerpMotion` (and `recreateFromPacket`'s motion) for the
|
||||
/// entities whose own tick moves them on a client: dropped items and
|
||||
/// falling blocks.
|
||||
/// entities whose own tick moves them on a client: dropped items, falling
|
||||
/// blocks and primed TNT.
|
||||
fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) {
|
||||
let v = Vec3::new(velocity[0], velocity[1], velocity[2]);
|
||||
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
|
||||
d.velocity = v;
|
||||
} else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) {
|
||||
f.velocity = v;
|
||||
} else if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id as u32) {
|
||||
t.velocity = v;
|
||||
} else if let Some(p) = self
|
||||
.creatures
|
||||
.projectiles
|
||||
.iter_mut()
|
||||
.find(|p| p.id == id as u32)
|
||||
{
|
||||
p.velocity = v;
|
||||
} else if let Some(p) = self
|
||||
.remote
|
||||
.as_mut()
|
||||
@@ -3032,16 +3100,19 @@ impl Game<'_> {
|
||||
fn tick_remote_level(&mut self) -> Result<()> {
|
||||
self.ticks += 1;
|
||||
self.track_experience_display();
|
||||
// Options.broadcastOptions: a changed render distance is sent again.
|
||||
// Options.broadcastOptions: a changed render distance or Chat option
|
||||
// is sent again.
|
||||
let view = client_view_distance(self.settings.render_distance);
|
||||
let visibility = self.settings.chat_visibility as i32;
|
||||
if let Some(r) = self.remote.as_mut()
|
||||
&& r.joined
|
||||
&& r.sent_view != view
|
||||
&& (r.sent_view != view || r.sent_chat_visibility != visibility)
|
||||
{
|
||||
r.sent_view = view;
|
||||
self.send(S::ClientInformation(
|
||||
horizon_protocol::packets::configuration::ClientInformation::new(view),
|
||||
));
|
||||
r.sent_chat_visibility = visibility;
|
||||
let mut info = horizon_protocol::packets::configuration::ClientInformation::new(view);
|
||||
info.chat_visibility = visibility;
|
||||
self.send(S::ClientInformation(info));
|
||||
}
|
||||
// Minecraft.tick: TickRateManager.tick; ClientLevel.tickTime advances
|
||||
// the time only while the level runs normally.
|
||||
@@ -3404,6 +3475,10 @@ impl Game<'_> {
|
||||
m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32;
|
||||
*steps -= 1;
|
||||
}
|
||||
// Chicken.aiStep: the wings follow the server's on-ground flag.
|
||||
if m.species() == horizon_client::mobs::Species::Chicken {
|
||||
horizon_client::mobs::farm::chicken_flap(m);
|
||||
}
|
||||
// LivingEntity.updatingUsingItem: the ticks the item has been
|
||||
// used before this one. Another player's use particles; a mob's
|
||||
// drawn bow only needs the count (its pull follows it).
|
||||
@@ -4123,8 +4198,12 @@ impl Game<'_> {
|
||||
let Some(info) = self.res.items().get(&held.item).cloned() else {
|
||||
return false;
|
||||
};
|
||||
// MultiPlayerGameMode.useItem runs the use here too: food starts
|
||||
// being eaten (Consumable.startConsuming), a book and quill opens.
|
||||
// MultiPlayerGameMode.useItem runs the use here too (inside
|
||||
// startPrediction): the `use_cooldown` component starts its entry, and
|
||||
// the server's ClientboundCooldownPacket confirms it.
|
||||
self.apply_use_cooldown(&held);
|
||||
// Food starts being eaten (Consumable.startConsuming), a book and
|
||||
// quill opens.
|
||||
self.with_hand(hand, |g| g.start_eating(&info));
|
||||
if self.with_hand(hand, |g| g.remote_use_book(&held)) {
|
||||
return true;
|
||||
@@ -4463,10 +4542,12 @@ impl Game<'_> {
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
/// ClientPacketListener.sendChat / sendCommand (unsigned).
|
||||
/// ClientPacketListener.sendChat / sendCommand (unsigned). The Chat
|
||||
/// option's Hidden and System levels keep chat out and Hidden keeps the
|
||||
/// commands out (ChatAbilities).
|
||||
pub(super) fn send_chat(&mut self, message: &str) {
|
||||
let message = message.trim();
|
||||
if message.is_empty() {
|
||||
if message.is_empty() || !self.chat_abilities().allows(message) {
|
||||
return;
|
||||
}
|
||||
if let Some(command) = message.strip_prefix('/') {
|
||||
@@ -4781,14 +4862,7 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
if let Some(kind) = Self::remote_station_kind(&menu) {
|
||||
let title = plain(
|
||||
&p.title,
|
||||
&self
|
||||
.remote
|
||||
.as_ref()
|
||||
.map(|r| r.lang.clone())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
let title = menu_title(&p.title);
|
||||
let pos = target.map_or([0, 0, 0], |t| [t.0, t.1, t.2]);
|
||||
self.remote_open_station(p.container, menu, kind, title, pos);
|
||||
return;
|
||||
@@ -4847,20 +4921,16 @@ impl Game<'_> {
|
||||
self.send(S::ContainerClose(play::ContainerClose {
|
||||
container: p.container,
|
||||
}));
|
||||
self.chat_line(horizon_client::text::Text::literal(format!(
|
||||
"(Horizon cannot show {menu} screens yet)"
|
||||
)));
|
||||
self.chat_line(
|
||||
horizon_client::text::Text::literal(format!(
|
||||
"(Horizon cannot show {menu} screens yet)"
|
||||
)),
|
||||
horizon_client::chat::ChatSource::Client,
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let title = plain(
|
||||
&p.title,
|
||||
&self
|
||||
.remote
|
||||
.as_ref()
|
||||
.map(|r| r.lang.clone())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
let title = menu_title(&p.title);
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.menu = Some((p.container, menu.clone()));
|
||||
r.menu_title = Some(title);
|
||||
@@ -4904,7 +4974,7 @@ impl Game<'_> {
|
||||
Some(self.remote.as_ref()?.menu.as_ref()?.1.as_str())
|
||||
}
|
||||
/// The title the server gave the menu it opened.
|
||||
pub(super) fn remote_menu_title(&self) -> Option<String> {
|
||||
pub(super) fn remote_menu_title(&self) -> Option<horizon_client::text::Text> {
|
||||
self.remote.as_ref()?.menu_title.clone()
|
||||
}
|
||||
/// A language change reaches the server-sent components too: their titles
|
||||
@@ -4917,7 +4987,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// A server's chest-like menu (`MenuType.GENERIC_9xN`): its rows and title.
|
||||
pub(super) fn remote_chest_menu(&self) -> Option<(usize, String)> {
|
||||
pub(super) fn remote_chest_menu(&self) -> Option<(usize, horizon_client::text::Text)> {
|
||||
let r = self.remote.as_ref()?;
|
||||
let rows = r
|
||||
.menu
|
||||
@@ -4926,7 +4996,12 @@ impl Game<'_> {
|
||||
.strip_prefix("minecraft:generic_9x")?
|
||||
.parse()
|
||||
.ok()?;
|
||||
Some((rows, r.menu_title.clone().unwrap_or_default()))
|
||||
Some((
|
||||
rows,
|
||||
r.menu_title
|
||||
.clone()
|
||||
.unwrap_or_else(horizon_client::text::Text::empty),
|
||||
))
|
||||
}
|
||||
/// ServerboundPlayerCommandPacket STOP_SLEEPING.
|
||||
pub(super) fn remote_stop_sleeping(&mut self) {
|
||||
|
||||
@@ -220,10 +220,21 @@ impl Game<'_> {
|
||||
|
||||
/// One tick of interpolation, as `tick_remote_objects`.
|
||||
pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
|
||||
for t in &mut self.tnts {
|
||||
t.previous = t.position;
|
||||
t.position = step(t.id, t.position);
|
||||
}
|
||||
// PrimedTnt.tick runs on a client too: it falls, bounces and burns its
|
||||
// fuse down (the swell and flash follow it) between the server's
|
||||
// updates (every 10 ticks), and a client discards it when the fuse
|
||||
// runs out; only the server explodes it.
|
||||
let (world, collision, assets, facts) = (
|
||||
&self.world,
|
||||
self.collision,
|
||||
&self.pack.assets,
|
||||
self.res.facts(),
|
||||
);
|
||||
self.tnts.retain_mut(|t| {
|
||||
// A fluid lookup that fails leaves it where its move put it.
|
||||
let _ = t.tick(world, collision, assets, facts);
|
||||
t.fuse > 0
|
||||
});
|
||||
// FallingBlockEntity.tick runs on a client too: the block falls by
|
||||
// itself between the server's updates (every 20 ticks), then waits
|
||||
// where it lands for the server to place it and remove it.
|
||||
@@ -238,7 +249,25 @@ impl Game<'_> {
|
||||
for p in &mut self.creatures.projectiles {
|
||||
p.previous = p.position;
|
||||
p.age += 1;
|
||||
p.position = step(p.id, p.position);
|
||||
if matches!(p.kind, ProjectileKind::LargeFireball { .. }) {
|
||||
// AbstractHurtingProjectile.tick advances on the client between
|
||||
// the tracker updates (ten ticks apart for a ghast's fireball).
|
||||
let at = p.position;
|
||||
let water = self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(
|
||||
at.x.floor() as i32,
|
||||
at.y.floor() as i32,
|
||||
at.z.floor() as i32,
|
||||
))
|
||||
.fluid
|
||||
== horizon_client::blocks::Fluid::Water;
|
||||
p.apply_hurting_inertia(water);
|
||||
p.position = p.position.add_vector(p.velocity);
|
||||
} else {
|
||||
p.position = step(p.id, p.position);
|
||||
}
|
||||
}
|
||||
for t in &mut self.tridents {
|
||||
let id = t.id;
|
||||
|
||||
@@ -18,7 +18,7 @@ impl Game<'_> {
|
||||
container: i32,
|
||||
menu: String,
|
||||
kind: Kind,
|
||||
title: String,
|
||||
title: horizon_client::text::Text,
|
||||
pos: [i32; 3],
|
||||
) {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
|
||||
@@ -63,6 +63,12 @@ struct Steps {
|
||||
on_ground: bool,
|
||||
in_water: bool,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct PlayerEvents {
|
||||
steps: Option<Steps>,
|
||||
last_health: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SculkState {
|
||||
/// The player's warning level toward a warden.
|
||||
@@ -86,6 +92,15 @@ pub(super) struct SculkState {
|
||||
}
|
||||
|
||||
impl SculkState {
|
||||
pub(super) fn swap_player(&mut self, other: &mut PlayerEvents) {
|
||||
let steps = self.steps.remove(&Who::Player);
|
||||
if let Some(guest) = other.steps.take() {
|
||||
self.steps.insert(Who::Player, guest);
|
||||
}
|
||||
other.steps = steps;
|
||||
std::mem::swap(&mut self.last_health, &mut other.last_health);
|
||||
}
|
||||
|
||||
/// Exchange the level-held parts (its sculk block entities and the
|
||||
/// chunks scanned for them) with another level's (game/levels.rs).
|
||||
pub(super) fn swap_level(&mut self, other: &mut Self) {
|
||||
@@ -1498,6 +1513,12 @@ impl Game<'_> {
|
||||
/// Events from entities moving, getting hurt and dying, derived from what
|
||||
/// changed this tick.
|
||||
fn tick_entity_events(&mut self) {
|
||||
self.tick_player_sculk_events();
|
||||
self.tick_mob_sculk_events();
|
||||
}
|
||||
|
||||
/// Entity.move emits on the authoritative server too, for each ServerPlayer.
|
||||
pub(super) fn tick_player_sculk_events(&mut self) {
|
||||
// The player.
|
||||
let player = self.player.as_ref().map(|p| {
|
||||
(
|
||||
@@ -1525,7 +1546,9 @@ impl Game<'_> {
|
||||
}
|
||||
self.sculk.last_health = Some(health);
|
||||
}
|
||||
// Mobs.
|
||||
}
|
||||
|
||||
fn tick_mob_sculk_events(&mut self) {
|
||||
let snapshot: Vec<(u32, [f64; 3], bool, bool, Species, Option<i64>)> = self
|
||||
.mobs
|
||||
.iter()
|
||||
|
||||
@@ -232,6 +232,32 @@ impl Game<'_> {
|
||||
.unwrap_or(ids.missing_block)
|
||||
});
|
||||
self.push_span(start, "BLOCK_ENTITIES", id);
|
||||
let emission = self
|
||||
.res
|
||||
.facts()
|
||||
.get(horizon_world::registry::BlockStateId(state))
|
||||
.emission;
|
||||
if let Some(last) = self.entity_spans.borrow_mut().last_mut() {
|
||||
last.emissive = emission > 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the span of the local player's model; `hidden` in first person, where only a
|
||||
/// pack's shadow pass draws it.
|
||||
pub(super) fn mark_player(&self, start: usize, hidden: bool) {
|
||||
self.mark_entity(start, "minecraft:player");
|
||||
if self.pack_ids.is_some()
|
||||
&& let Some(last) = self.entity_spans.borrow_mut().last_mut()
|
||||
{
|
||||
last.player = true;
|
||||
last.hidden = hidden;
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks vertices `start..end` (one entity) as hidden from the camera, for an entity
|
||||
/// Horizon's culling would drop but a pack's shadow pass still draws (`EntitySpan::hide`).
|
||||
pub(super) fn hide_spans_from(&self, start: usize, end: usize) -> bool {
|
||||
EntitySpan::hide(&mut self.entity_spans.borrow_mut(), start, end)
|
||||
}
|
||||
|
||||
/// Starts a span of geometry that is not an entity (`PARTICLES`, `DESTROY`...).
|
||||
@@ -247,7 +273,7 @@ impl Game<'_> {
|
||||
start: start as u32,
|
||||
stage: horizon_shaders::render_stage(stage),
|
||||
id,
|
||||
translucent: false,
|
||||
..Default::default()
|
||||
};
|
||||
// A span that drew nothing gives way to the next.
|
||||
match spans.last_mut() {
|
||||
|
||||
@@ -11,6 +11,7 @@ use horizon_client::{
|
||||
hud::{HudBatch, rgba},
|
||||
items::ItemStack,
|
||||
stations::{self, AnvilResult, EnchantOffers},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
|
||||
@@ -1160,15 +1161,15 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
let default = self.translate("container.brewing", "Brewing Stand");
|
||||
let title = self
|
||||
.station
|
||||
.as_ref()
|
||||
.and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2])))
|
||||
.cloned()
|
||||
.or_else(|| self.remote_menu_title())
|
||||
.unwrap_or(default);
|
||||
let tw = HudBatch::text_width(atlas, &title);
|
||||
batch.text(
|
||||
let title = self.remote_menu_title().unwrap_or_else(|| {
|
||||
let named = self
|
||||
.station
|
||||
.as_ref()
|
||||
.and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2])));
|
||||
Text::literal(named.cloned().unwrap_or(default)).resolve_legacy()
|
||||
});
|
||||
let tw = atlas.font.width_text(&title);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&title,
|
||||
ox + (176.0 - tw) / 2.0,
|
||||
@@ -1195,7 +1196,10 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
} else if let Some(kind) = self.station.as_ref().map(|s| s.kind) {
|
||||
let title = self.translate(kind.title_key(), "");
|
||||
// A server's menu has the title it was given.
|
||||
let title = self
|
||||
.remote_menu_title()
|
||||
.unwrap_or_else(|| Text::literal(self.translate(kind.title_key(), "")));
|
||||
{
|
||||
let atlas = &self.gui.atlas;
|
||||
Self::part(
|
||||
@@ -1207,7 +1211,7 @@ impl Game<'_> {
|
||||
(ox, oy),
|
||||
);
|
||||
let (tx, ty) = kind.title_pos();
|
||||
batch.text(atlas, &title, ox + tx, oy + ty, GREY, false);
|
||||
batch.text_styled(atlas, &title, ox + tx, oy + ty, GREY, false);
|
||||
batch.text(atlas, &inventory_label, ox + 8.0, oy + 72.0, GREY, false);
|
||||
}
|
||||
if kind == Kind::Cartography {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! kept in the dropped item's `container` component) and ender chests (the
|
||||
//! player's `PlayerEnderChestContainer`, saved as `EnderItems`).
|
||||
use super::Game;
|
||||
use horizon_client::{containers::BlockEntity, items::ItemStack};
|
||||
use horizon_client::{containers::BlockEntity, items::ItemStack, text::Text};
|
||||
|
||||
pub(super) fn is_shulker_box(name: &str) -> bool {
|
||||
name.ends_with("shulker_box")
|
||||
@@ -233,7 +233,7 @@ impl Game<'_> {
|
||||
generic.then(|| self.container_size() / 9)
|
||||
}
|
||||
/// The title of the open chest-like menu.
|
||||
fn chest_title(&self, rows: usize) -> String {
|
||||
fn chest_title(&self, rows: usize) -> Text {
|
||||
if let Some((_, title)) = self.remote_chest_menu() {
|
||||
return title;
|
||||
}
|
||||
@@ -246,7 +246,7 @@ impl Game<'_> {
|
||||
_ if rows > 3 => ("container.chestDouble", "Large Chest"),
|
||||
_ => ("container.chest", "Chest"),
|
||||
};
|
||||
self.container_title(self.translate(key, fallback))
|
||||
Text::literal(self.container_title(self.translate(key, fallback))).resolve_legacy()
|
||||
}
|
||||
/// `ContainerScreen` / `ShulkerBoxScreen`: the background with its
|
||||
/// container rows, the title and the inventory label.
|
||||
@@ -294,7 +294,7 @@ impl Game<'_> {
|
||||
r.u1 = r.u0 + 176.0 * du;
|
||||
batch.rect_uv(ox, oy + top, 176.0, 96.0, r, u32::MAX);
|
||||
}
|
||||
batch.text(
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&self.chest_title(rows),
|
||||
ox + 8.0,
|
||||
|
||||
@@ -33,7 +33,7 @@ impl PrimedTnt {
|
||||
),
|
||||
)
|
||||
}
|
||||
fn tick(
|
||||
pub(super) fn tick(
|
||||
&mut self,
|
||||
world: &horizon_client::world::World,
|
||||
collision: &horizon_world::block_collision::BlockCollisionRegistry<'_>,
|
||||
|
||||
@@ -52,10 +52,6 @@ fn triggers(name: &str) -> bool {
|
||||
impl Game<'_> {
|
||||
/// `WindChargeItem.use`.
|
||||
pub(super) fn throw_wind_charge(&mut self) -> Result<bool> {
|
||||
if self.creatures.wind_cooldown > 0 {
|
||||
return Ok(true);
|
||||
}
|
||||
self.creatures.wind_cooldown = 10;
|
||||
let (Some(eye), Some(p)) = (self.eye_position(), self.player.as_ref()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
@@ -73,6 +73,7 @@ pub mod pack_draw;
|
||||
mod pack_entities;
|
||||
mod pack_hand;
|
||||
mod pack_post;
|
||||
mod pack_shadow;
|
||||
mod pack_sky;
|
||||
mod pack_timing;
|
||||
pub mod pack_uniforms;
|
||||
@@ -470,6 +471,8 @@ pub struct Renderer {
|
||||
/// Per-frame scratch, kept to avoid allocating every frame.
|
||||
visible: Vec<resident::Visible>,
|
||||
visible_lods: Vec<lod::Visible>,
|
||||
/// The sections a shader pack's shadow camera sees (`pack_post::ShadowView`).
|
||||
shadow_visible: Vec<resident::Visible>,
|
||||
translucent_draws: Vec<(u64, usize, [u32; 5], (u32, Option<u32>))>,
|
||||
origins: Vec<[f32; 4]>,
|
||||
/// `DrawIndexedIndirectArgs` words: index count, instance count, first
|
||||
@@ -484,6 +487,8 @@ pub struct Renderer {
|
||||
/// Each section's solid draws, to group them by arena page.
|
||||
solid_runs: page_runs::PageRuns,
|
||||
phase2_runs: page_runs::PageRuns,
|
||||
/// The shadow camera's draws by page, in bands of distance from the light.
|
||||
shadow_runs: page_runs::PageRuns,
|
||||
/// Block-entity blocks per meshed section (world position, state id).
|
||||
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
|
||||
/// Changes whenever `block_entities` does (unique across renderers).
|
||||
@@ -2389,6 +2394,7 @@ impl Renderer {
|
||||
multi_draw,
|
||||
visible: Vec::new(),
|
||||
visible_lods: Vec::new(),
|
||||
shadow_visible: Vec::new(),
|
||||
translucent_draws: Vec::new(),
|
||||
origins: Vec::new(),
|
||||
draws: Vec::new(),
|
||||
@@ -2397,6 +2403,7 @@ impl Renderer {
|
||||
phase2_pages: Vec::new(),
|
||||
solid_runs: page_runs::PageRuns::default(),
|
||||
phase2_runs: page_runs::PageRuns::default(),
|
||||
shadow_runs: page_runs::PageRuns::default(),
|
||||
block_entities: HashMap::new(),
|
||||
block_entity_revision: next_block_entity_revision(),
|
||||
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
|
||||
@@ -2592,6 +2599,18 @@ impl Renderer {
|
||||
pub fn section_count(&self) -> usize {
|
||||
self.sections.len()
|
||||
}
|
||||
/// What a shader pack's shadow pass draws of the entities this frame: (entities or block
|
||||
/// entities other than the player, so those Horizon's culling hides from the camera are
|
||||
/// kept for it; the local player, so its model is built in first person too). (false,
|
||||
/// false) without a pack or its shadow pass.
|
||||
pub fn pack_shadow_casters(&self) -> (bool, bool) {
|
||||
let Some((_, Some(post))) = &self.pack_post else {
|
||||
return (false, false);
|
||||
};
|
||||
let c = post.shadow_casters();
|
||||
((c.entities && !c.only_player) || c.blocks, c.entities)
|
||||
}
|
||||
|
||||
pub fn has_section(&self, key: SectionKey) -> bool {
|
||||
self.sections.contains(key)
|
||||
}
|
||||
@@ -3313,8 +3332,43 @@ impl Renderer {
|
||||
);
|
||||
visible_lods.sort_unstable_by_key(|v| (v.distance, v.key));
|
||||
}
|
||||
// A shader pack's shadow pass draws the sections in its camera's box, all of them (the
|
||||
// occlusion graph follows the eye, not the light), within shadowDistanceRenderMul.
|
||||
let shadow_view = self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.filter(|_| !frame.title)
|
||||
.and_then(|p| p.shadow_view(frame));
|
||||
let mut shadow_visible = std::mem::take(&mut self.shadow_visible);
|
||||
shadow_visible.clear();
|
||||
if let Some(v) = &shadow_view {
|
||||
let radius = (frame.detail_distance / 16.0) as i32;
|
||||
let radius = v
|
||||
.distance
|
||||
.map_or(radius, |d| radius.min((d / 16.0).ceil() as i32));
|
||||
let light = Frustum {
|
||||
planes: frustum(v.cull),
|
||||
};
|
||||
crate::spans::time("shadow visibility", || {
|
||||
self.sections.visible(
|
||||
camera,
|
||||
radius,
|
||||
&light,
|
||||
|_| true,
|
||||
|_, _| false,
|
||||
&mut shadow_visible,
|
||||
)
|
||||
});
|
||||
// Nearest the light first, so the depth test rejects what lies under it.
|
||||
let light = v.light;
|
||||
shadow_visible.sort_unstable_by(|a, b| {
|
||||
let height = |s: &resident::Visible| glam::Vec3::from(s.origin).dot(light);
|
||||
height(b).total_cmp(&height(a))
|
||||
});
|
||||
}
|
||||
self.drawn_sections = visible.len() + visible_lods.len();
|
||||
let instances = self.drawn_sections;
|
||||
let instances = self.drawn_sections + shadow_visible.len();
|
||||
if instances as u64 > self.instance_capacity {
|
||||
self.instance_capacity = (instances as u64).next_power_of_two();
|
||||
self.instances = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
@@ -3331,7 +3385,8 @@ impl Renderer {
|
||||
visible
|
||||
.iter()
|
||||
.map(|v| section_instance(v.origin))
|
||||
.chain(visible_lods.iter().map(|v| lod::instance(v.origin))),
|
||||
.chain(visible_lods.iter().map(|v| lod::instance(v.origin)))
|
||||
.chain(shadow_visible.iter().map(|v| section_instance(v.origin))),
|
||||
);
|
||||
if !self.origins.is_empty() {
|
||||
self.uploads.buffer(
|
||||
@@ -3535,9 +3590,87 @@ impl Renderer {
|
||||
self.translucency_cursor += budget;
|
||||
let translucent_draws = self.draws.len() as u32 - solid_draws;
|
||||
self.section_draws = self.draws.len();
|
||||
// The shadow camera's sections after the camera's: quads that can face the light, then
|
||||
// translucent ones (in their last sorted order; depth decides there).
|
||||
let shadow_first = self.draws.len() as u32;
|
||||
let mut shadow_translucent = Vec::new();
|
||||
self.shadow_runs.clear();
|
||||
if let Some(view) = &shadow_view {
|
||||
let base = self.drawn_sections;
|
||||
let toward = view.light * 1.0e5;
|
||||
// How far below the nearest section to the light (squared, as bits, as `PageRuns`
|
||||
// takes distances): each band's draws go by page, a call per page and band.
|
||||
let height = |v: &resident::Visible| glam::Vec3::from(v.origin).dot(view.light);
|
||||
let top = shadow_visible.first().map_or(0.0, height);
|
||||
for (k, v) in shadow_visible.iter().enumerate() {
|
||||
let s = self.sections.get_mut(v.slot);
|
||||
let instance = (base + k) as u32;
|
||||
let depth = f64::from(top - height(v)).max(0.0);
|
||||
let distance = (depth * depth).to_bits();
|
||||
// A section the camera never saw has no sorted indices yet: sorted once now.
|
||||
if let Some((index_page, index_start)) = s.sorted_indices
|
||||
&& !s.sort.is_sorted()
|
||||
{
|
||||
let origin = [
|
||||
v.key.0 * 16,
|
||||
crate::chunk::MIN_Y + v.key.1 * 16,
|
||||
v.key.2 * 16,
|
||||
];
|
||||
if let Some(indices) =
|
||||
s.sort
|
||||
.update(camera.to_array(), origin, &mut self.translucent_sorter)
|
||||
{
|
||||
self.uploads.buffer(
|
||||
&mut encoder,
|
||||
self.sorted_indices.buffer(index_page),
|
||||
index_start * 4,
|
||||
bytemuck::cast_slice(indices),
|
||||
);
|
||||
}
|
||||
}
|
||||
let before = self.draws.len();
|
||||
facing_runs(&s.sides, Some(toward), v.origin, |first, quads| {
|
||||
let start = s.start as u32 + first * 4;
|
||||
self.draws.push([quads * 6, 1, 0, start, instance]);
|
||||
self.draw_pages.push((s.page, None));
|
||||
});
|
||||
let len = self.draws.len() - before;
|
||||
self.shadow_runs.push(distance, s.page, before, len, [0; 3]);
|
||||
if let Some((index_page, index_start)) = s.sorted_indices {
|
||||
let start = s.start + u64::from(s.solid) * 4;
|
||||
shadow_translucent.push((
|
||||
distance,
|
||||
[
|
||||
s.translucent * 6,
|
||||
1,
|
||||
index_start as u32,
|
||||
start as u32,
|
||||
instance,
|
||||
],
|
||||
(s.page, Some(index_page)),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let shadow_solid = self.draws.len() as u32 - shadow_first;
|
||||
self.shadow_runs
|
||||
.regroup(&mut self.draws, &mut self.draw_pages, shadow_first as usize);
|
||||
self.shadow_runs.clear();
|
||||
for (distance, draw, pages) in shadow_translucent {
|
||||
self.shadow_runs
|
||||
.push(distance, pages.0, self.draws.len(), 1, [0; 3]);
|
||||
self.draws.push(draw);
|
||||
self.draw_pages.push(pages);
|
||||
}
|
||||
self.shadow_runs.regroup(
|
||||
&mut self.draws,
|
||||
&mut self.draw_pages,
|
||||
(shadow_first + shadow_solid) as usize,
|
||||
);
|
||||
let shadow_translucent = self.draws.len() as u32 - shadow_first - shadow_solid;
|
||||
// Metal replays a multi-draw as one draw call per entry.
|
||||
self.section_draw_calls = if self.multi_draw && self.info.backend != wgpu::Backend::Metal {
|
||||
(0..self.draws.len())
|
||||
(0..self.section_draws)
|
||||
.filter(|&i| {
|
||||
i == 0
|
||||
|| i == phase1_draws as usize
|
||||
@@ -3546,7 +3679,7 @@ impl Renderer {
|
||||
})
|
||||
.count()
|
||||
} else {
|
||||
self.draws.len()
|
||||
self.section_draws
|
||||
};
|
||||
let debug_depth = frame.debug_lines.len() as u32;
|
||||
let debug_top = frame.debug_lines_on_top.len() as u32;
|
||||
@@ -3783,7 +3916,9 @@ impl Renderer {
|
||||
Some(flat)
|
||||
if self.flat_on
|
||||
&& !self.draws.is_empty()
|
||||
&& (self.drawn_sections >= flat.min_sections || pack_terrain) =>
|
||||
&& (self.drawn_sections >= flat.min_sections
|
||||
|| pack_terrain
|
||||
|| shadow_view.is_some()) =>
|
||||
{
|
||||
let sections = &self.sections;
|
||||
let lods = &self.lods;
|
||||
@@ -3798,9 +3933,11 @@ impl Renderer {
|
||||
&self.draw_pages,
|
||||
phase1_draws as usize,
|
||||
solid_draws as usize,
|
||||
[shadow_first, shadow_first + shadow_solid].map(|d| d as usize),
|
||||
phase2,
|
||||
visible
|
||||
.iter()
|
||||
.chain(&shadow_visible)
|
||||
.filter_map(|v| {
|
||||
let id = sections.get(v.slot).flat_id?;
|
||||
Some((id, section_instance(v.origin)))
|
||||
@@ -3816,7 +3953,7 @@ impl Renderer {
|
||||
_ => false,
|
||||
};
|
||||
if flat_frame {
|
||||
self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.calls.len());
|
||||
self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.shadow_calls[0]);
|
||||
} else if self.multi_draw && !self.draws.is_empty() {
|
||||
if self.draws.len() as u64 > self.indirect_capacity {
|
||||
self.indirect_capacity = (self.draws.len() as u64).next_power_of_two();
|
||||
@@ -3845,6 +3982,8 @@ impl Renderer {
|
||||
let pack_post = !frame.title && self.pack_post.as_ref().is_some_and(|p| p.1.is_some());
|
||||
// The pack's program reads the vertices this frame's draws bind.
|
||||
let pack_draws_terrain = pack_terrain && flat_frame == self.pack_terrain_flat;
|
||||
// The shadow camera's lists, drawn by the pack's shadow programs.
|
||||
let pack_draws_shadow = shadow_view.is_some() && flat_frame == self.pack_terrain_flat;
|
||||
let pack_draws_sky = pack_post
|
||||
&& self
|
||||
.pack_post
|
||||
@@ -4114,7 +4253,7 @@ impl Renderer {
|
||||
_ if pack_draws_water => {}
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.translucent);
|
||||
flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| {
|
||||
flat.draw(&mut pass, flat.translucent_calls(), |p| {
|
||||
self.arena.buffer(p)
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
@@ -4221,7 +4360,7 @@ impl Renderer {
|
||||
post.set_weather(weather);
|
||||
let flat = self.flat.as_ref().filter(|_| flat_frame);
|
||||
let pages: Vec<(u32, wgpu::Buffer)> = match flat {
|
||||
Some(_) if pack_draws_terrain => self
|
||||
Some(_) if pack_draws_terrain || pack_draws_shadow => self
|
||||
.arena
|
||||
.page_buffers()
|
||||
.map(|(p, b)| (p, b.clone()))
|
||||
@@ -4230,27 +4369,38 @@ impl Renderer {
|
||||
};
|
||||
let mut terrain =
|
||||
|rp: &mut wgpu::RenderPass<'_>,
|
||||
translucent: bool,
|
||||
list: pack_post::TerrainList,
|
||||
page: &dyn Fn(&mut wgpu::RenderPass<'_>, u32)| {
|
||||
if !pack_draws_terrain {
|
||||
use pack_post::TerrainList as L;
|
||||
let shadow = matches!(list, L::ShadowSolid | L::ShadowTranslucent);
|
||||
if !(if shadow {
|
||||
pack_draws_shadow
|
||||
} else {
|
||||
pack_draws_terrain
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
match flat {
|
||||
Some(flat) => {
|
||||
let calls = if translucent {
|
||||
&flat.calls[flat.solid_calls..]
|
||||
} else {
|
||||
&flat.calls[..flat.solid_calls]
|
||||
let [shadow, shadow_translucent] = flat.shadow_calls;
|
||||
let calls = match list {
|
||||
L::Solid => &flat.calls[..flat.solid_calls],
|
||||
L::Translucent => flat.translucent_calls(),
|
||||
L::ShadowSolid => &flat.calls[shadow..shadow_translucent],
|
||||
L::ShadowTranslucent => &flat.calls[shadow_translucent..],
|
||||
};
|
||||
flat.draw_with(rp, calls, |p| self.arena.buffer(p), page);
|
||||
}
|
||||
None => {
|
||||
rp.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
rp.set_vertex_buffer(1, self.instances.slice(..));
|
||||
let (first, count) = if translucent {
|
||||
(solid_draws, translucent_draws)
|
||||
} else {
|
||||
(0, solid_draws)
|
||||
let (first, count) = match list {
|
||||
L::Solid => (0, solid_draws),
|
||||
L::Translucent => (solid_draws, translucent_draws),
|
||||
L::ShadowSolid => (shadow_first, shadow_solid),
|
||||
L::ShadowTranslucent => {
|
||||
(shadow_first + shadow_solid, shadow_translucent)
|
||||
}
|
||||
};
|
||||
self.draw_sections(rp, &self.indirect, 0, first, count);
|
||||
}
|
||||
@@ -4485,6 +4635,7 @@ impl Renderer {
|
||||
let _ = self.started;
|
||||
self.visible = visible;
|
||||
self.visible_lods = visible_lods;
|
||||
self.shadow_visible = shadow_visible;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,8 @@ enum Source {
|
||||
struct Plan {
|
||||
phase1_calls: usize,
|
||||
solid_calls: usize,
|
||||
/// Where the shadow camera's solid and translucent calls begin.
|
||||
shadow_calls: [usize; 2],
|
||||
total: u64,
|
||||
}
|
||||
const QUADS: u32 = u32::MAX;
|
||||
@@ -97,6 +99,10 @@ pub struct Flat {
|
||||
pub calls: Vec<Call>,
|
||||
pub phase1_calls: usize,
|
||||
pub solid_calls: usize,
|
||||
/// Where a shader pack's shadow camera's solid and translucent calls
|
||||
/// begin (`calls.len()` without them): the camera's translucent calls
|
||||
/// end at the first.
|
||||
pub shadow_calls: [usize; 2],
|
||||
/// Frames with fewer sections in view keep the per-section draws.
|
||||
pub min_sections: usize,
|
||||
range_align: u64,
|
||||
@@ -164,12 +170,16 @@ fn buffer(
|
||||
/// draw calls, one per run of draws in the same vertex page, phase 1's solid
|
||||
/// ones, phase 2's (draws `phase1_draws..solid_draws`) and translucent ones
|
||||
/// apart. A phase 2 range names its draw in phase 2 and its call in phase 2
|
||||
/// instead of a destination: the call's room holds all of its draws.
|
||||
/// instead of a destination: the call's room holds all of its draws. Draws
|
||||
/// from `shadow[0]` (solid) and `shadow[1]` (translucent) on are a shader
|
||||
/// pack's shadow camera's, with calls of their own.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn plan(
|
||||
draws: &[[u32; 5]],
|
||||
pages: &[(u32, Option<u32>)],
|
||||
phase1_draws: usize,
|
||||
solid_draws: usize,
|
||||
shadow: [usize; 2],
|
||||
align: u64,
|
||||
calls: &mut Vec<Call>,
|
||||
ranges: &mut Vec<Range>,
|
||||
@@ -179,6 +189,7 @@ fn plan(
|
||||
ranges.clear();
|
||||
segments.clear();
|
||||
let (mut phase1_calls, mut solid_calls) = (None, None);
|
||||
let mut shadow_calls = [None; 2];
|
||||
let mut total = 0u64;
|
||||
let mut by_source: Vec<(Source, Vec<Range>)> = Vec::new();
|
||||
for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() {
|
||||
@@ -188,10 +199,14 @@ fn plan(
|
||||
if i == solid_draws {
|
||||
solid_calls = Some(calls.len());
|
||||
}
|
||||
match calls.last_mut() {
|
||||
Some(last) if last.page == page && i != phase1_draws && i != solid_draws => {
|
||||
last.count += d[0]
|
||||
for (k, &from) in shadow.iter().enumerate() {
|
||||
if i == from {
|
||||
shadow_calls[k].get_or_insert(calls.len());
|
||||
}
|
||||
}
|
||||
let starts = i == phase1_draws || i == solid_draws || shadow.contains(&i);
|
||||
match calls.last_mut() {
|
||||
Some(last) if last.page == page && !starts => last.count += d[0],
|
||||
_ => calls.push(Call {
|
||||
page,
|
||||
first: total as u32,
|
||||
@@ -227,6 +242,7 @@ fn plan(
|
||||
Plan {
|
||||
phase1_calls: phase1_calls.unwrap_or(calls.len()).min(solid_calls),
|
||||
solid_calls,
|
||||
shadow_calls: shadow_calls.map(|c| c.unwrap_or(calls.len())),
|
||||
total,
|
||||
}
|
||||
}
|
||||
@@ -340,6 +356,7 @@ impl Flat {
|
||||
calls: Vec::new(),
|
||||
phase1_calls: 0,
|
||||
solid_calls: 0,
|
||||
shadow_calls: [0; 2],
|
||||
min_sections: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") {
|
||||
0
|
||||
} else {
|
||||
@@ -412,6 +429,7 @@ impl Flat {
|
||||
///
|
||||
/// When culling, the solid draws from `phase1_draws` are phase 2's, which
|
||||
/// `phase2` holds as the test leaves them: `flatten_phase2` copies them.
|
||||
/// Draws from `shadow` on are a shader pack's shadow camera's (`plan`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
@@ -422,6 +440,7 @@ impl Flat {
|
||||
pages: &[(u32, Option<u32>)],
|
||||
phase1_draws: usize,
|
||||
solid_draws: usize,
|
||||
shadow: [usize; 2],
|
||||
phase2: Option<&wgpu::Buffer>,
|
||||
origins: impl Iterator<Item = (u32, [f32; 4])>,
|
||||
sorted_page: impl Fn(u32) -> wgpu::Buffer,
|
||||
@@ -464,12 +483,14 @@ impl Flat {
|
||||
let Plan {
|
||||
phase1_calls,
|
||||
solid_calls,
|
||||
shadow_calls,
|
||||
total,
|
||||
} = plan(
|
||||
draws,
|
||||
pages,
|
||||
phase1_draws,
|
||||
solid_draws,
|
||||
shadow,
|
||||
self.range_align,
|
||||
&mut self.calls,
|
||||
&mut self.range_data,
|
||||
@@ -477,10 +498,12 @@ impl Flat {
|
||||
);
|
||||
self.phase1_calls = phase1_calls;
|
||||
self.solid_calls = solid_calls;
|
||||
self.shadow_calls = shadow_calls;
|
||||
if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {
|
||||
self.calls.clear();
|
||||
self.phase1_calls = 0;
|
||||
self.solid_calls = 0;
|
||||
self.shadow_calls = [0; 2];
|
||||
return false;
|
||||
}
|
||||
if self.range_data.len() as u64 > self.range_capacity {
|
||||
@@ -644,6 +667,11 @@ impl Flat {
|
||||
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
|
||||
}
|
||||
|
||||
/// The camera's translucent calls.
|
||||
pub fn translucent_calls(&self) -> &[Call] {
|
||||
&self.calls[self.solid_calls..self.shadow_calls[0]]
|
||||
}
|
||||
|
||||
/// Draws `calls` with a flat pipeline set and `vertices` giving each
|
||||
/// page's vertex buffer.
|
||||
pub fn draw<'a>(
|
||||
@@ -735,11 +763,13 @@ mod tests {
|
||||
phase1_calls,
|
||||
solid_calls,
|
||||
total,
|
||||
..
|
||||
} = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
solid,
|
||||
[draws.len(); 2],
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
@@ -774,6 +804,35 @@ mod tests {
|
||||
assert_eq!(ranges.len(), 12);
|
||||
}
|
||||
|
||||
/// A shader pack's shadow draws follow the camera's, in calls of their
|
||||
/// own even from the same page: solid ones, then translucent ones.
|
||||
#[test]
|
||||
fn plan_gives_the_shadow_lists_calls_of_their_own() {
|
||||
let (mut draws, mut pages, solid) = sample();
|
||||
let camera = draws.len();
|
||||
draws.extend([[6, 1, 0, 40, 6], [6 * 2, 1, 0, 64, 7], [6, 1, 6, 80, 7]]);
|
||||
pages.extend([(0, None), (0, None), (0, Some(0))]);
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let plan = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
solid,
|
||||
[camera, camera + 2],
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
assert_eq!((plan.solid_calls, plan.shadow_calls), (3, [4, 5]));
|
||||
let call = |page, first, count| Call { page, first, count };
|
||||
assert_eq!(
|
||||
&calls[3..],
|
||||
[call(0, 60, 18), call(0, 78, 18), call(0, 96, 6)]
|
||||
);
|
||||
assert_eq!(plan.total, 6 * 17);
|
||||
}
|
||||
|
||||
/// Phase 2's draws (here the third and fourth) get calls of their own,
|
||||
/// each with room for all of its draws, and ranges naming their draw
|
||||
/// and call in phase 2.
|
||||
@@ -786,6 +845,7 @@ mod tests {
|
||||
&pages,
|
||||
2,
|
||||
solid,
|
||||
[draws.len(); 2],
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
@@ -796,6 +856,7 @@ mod tests {
|
||||
Plan {
|
||||
phase1_calls: 1,
|
||||
solid_calls: 3,
|
||||
shadow_calls: [4, 4],
|
||||
total: 6 * 13
|
||||
}
|
||||
);
|
||||
@@ -899,6 +960,7 @@ mod tests {
|
||||
&pages,
|
||||
phase1,
|
||||
solid,
|
||||
[draws.len(); 2],
|
||||
align,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
|
||||
@@ -7,7 +7,7 @@ use horizon_shaders::{RENDER_STAGES, render_stage};
|
||||
/// Where a run of `Frame::entities` begins, and what it is (slice 7): the run lasts until the
|
||||
/// next span. Recorded only while a shader pack draws entities, so Horizon's own frames carry
|
||||
/// none; Horizon itself still draws the whole list at once.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct EntitySpan {
|
||||
/// The first vertex.
|
||||
pub start: u32,
|
||||
@@ -18,6 +18,44 @@ pub struct EntitySpan {
|
||||
pub id: i32,
|
||||
/// An entity part that blends (a name tag, a shadow): `gbuffers_entities_translucent`.
|
||||
pub translucent: bool,
|
||||
/// Hidden from the camera (Horizon's entity culling, the player in first person): only the
|
||||
/// shadow pass draws it.
|
||||
pub hidden: bool,
|
||||
/// The local player (`shadowPlayer`).
|
||||
pub player: bool,
|
||||
/// A block entity whose block emits light (`shadowLightBlockEntities`).
|
||||
pub emissive: bool,
|
||||
}
|
||||
|
||||
impl EntitySpan {
|
||||
/// Marks vertices `start..end` of `spans`' list (one entity) as hidden: the span covering
|
||||
/// `start` is split there, the spans inside are hidden, and the geometry after `end` goes
|
||||
/// on in the last span's kind. False when no span covers `start`.
|
||||
pub fn hide(spans: &mut Vec<EntitySpan>, start: usize, end: usize) -> bool {
|
||||
let Some(i) = spans.iter().rposition(|s| s.start as usize <= start) else {
|
||||
return false;
|
||||
};
|
||||
let after = spans[spans.len() - 1];
|
||||
if spans[i].start as usize != start {
|
||||
let split = EntitySpan {
|
||||
start: start as u32,
|
||||
..spans[i]
|
||||
};
|
||||
spans.insert(i + 1, split);
|
||||
}
|
||||
for s in spans.iter_mut().skip(i) {
|
||||
if s.start as usize >= start {
|
||||
s.hidden = true;
|
||||
}
|
||||
}
|
||||
if end > start {
|
||||
spans.push(EntitySpan {
|
||||
start: end as u32,
|
||||
..after
|
||||
});
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// `HzDraw`'s size: `renderStage`, `entityId`, `blockEntityId`, a pad, `entityColor`.
|
||||
@@ -81,3 +119,34 @@ impl DrawUniforms {
|
||||
pass.set_bind_group(2, &self.group, &[self.stride * render_stage(stage)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::EntitySpan;
|
||||
|
||||
fn span(start: u32, id: i32) -> EntitySpan {
|
||||
EntitySpan {
|
||||
start,
|
||||
id,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_splits_the_span_around_one_entity() {
|
||||
// Two cows in one span: the second (vertices 8..16) is hidden.
|
||||
let mut spans = vec![span(0, 7)];
|
||||
assert!(EntitySpan::hide(&mut spans, 8, 16));
|
||||
let hidden = EntitySpan {
|
||||
hidden: true,
|
||||
..span(8, 7)
|
||||
};
|
||||
assert_eq!(spans, [span(0, 7), hidden, span(16, 7)]);
|
||||
// An entity with its own span and a part after it (armour) is hidden whole.
|
||||
let mut spans = vec![span(0, 1), span(4, 2), span(6, 3)];
|
||||
assert!(EntitySpan::hide(&mut spans, 4, 10));
|
||||
assert!(!spans[0].hidden && spans[1].hidden && spans[2].hidden);
|
||||
assert_eq!(spans[3], span(10, 3));
|
||||
assert!(!EntitySpan::hide(&mut Vec::new(), 0, 4));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,11 +161,39 @@ pub(super) struct Draw {
|
||||
/// The first vertex.
|
||||
pub base: u32,
|
||||
pub quads: u32,
|
||||
/// The program that draws it (`ENTITY`, `BLOCK`, `TRANSLUCENT`, `PARTICLE`).
|
||||
/// The kind of program that draws it (`ENTITY`, `BLOCK`, `TRANSLUCENT`, `PARTICLE`).
|
||||
pub program: usize,
|
||||
/// The pack's gbuffers program draws it (else Horizon does).
|
||||
pub pack: bool,
|
||||
/// The pack's shadow program draws it into the shadow map too.
|
||||
pub shadow: bool,
|
||||
pub slot: u32,
|
||||
}
|
||||
|
||||
/// Which entity runs a pack's shadow pass draws (2.4, 3.2).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Casters {
|
||||
/// `shadow_entities` (or `shadow`) draws entities...
|
||||
pub entities: bool,
|
||||
/// ...only the local player (`shadowPlayer` without `shadowEntities`).
|
||||
pub only_player: bool,
|
||||
/// `shadow_block` (or `shadow`) draws block entities...
|
||||
pub blocks: bool,
|
||||
/// ...only those whose block emits light (`shadowLightBlockEntities`).
|
||||
pub only_lit: bool,
|
||||
}
|
||||
|
||||
impl Casters {
|
||||
/// Whether the shadow pass draws `span`'s run, of kind `program`.
|
||||
pub fn cast(&self, span: &EntitySpan, program: usize) -> bool {
|
||||
match program {
|
||||
ENTITY => self.entities && (!self.only_player || span.player),
|
||||
BLOCK => self.blocks && (!self.only_lit || span.emissive),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The vertices and per-draw uniforms of the runs a pack draws, rebuilt each frame.
|
||||
pub(super) struct PackEntities {
|
||||
vertices: wgpu::Buffer,
|
||||
@@ -280,7 +308,8 @@ impl PackEntities {
|
||||
|
||||
/// Splits `entities` between the pack, which draws the runs of `spans` its programs cover
|
||||
/// (`drawn`: whether it has `gbuffers_entities`, `gbuffers_block` or their fallbacks), and
|
||||
/// Horizon, which draws the rest (`rest`). Uploads the pack's part.
|
||||
/// Horizon, which draws the rest (`rest`). Uploads the pack's part, and the runs its shadow
|
||||
/// programs draw (`shadow`). Runs hidden from the camera only ever cast shadows.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
@@ -290,6 +319,7 @@ impl PackEntities {
|
||||
entities: &[Vertex],
|
||||
spans: &[EntitySpan],
|
||||
drawn: [bool; PROGRAMS],
|
||||
shadow: Casters,
|
||||
rest: &mut Vec<Vertex>,
|
||||
) {
|
||||
self.draws.clear();
|
||||
@@ -300,13 +330,15 @@ impl PackEntities {
|
||||
rest.extend_from_slice(&entities[..first.min(entities.len())]);
|
||||
for (span, range) in runs(entities.len(), spans) {
|
||||
let run = &entities[range];
|
||||
let Some(program) = drawn_by_pack(&span, drawn).filter(|_| plain(run)) else {
|
||||
let program = program_of(&span).filter(|_| plain(run));
|
||||
let pack = program.is_some_and(|p| drawn[p]) && !span.hidden;
|
||||
let casts = program.is_some_and(|p| shadow.cast(&span, p));
|
||||
if !pack && !span.hidden {
|
||||
rest.extend_from_slice(run);
|
||||
}
|
||||
let Some(program) = program.filter(|_| (pack || casts) && !run.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if run.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let start = self.scratch.len() as u32;
|
||||
self.scratch.extend_from_slice(run);
|
||||
let (entity_id, block_id) = match program {
|
||||
@@ -327,6 +359,8 @@ impl PackEntities {
|
||||
base: start,
|
||||
quads: run.len() as u32 / 4,
|
||||
program,
|
||||
pack,
|
||||
shadow: casts,
|
||||
slot: self.draws.len() as u32,
|
||||
});
|
||||
}
|
||||
@@ -388,8 +422,14 @@ pub const PROGRAMS: usize = 4;
|
||||
|
||||
/// Which program draws `span`'s run, given which of them (or their fallbacks) the pack has;
|
||||
/// `None`: Horizon draws it.
|
||||
pub fn drawn_by_pack(span: &EntitySpan, drawn: [bool; PROGRAMS]) -> Option<usize> {
|
||||
let program = if span.stage == render_stage("ENTITIES") {
|
||||
#[cfg(test)]
|
||||
fn drawn_by_pack(span: &EntitySpan, drawn: [bool; PROGRAMS]) -> Option<usize> {
|
||||
program_of(span).filter(|&p| drawn[p])
|
||||
}
|
||||
|
||||
/// The kind of program that draws `span`'s run, when a pack may.
|
||||
pub fn program_of(span: &EntitySpan) -> Option<usize> {
|
||||
Some(if span.stage == render_stage("ENTITIES") {
|
||||
if span.translucent {
|
||||
TRANSLUCENT
|
||||
} else {
|
||||
@@ -401,8 +441,7 @@ pub fn drawn_by_pack(span: &EntitySpan, drawn: [bool; PROGRAMS]) -> Option<usize
|
||||
PARTICLE
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
drawn[program].then_some(program)
|
||||
})
|
||||
}
|
||||
|
||||
/// Each span with its vertex range: from its start to the next span's (or the end).
|
||||
@@ -431,7 +470,7 @@ mod tests {
|
||||
start,
|
||||
stage: render_stage(stage),
|
||||
id,
|
||||
translucent: false,
|
||||
..Default::default()
|
||||
};
|
||||
let spans = [
|
||||
span(2, "ENTITIES", 7),
|
||||
@@ -458,5 +497,28 @@ mod tests {
|
||||
assert_eq!(entity_color(1)[0], 1.0);
|
||||
assert!((entity_color(1)[3] - (1.0 - 178.0 / 255.0)).abs() < 1e-6);
|
||||
assert_eq!(entity_color(0), [0.0; 4]);
|
||||
// The shadow pass: entities, the player alone, block entities, those that emit light.
|
||||
let all = Casters {
|
||||
entities: true,
|
||||
blocks: true,
|
||||
..Default::default()
|
||||
};
|
||||
let player = EntitySpan {
|
||||
player: true,
|
||||
..spans[0]
|
||||
};
|
||||
let lit = EntitySpan {
|
||||
emissive: true,
|
||||
..spans[2]
|
||||
};
|
||||
assert!(all.cast(&spans[0], ENTITY) && all.cast(&spans[2], BLOCK));
|
||||
assert!(!all.cast(&spans[1], PARTICLE));
|
||||
let some = Casters {
|
||||
only_player: true,
|
||||
only_lit: true,
|
||||
..all
|
||||
};
|
||||
assert!(!some.cast(&spans[0], ENTITY) && some.cast(&player, ENTITY));
|
||||
assert!(!some.cast(&spans[2], BLOCK) && some.cast(&lit, BLOCK));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,10 @@ enum Source {
|
||||
/// The block atlas (pack_atlas.rs), in gbuffers programs.
|
||||
Atlas,
|
||||
Lightmap,
|
||||
/// `shadowtex0`/`shadowtex1` (6.3), with depth comparison (`sampler2DShadow`) or not.
|
||||
ShadowDepth(usize, bool),
|
||||
/// `shadowcolor0/1` read outside the shadow programs (in them they are `Color`).
|
||||
ShadowColor(usize),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -63,13 +67,17 @@ enum SamplerKind {
|
||||
impl SamplerKind {
|
||||
fn of(source: Source, filtering: bool) -> Self {
|
||||
match source {
|
||||
Source::Color(_) | Source::Dummy if !filtering => Self::Nearest,
|
||||
Source::Depth | Source::Depth1 => Self::Nearest,
|
||||
Source::Color(_) | Source::ShadowColor(_) | Source::Dummy if !filtering => {
|
||||
Self::Nearest
|
||||
}
|
||||
Source::Depth | Source::Depth1 | Source::ShadowDepth(_, false) => Self::Nearest,
|
||||
Source::Noise => Self::Repeat,
|
||||
Source::Shadow => Self::Comparison,
|
||||
Source::Shadow | Source::ShadowDepth(_, true) => Self::Comparison,
|
||||
// Blocks look as the game draws them: nearest texels.
|
||||
Source::Atlas => Self::NearestRepeat,
|
||||
Source::Color(_) | Source::Dummy | Source::Lightmap => Self::Linear,
|
||||
Source::Color(_) | Source::ShadowColor(_) | Source::Dummy | Source::Lightmap => {
|
||||
Self::Linear
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,6 +147,17 @@ struct Entities {
|
||||
geometry: PackEntities,
|
||||
passes: [Option<Pass>; PROGRAMS],
|
||||
late: [bool; PROGRAMS],
|
||||
/// What draws entities and block entities into the shadow map (2.4).
|
||||
shadow: [Option<Pass>; 2],
|
||||
/// Only the player, only block entities that emit light (3.2).
|
||||
only: (bool, bool),
|
||||
}
|
||||
|
||||
impl Entities {
|
||||
/// Whether a gbuffers program draws some of them (else only the shadow pass does).
|
||||
fn drawn(&self) -> bool {
|
||||
self.passes.iter().any(Option::is_some)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -158,6 +177,8 @@ struct Pass {
|
||||
flip: u16,
|
||||
/// Buffers sampled, for the bind group cache key.
|
||||
reads: u16,
|
||||
/// shadowcolor buffers sampled by a program of the other buffers.
|
||||
shadow_reads: u16,
|
||||
/// Buffers written.
|
||||
written: u16,
|
||||
/// Buffers whose mip chain is regenerated right before it (6.1.7).
|
||||
@@ -168,9 +189,9 @@ struct Pass {
|
||||
atlas: Option<wgpu::TextureView>,
|
||||
/// Reads `mc_Entity`'s table (`PackPost::block_ids`).
|
||||
ids: bool,
|
||||
/// Bind groups by the sides read (low 16 bits) and the buffers whose mip chain is current
|
||||
/// (high 16 bits).
|
||||
groups: HashMap<u32, wgpu::BindGroup>,
|
||||
/// Bind groups by the sides read (bits 0–15), the buffers whose mip chain is current (bits
|
||||
/// 16–31) and the shadowcolor sides read (bits 32–33).
|
||||
groups: HashMap<u64, wgpu::BindGroup>,
|
||||
}
|
||||
|
||||
/// One side of a buffer with mipmaps.
|
||||
@@ -258,6 +279,12 @@ pub struct PackPost {
|
||||
hand: Option<(Pass, super::pack_hand::PackHand)>,
|
||||
/// A program after translucent terrain reads `depthtex1`: it is copied before water.
|
||||
depth1: bool,
|
||||
/// The shadow buffers, when the shadow pass runs (2.5), and the `shadowcomp` programs.
|
||||
shadow_targets: Option<super::pack_shadow::ShadowTargets>,
|
||||
/// What draws terrain from the light (`shadow`), and translucent terrain (`shadow_water`).
|
||||
shadow_terrain: Option<Pass>,
|
||||
shadow_water: Option<Pass>,
|
||||
shadow_comp: Vec<Pass>,
|
||||
/// Buffers with mipmaps (filterable ones a program asks them for).
|
||||
mipped: u16,
|
||||
/// Buffers whose mip chain matches their first level, this frame.
|
||||
@@ -342,7 +369,37 @@ fn texture_format(f: Format, features: wgpu::Features) -> wgpu::TextureFormat {
|
||||
}
|
||||
}
|
||||
|
||||
fn source(name: &str) -> Source {
|
||||
/// The texture behind sampler `name` in a program of the shadow buffers (`shadow_space`: buffer
|
||||
/// n is shadowcolor n) or of the others, when the shadow pass runs (`shadow_pass`). `shadow` is
|
||||
/// `shadowtex1` when the program also declares `watershadow` (6.3).
|
||||
fn source(name: &str, shadow_space: bool, shadow_pass: bool, watershadow: bool) -> Source {
|
||||
let shadow_color = match name {
|
||||
"shadowcolor" | "shadowcolor0" => Some(0),
|
||||
"shadowcolor1" => Some(1),
|
||||
_ => None,
|
||||
};
|
||||
let shadow_depth = match name {
|
||||
"shadowtex0" | "watershadow" | "shadowtex0HW" => Some(0),
|
||||
"shadowtex1" | "shadowtex1HW" => Some(1),
|
||||
"shadow" => Some(usize::from(watershadow)),
|
||||
_ => None,
|
||||
};
|
||||
if shadow_pass {
|
||||
if let Some(n) = shadow_depth {
|
||||
return Source::ShadowDepth(n, name.ends_with("HW"));
|
||||
}
|
||||
if let Some(n) = shadow_color {
|
||||
return if shadow_space {
|
||||
Source::Color(n)
|
||||
} else {
|
||||
Source::ShadowColor(n)
|
||||
};
|
||||
}
|
||||
}
|
||||
if shadow_space && horizon_shaders::buffer_index(name).is_some() {
|
||||
// colortex buffers are not this pass's.
|
||||
return Source::Dummy;
|
||||
}
|
||||
match name {
|
||||
"depthtex0" | "gdepthtex" => Source::Depth,
|
||||
// The hand is drawn after the pack, so `depthtex2` (without it) is `depthtex1`.
|
||||
@@ -555,10 +612,35 @@ fn attach(
|
||||
})
|
||||
}
|
||||
|
||||
/// Draws the game's terrain (`true`: translucent) into a pass; calls its third argument with
|
||||
/// each arena page before drawing from it.
|
||||
/// Which of the frame's terrain draws: the camera's solid or translucent ones, or the shadow
|
||||
/// camera's.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum TerrainList {
|
||||
Solid,
|
||||
Translucent,
|
||||
ShadowSolid,
|
||||
ShadowTranslucent,
|
||||
}
|
||||
|
||||
impl TerrainList {
|
||||
fn translucent(self) -> bool {
|
||||
matches!(self, Self::Translucent | Self::ShadowTranslucent)
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the game's terrain of one list into a pass; calls its third argument with each arena
|
||||
/// page before drawing from it.
|
||||
pub(super) type TerrainDraw<'a> =
|
||||
dyn FnMut(&mut wgpu::RenderPass<'_>, bool, &dyn Fn(&mut wgpu::RenderPass<'_>, u32)) + 'a;
|
||||
dyn FnMut(&mut wgpu::RenderPass<'_>, TerrainList, &dyn Fn(&mut wgpu::RenderPass<'_>, u32)) + 'a;
|
||||
|
||||
/// What the shadow camera sees of the terrain, for the game's draw lists: its view and
|
||||
/// projection in wgpu's clip space, the direction toward the light, and how far from the camera
|
||||
/// terrain is drawn (`shadowDistanceRenderMul`).
|
||||
pub(super) struct ShadowView {
|
||||
pub cull: glam::Mat4,
|
||||
pub light: glam::Vec3,
|
||||
pub distance: Option<f32>,
|
||||
}
|
||||
|
||||
/// Set 3 of flat terrain, read by the vertex stage: `mc_Entity`'s table (-1 pairs when empty)
|
||||
/// and, per arena page, the page's vertices (a vertex reads its quad's corners for its normal).
|
||||
@@ -606,11 +688,15 @@ pub(super) struct Geometry<'a> {
|
||||
}
|
||||
|
||||
/// The pass of program `p`: a quad, or `geometry` drawn by the game. `None` (with a note) when
|
||||
/// wgpu refuses it or it writes nothing.
|
||||
/// wgpu refuses it or it writes nothing. `formats` are its buffers' (for a program of the shadow
|
||||
/// buffers, buffer n is shadowcolor n); `shadow` the shadowcolor formats when the shadow pass
|
||||
/// runs.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_pass(
|
||||
device: &wgpu::Device,
|
||||
p: horizon_shaders::PostProgram,
|
||||
formats: &[wgpu::TextureFormat; BUFFERS],
|
||||
shadow: Option<&[wgpu::TextureFormat; 2]>,
|
||||
screen: wgpu::TextureFormat,
|
||||
notes: &mut Vec<String>,
|
||||
geometry: Option<&Geometry<'_>>,
|
||||
@@ -639,6 +725,8 @@ fn build_pass(
|
||||
let mut samplers = Vec::new();
|
||||
let (mut kinds, mut slots) = (HashMap::new(), HashMap::new());
|
||||
let mut reads = 0u16;
|
||||
let mut shadow_reads = 0u16;
|
||||
let watershadow = interface.samplers.iter().any(|s| s.name == "watershadow");
|
||||
// A gbuffers pass draws into its buffers and the depth buffer: reading them as well would
|
||||
// be a feedback loop (undefined in GL, refused by wgpu), so those read a blank texture.
|
||||
let in_place = match geometry {
|
||||
@@ -646,8 +734,10 @@ fn build_pass(
|
||||
None => 0,
|
||||
};
|
||||
for s in &interface.samplers {
|
||||
let mut src = source(&s.name);
|
||||
let mut src = source(&s.name, p.group.shadow(), shadow.is_some(), watershadow);
|
||||
let blank = match src {
|
||||
// The shadow pass writes the shadow map.
|
||||
Source::ShadowDepth(..) => p.group == Group::Shadow,
|
||||
Source::Atlas => geometry.is_none(),
|
||||
Source::Depth => geometry.is_some(),
|
||||
// Translucent terrain reads the copy; opaque terrain would read itself.
|
||||
@@ -660,14 +750,23 @@ fn build_pass(
|
||||
Source::Color(n) => formats[n]
|
||||
.sample_type(None, Some(features))
|
||||
.unwrap_or(float),
|
||||
Source::Depth | Source::Depth1 => wgpu::TextureSampleType::Float { filterable: false },
|
||||
Source::ShadowColor(n) => shadow
|
||||
.and_then(|f| f[n].sample_type(None, Some(features)))
|
||||
.unwrap_or(float),
|
||||
Source::Depth | Source::Depth1 | Source::ShadowDepth(..) => {
|
||||
wgpu::TextureSampleType::Float { filterable: false }
|
||||
}
|
||||
// Unfilterable on WebGPU-level devices; the lightmap is sampled at texel centres.
|
||||
Source::Lightmap => float,
|
||||
_ => float,
|
||||
};
|
||||
let int = !matches!(sample_type, wgpu::TextureSampleType::Float { .. });
|
||||
if s.ty == "sampler2DShadow" {
|
||||
(src, sample_type) = (Source::Shadow, wgpu::TextureSampleType::Depth);
|
||||
src = match src {
|
||||
Source::ShadowDepth(n, _) => Source::ShadowDepth(n, true),
|
||||
_ => Source::Shadow,
|
||||
};
|
||||
sample_type = wgpu::TextureSampleType::Depth;
|
||||
}
|
||||
let wanted = match s.ty.as_str() {
|
||||
"sampler2DShadow" => true,
|
||||
@@ -683,7 +782,9 @@ fn build_pass(
|
||||
));
|
||||
(src, sample_type) = (Source::Dummy, float);
|
||||
}
|
||||
if blank {
|
||||
if blank && sample_type == wgpu::TextureSampleType::Depth {
|
||||
src = Source::Shadow;
|
||||
} else if blank {
|
||||
// The blank texture is float: an integer sampler then fails the pipeline (a note).
|
||||
src = Source::Dummy;
|
||||
if int {
|
||||
@@ -691,8 +792,10 @@ fn build_pass(
|
||||
}
|
||||
}
|
||||
let filtering = sample_type == float;
|
||||
if let Source::Color(n) = src {
|
||||
reads |= 1 << n;
|
||||
match src {
|
||||
Source::Color(n) => reads |= 1 << n,
|
||||
Source::ShadowColor(n) => shadow_reads |= 1 << n,
|
||||
_ => {}
|
||||
}
|
||||
entries.push(texture_entry(s.binding, sample_type));
|
||||
let kind = SamplerKind::of(src, filtering);
|
||||
@@ -849,6 +952,7 @@ fn build_pass(
|
||||
writes,
|
||||
flip,
|
||||
reads,
|
||||
shadow_reads,
|
||||
written,
|
||||
mipmaps: p.mipmaps,
|
||||
draw,
|
||||
@@ -892,18 +996,32 @@ impl PackPost {
|
||||
|flips: &[(u32, bool)]| flips.iter().filter(|f| f.1).fold(0u16, |m, f| m | 1 << f.0);
|
||||
let mut used = 1u16;
|
||||
let draws = DrawUniforms::new(device);
|
||||
// The shadow buffers' formats when the shadow pass runs; their programs see them as
|
||||
// buffers 0 and 1.
|
||||
let shadow_formats: Option<[wgpu::TextureFormat; 2]> = post.shadow_pass.then(|| {
|
||||
std::array::from_fn(|n| texture_format(shadow_config.colors[n].format, features))
|
||||
});
|
||||
let shadow_space: [wgpu::TextureFormat; BUFFERS] = std::array::from_fn(|i| {
|
||||
shadow_formats
|
||||
.filter(|_| i < 2)
|
||||
.map_or(formats[i], |f| f[i])
|
||||
});
|
||||
let mut build = |p: horizon_shaders::PostProgram, geometry: Option<&Geometry<'_>>| {
|
||||
let in_shadow = p.group.shadow();
|
||||
let pass = build_pass(
|
||||
device,
|
||||
p,
|
||||
&formats,
|
||||
if in_shadow { &shadow_space } else { &formats },
|
||||
shadow_formats.as_ref(),
|
||||
screen,
|
||||
&mut notes,
|
||||
geometry,
|
||||
&custom_names,
|
||||
&draws.layout,
|
||||
)?;
|
||||
used |= pass.reads | pass.written | pass.flip;
|
||||
if !in_shadow {
|
||||
used |= pass.reads | pass.written | pass.flip;
|
||||
}
|
||||
Some(pass)
|
||||
};
|
||||
// Flat terrain reads `mc_Entity` from a table of the sprite layers.
|
||||
@@ -928,6 +1046,14 @@ impl PackPost {
|
||||
.water
|
||||
.zip(terrain_geometry.as_ref())
|
||||
.and_then(|(p, g)| build(p, Some(g)));
|
||||
let shadow_terrain = post
|
||||
.shadow
|
||||
.zip(terrain_geometry.as_ref())
|
||||
.and_then(|(p, g)| build(p, Some(g)));
|
||||
let shadow_water = post
|
||||
.shadow_water
|
||||
.zip(terrain_geometry.as_ref())
|
||||
.and_then(|(p, g)| build(p, Some(g)));
|
||||
let sky = (post.sky.is_some() || post.sky_textured.is_some()).then(|| {
|
||||
let geometry = PackSky::new(device);
|
||||
let basic = Geometry {
|
||||
@@ -962,8 +1088,9 @@ impl PackPost {
|
||||
post.particles,
|
||||
];
|
||||
let late = [false, false, post.translucent_late, post.particles_late];
|
||||
let entity_vertices = programs
|
||||
.iter()
|
||||
let shadow_only = (post.shadow_only_player, post.shadow_only_lit_blocks);
|
||||
let shadow_programs = [post.shadow_entities, post.shadow_block];
|
||||
let entity_vertices = (programs.iter().chain(&shadow_programs))
|
||||
.any(Option::is_some)
|
||||
.then(|| PackEntities::new(device, &draws.layout));
|
||||
let entity_buffers = super::pack_entities::buffers();
|
||||
@@ -979,12 +1106,18 @@ impl PackPost {
|
||||
p.zip(entity_geometry.as_ref())
|
||||
.and_then(|(p, g)| build(p, Some(g)))
|
||||
});
|
||||
let shadow_entities = shadow_programs.map(|p| {
|
||||
p.zip(entity_geometry.as_ref())
|
||||
.and_then(|(p, g)| build(p, Some(g)))
|
||||
});
|
||||
let entities = entity_vertices
|
||||
.filter(|_| entity_passes.iter().any(Option::is_some))
|
||||
.filter(|_| (entity_passes.iter().chain(&shadow_entities)).any(Option::is_some))
|
||||
.map(|geometry| Entities {
|
||||
geometry,
|
||||
passes: entity_passes,
|
||||
late,
|
||||
shadow: shadow_entities,
|
||||
only: shadow_only,
|
||||
});
|
||||
let cloud_geometry = world.clouds.map(|layout| Geometry {
|
||||
buffers: &entity_buffers,
|
||||
@@ -1036,12 +1169,31 @@ impl PackPost {
|
||||
.filter(|p| !skip.split(',').any(|s| s == p.name))
|
||||
.filter_map(|p| build(p, None))
|
||||
.collect();
|
||||
let shadow_comp: Vec<Pass> = post
|
||||
.shadow_comp
|
||||
.into_iter()
|
||||
.filter(|p| !skip.split(',').any(|s| s == p.name))
|
||||
.filter_map(|p| build(p, None))
|
||||
.collect();
|
||||
if let Some(t) = &terrain {
|
||||
notes.push(format!("terrain draws with {}", t.name));
|
||||
}
|
||||
for (part, pass) in [
|
||||
("terrain", &shadow_terrain),
|
||||
("translucent terrain", &shadow_water),
|
||||
] {
|
||||
if let Some(p) = pass {
|
||||
notes.push(format!("{part} casts shadows with {}", p.name));
|
||||
}
|
||||
}
|
||||
if let Some(w) = &water {
|
||||
notes.push(format!("translucent terrain draws with {}", w.name));
|
||||
}
|
||||
// Timed (and labelled) apart from the solid shadow pass that runs the same program.
|
||||
let mut shadow_water = shadow_water;
|
||||
if let Some(p) = &mut shadow_water {
|
||||
p.name.push_str(" (translucent)");
|
||||
}
|
||||
for (part, pass) in sky
|
||||
.iter()
|
||||
.flat_map(|s| [("sky", &s.basic), ("sun and moon", &s.textured)])
|
||||
@@ -1070,6 +1222,22 @@ impl PackPost {
|
||||
notes.push(format!("{part} draw with {}", p.name));
|
||||
}
|
||||
}
|
||||
// Timed (and labelled) apart from the terrain's shadow pass, which may run the same
|
||||
// program.
|
||||
let mut entities = entities;
|
||||
for e in entities.iter_mut() {
|
||||
let only = [
|
||||
(e.only.0, " (only the player)"),
|
||||
(e.only.1, " (only those that emit light)"),
|
||||
];
|
||||
for ((part, pass), (only, which)) in parts.iter().zip(&mut e.shadow).zip(only) {
|
||||
if let Some(p) = pass {
|
||||
let which = if only { which } else { "" };
|
||||
notes.push(format!("{part}{which} cast shadows with {}", p.name));
|
||||
p.name.push_str(&format!(" ({part})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let depth1 = water.is_some()
|
||||
&& passes
|
||||
.iter()
|
||||
@@ -1077,6 +1245,43 @@ impl PackPost {
|
||||
.chain(&water)
|
||||
.chain(weather.iter().take(1).flatten())
|
||||
.any(|p| p.samplers.iter().any(|s| s.source == Source::Depth1));
|
||||
let every_pass = || {
|
||||
(passes
|
||||
.iter()
|
||||
.chain(&shadow_comp)
|
||||
.chain(&terrain)
|
||||
.chain(&water))
|
||||
.chain(shadow_terrain.iter().chain(&shadow_water))
|
||||
.chain(sky.iter().flat_map(|s| s.basic.iter().chain(&s.textured)))
|
||||
.chain(entities.iter().flat_map(|e| e.passes.iter().flatten()))
|
||||
.chain(entities.iter().flat_map(|e| e.shadow.iter().flatten()))
|
||||
.chain(&clouds)
|
||||
.chain(weather.iter().flatten())
|
||||
.chain(hand.iter().map(|h| &h.0))
|
||||
};
|
||||
let shadow_targets = shadow_formats.map(|f| {
|
||||
let colors = every_pass().fold(0u16, |m, p| {
|
||||
let own = if p.group.shadow() {
|
||||
p.reads | p.written | p.flip
|
||||
} else {
|
||||
0
|
||||
};
|
||||
m | own | p.shadow_reads
|
||||
});
|
||||
let depth1 = every_pass()
|
||||
.flat_map(|p| &p.samplers)
|
||||
.any(|s| matches!(s.source, Source::ShadowDepth(1, _)));
|
||||
let t =
|
||||
super::pack_shadow::ShadowTargets::new(device, &shadow_config, f, colors, depth1);
|
||||
notes.push(format!(
|
||||
"shadow map {0}x{0} over {2} blocks, sunPathRotation {3}, shadowcolor buffers {colors:#b}{1}",
|
||||
t.size,
|
||||
if depth1 { ", shadowtex1" } else { "" },
|
||||
shadow_config.distance,
|
||||
shadow_config.sun_path_rotation,
|
||||
));
|
||||
t
|
||||
});
|
||||
// A clear only matters when a program reads the buffer before one writes all of it
|
||||
// (composite passes cover their whole target, terrain does not); the others are skipped.
|
||||
let mut cleared = Vec::new();
|
||||
@@ -1107,7 +1312,7 @@ impl PackPost {
|
||||
let blit_depth = terrain.is_some()
|
||||
|| water.is_some()
|
||||
|| sky.is_some()
|
||||
|| entities.is_some()
|
||||
|| entities.as_ref().is_some_and(Entities::drawn)
|
||||
|| clouds.is_some()
|
||||
|| weather.is_some()
|
||||
|| hand.is_some()
|
||||
@@ -1215,6 +1420,10 @@ impl PackPost {
|
||||
weather_generation: 0,
|
||||
hand,
|
||||
depth1,
|
||||
shadow_targets,
|
||||
shadow_terrain,
|
||||
shadow_water,
|
||||
shadow_comp,
|
||||
mipped,
|
||||
mips_valid: 0,
|
||||
down,
|
||||
@@ -1319,17 +1528,43 @@ impl PackPost {
|
||||
queue.write_buffer(&pass.ubo, 0, &pass.block);
|
||||
}
|
||||
let targets = self.targets.as_ref().expect("resized");
|
||||
let shadow = self.shadow_targets.as_ref();
|
||||
let shadow_main = shadow.map_or(0, |s| s.main);
|
||||
let shadow_space = pass.group.shadow();
|
||||
// A chain is sampled only while it is current: a buffer written since its last chain
|
||||
// reads its first level, never stale levels (6.1.7).
|
||||
let current = self.mips_valid & self.mipped & pass.reads;
|
||||
let key = u32::from(self.main & pass.reads) | u32::from(current) << 16;
|
||||
// reads its first level, never stale levels (6.1.7). The shadow buffers have none.
|
||||
let (main, current) = if shadow_space {
|
||||
(shadow_main, 0)
|
||||
} else {
|
||||
(self.main, self.mips_valid & self.mipped & pass.reads)
|
||||
};
|
||||
let key = u64::from(main & pass.reads)
|
||||
| u64::from(current) << 16
|
||||
| u64::from(shadow_main & pass.shadow_reads) << 32;
|
||||
let group = pass.groups.entry(key).or_insert_with(|| {
|
||||
let mut entries = vec![wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: pass.ubo.as_entire_binding(),
|
||||
}];
|
||||
for s in &pass.samplers {
|
||||
let shadow_color = |i: usize, side: usize| {
|
||||
shadow.and_then(|t| t.color[i].as_ref()).map(|c| &c[side])
|
||||
};
|
||||
let texture = match s.source {
|
||||
Source::Color(i) if shadow_space => {
|
||||
shadow_color(i, usize::from(key & 1 << i != 0)).unwrap_or(&self.dummy)
|
||||
}
|
||||
Source::ShadowColor(i) => {
|
||||
shadow_color(i, usize::from(key & 1 << (32 + i) != 0))
|
||||
.unwrap_or(&self.dummy)
|
||||
}
|
||||
Source::ShadowDepth(i, _) => match shadow {
|
||||
Some(t) => match (i, &t.depth1) {
|
||||
(1, Some(d)) => &d.1,
|
||||
_ => &t.depth.1,
|
||||
},
|
||||
None => &self.shadow.0,
|
||||
},
|
||||
Source::Color(i) => {
|
||||
let side = usize::from(key & 1 << i != 0);
|
||||
match (&targets.mips[i], &targets.color[i]) {
|
||||
@@ -1366,7 +1601,7 @@ impl PackPost {
|
||||
SamplerKind::Nearest => &self.nearest,
|
||||
SamplerKind::Repeat => &self.repeat,
|
||||
SamplerKind::NearestRepeat => &self.nearest_repeat,
|
||||
SamplerKind::Comparison => &self.shadow.1,
|
||||
SamplerKind::Comparison => shadow.map_or(&self.shadow.1, |t| &t.comparison),
|
||||
};
|
||||
entries.push(wgpu::BindGroupEntry {
|
||||
binding: s.binding,
|
||||
@@ -1399,15 +1634,27 @@ impl PackPost {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
};
|
||||
// The shadow pass draws into the shadow buffers and the shadow map, the frame's first
|
||||
// one clearing them.
|
||||
let (depth_ops, shadow_ops) = match &mut self.shadow_targets {
|
||||
Some(s) if pass.group.shadow() => s.clear_ops(pass.writes.iter().map(|w| w.1)),
|
||||
_ => (super::pack_shadow::load(), [load; 2]),
|
||||
};
|
||||
let shadow = self.shadow_targets.as_ref().filter(|_| pass.group.shadow());
|
||||
let mut attachments: Vec<Option<wgpu::RenderPassColorAttachment>> = Vec::new();
|
||||
for &(location, buffer) in &pass.writes {
|
||||
let l = location as usize;
|
||||
if attachments.len() <= l {
|
||||
attachments.resize(l + 1, None);
|
||||
}
|
||||
attachments[l] = targets.color[buffer]
|
||||
.as_ref()
|
||||
.and_then(|t| attach(&t[usize::from(self.main & 1 << buffer != 0)], load));
|
||||
attachments[l] = match shadow {
|
||||
Some(s) => s
|
||||
.color(buffer, false)
|
||||
.and_then(|v| attach(v, shadow_ops.get(buffer).copied().unwrap_or(load))),
|
||||
None => targets.color[buffer]
|
||||
.as_ref()
|
||||
.and_then(|t| attach(&t[usize::from(self.main & 1 << buffer != 0)], load)),
|
||||
};
|
||||
}
|
||||
let timestamp_writes = self.timing.as_mut().and_then(|t| t.writes(&pass.name));
|
||||
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
@@ -1415,11 +1662,8 @@ impl PackPost {
|
||||
color_attachments: &attachments,
|
||||
timestamp_writes,
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &targets.depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
}),
|
||||
view: shadow.map_or(&targets.depth, |s| &s.depth.1),
|
||||
depth_ops: Some(depth_ops),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
@@ -1434,18 +1678,20 @@ impl PackPost {
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
size: [u32; 2],
|
||||
translucent: bool,
|
||||
list: TerrainList,
|
||||
draw: &mut TerrainDraw<'_>,
|
||||
) {
|
||||
let slot = if translucent {
|
||||
&mut self.water
|
||||
} else {
|
||||
&mut self.terrain
|
||||
let slot = match list {
|
||||
TerrainList::Solid => &mut self.terrain,
|
||||
TerrainList::Translucent => &mut self.water,
|
||||
TerrainList::ShadowSolid => &mut self.shadow_terrain,
|
||||
TerrainList::ShadowTranslucent => &mut self.shadow_water,
|
||||
};
|
||||
let Some(mut pass) = slot.take() else {
|
||||
return;
|
||||
};
|
||||
if translucent
|
||||
let translucent = list.translucent();
|
||||
if list == TerrainList::Translucent
|
||||
&& let Some(t) = &self.targets
|
||||
&& let Some((copy, _)) = &t.depth1
|
||||
{
|
||||
@@ -1474,14 +1720,17 @@ impl PackPost {
|
||||
rp.set_bind_group(3, group, &[]);
|
||||
}
|
||||
};
|
||||
draw(&mut rp, translucent, &page);
|
||||
draw(&mut rp, list, &page);
|
||||
}
|
||||
self.mips_valid &= !pass.written;
|
||||
if translucent {
|
||||
self.water = Some(pass);
|
||||
} else {
|
||||
self.terrain = Some(pass);
|
||||
if !pass.group.shadow() {
|
||||
self.mips_valid &= !pass.written;
|
||||
}
|
||||
*match list {
|
||||
TerrainList::Solid => &mut self.terrain,
|
||||
TerrainList::Translucent => &mut self.water,
|
||||
TerrainList::ShadowSolid => &mut self.shadow_terrain,
|
||||
TerrainList::ShadowTranslucent => &mut self.shadow_water,
|
||||
} = Some(pass);
|
||||
}
|
||||
|
||||
/// The sky's parts in vanilla's order, each with the program that draws it; one render pass
|
||||
@@ -1561,7 +1810,7 @@ impl PackPost {
|
||||
let mut draws = geometry
|
||||
.draws
|
||||
.iter()
|
||||
.filter(|d| d.program == program)
|
||||
.filter(|d| d.pack && d.program == program)
|
||||
.peekable();
|
||||
if draws.peek().is_none() {
|
||||
continue;
|
||||
@@ -1586,6 +1835,46 @@ impl PackPost {
|
||||
self.entities = Some(entities);
|
||||
}
|
||||
|
||||
/// Entities and block entities into the shadow map, each run with the per-draw uniforms
|
||||
/// of its gbuffers draw (2.4): opaque, so before the `shadowtex1` copy.
|
||||
fn draw_shadow_entities(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
size: [u32; 2],
|
||||
) {
|
||||
let Some(mut entities) = self.entities.take() else {
|
||||
return;
|
||||
};
|
||||
let geometry = &entities.geometry;
|
||||
for (program, pass) in entities.shadow.iter_mut().enumerate() {
|
||||
let Some(pass) = pass else {
|
||||
continue;
|
||||
};
|
||||
let mut draws = (geometry.draws.iter())
|
||||
.filter(|d| d.shadow && d.program == program)
|
||||
.peekable();
|
||||
if draws.peek().is_none() {
|
||||
continue;
|
||||
}
|
||||
let group = self.bind(device, queue, pass, size);
|
||||
let mut rp = self.begin(encoder, pass);
|
||||
rp.set_pipeline(&pass.pipeline);
|
||||
rp.set_bind_group(0, &group, &[]);
|
||||
rp.set_bind_group(1, &geometry.table_group, &[]);
|
||||
rp.set_vertex_buffer(0, geometry.vertices());
|
||||
rp.set_index_buffer(geometry.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for d in draws {
|
||||
if pass.draw {
|
||||
rp.set_bind_group(2, &geometry.group, &[geometry.offset(d.slot)]);
|
||||
}
|
||||
rp.draw_indexed(0..d.quads * 6, d.base as i32, 0..1);
|
||||
}
|
||||
}
|
||||
self.entities = Some(entities);
|
||||
}
|
||||
|
||||
/// Splits `entities` (`Frame::entities`) between the pack and Horizon by its runs
|
||||
/// (`spans`): the pack's part is uploaded for this frame's draw, Horizon's goes to `rest`.
|
||||
pub fn prepare_entities(
|
||||
@@ -1596,6 +1885,7 @@ impl PackPost {
|
||||
spans: &[super::pack_draw::EntitySpan],
|
||||
rest: &mut Vec<super::Vertex>,
|
||||
) {
|
||||
let shadow = self.shadow_casters();
|
||||
let Some(e) = &mut self.entities else {
|
||||
rest.clear();
|
||||
rest.extend_from_slice(entities);
|
||||
@@ -1609,10 +1899,28 @@ impl PackPost {
|
||||
entities,
|
||||
spans,
|
||||
drawn,
|
||||
shadow,
|
||||
rest,
|
||||
);
|
||||
}
|
||||
|
||||
/// Which entity runs the shadow pass draws: none without it.
|
||||
pub fn shadow_casters(&self) -> super::pack_entities::Casters {
|
||||
let Some(e) = self
|
||||
.entities
|
||||
.as_ref()
|
||||
.filter(|_| self.shadow_targets.is_some())
|
||||
else {
|
||||
return Default::default();
|
||||
};
|
||||
super::pack_entities::Casters {
|
||||
entities: e.shadow[0].is_some(),
|
||||
only_player: e.only.0,
|
||||
blocks: e.shadow[1].is_some(),
|
||||
only_lit: e.only.1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pack draws entities or block entities itself.
|
||||
pub fn has_entities(&self) -> bool {
|
||||
self.entities.is_some()
|
||||
@@ -1631,7 +1939,7 @@ impl PackPost {
|
||||
if super::sky_visible(frame) {
|
||||
self.draw_sky(device, queue, encoder, size, frame);
|
||||
}
|
||||
self.draw_terrain(device, queue, encoder, size, false, terrain);
|
||||
self.draw_terrain(device, queue, encoder, size, TerrainList::Solid, terrain);
|
||||
self.draw_entities(device, queue, encoder, size, false);
|
||||
self.draw_clouds(device, queue, encoder, size);
|
||||
self.draw_hand(device, queue, encoder, size, frame);
|
||||
@@ -1727,7 +2035,14 @@ impl PackPost {
|
||||
size: [u32; 2],
|
||||
terrain: &mut TerrainDraw<'_>,
|
||||
) {
|
||||
self.draw_terrain(device, queue, encoder, size, true, terrain);
|
||||
self.draw_terrain(
|
||||
device,
|
||||
queue,
|
||||
encoder,
|
||||
size,
|
||||
TerrainList::Translucent,
|
||||
terrain,
|
||||
);
|
||||
self.draw_entities(device, queue, encoder, size, true);
|
||||
self.draw_weather(device, queue, encoder, size);
|
||||
}
|
||||
@@ -1808,6 +2123,20 @@ impl PackPost {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the shadow camera draws of the terrain this frame, when the pack draws it.
|
||||
pub fn shadow_view(&self, frame: &super::Frame) -> Option<ShadowView> {
|
||||
self.shadow_targets.as_ref()?;
|
||||
if self.shadow_terrain.is_none() && self.shadow_water.is_none() {
|
||||
return None;
|
||||
}
|
||||
let shadow = &self.uniforms.shadow;
|
||||
Some(ShadowView {
|
||||
cull: pack_uniforms::shadow_culling(frame, shadow),
|
||||
light: pack_uniforms::shadow_light(frame, shadow),
|
||||
distance: (shadow.render_mul > 0.0).then_some(shadow.distance * shadow.render_mul),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the pack draws terrain itself.
|
||||
pub fn has_terrain(&self) -> bool {
|
||||
self.terrain.is_some()
|
||||
@@ -1930,6 +2259,75 @@ impl PackPost {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shadow pass (2.1, passes 2 and 3): the shadow buffers cleared, then the `shadowcomp`
|
||||
/// programs, each drawing into the "alt" side of what it writes and flipping it after.
|
||||
fn run_shadow(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
terrain: &mut TerrainDraw<'_>,
|
||||
) {
|
||||
let Some(t) = &mut self.shadow_targets else {
|
||||
return;
|
||||
};
|
||||
t.begin_frame();
|
||||
let size = [t.size; 2];
|
||||
self.draw_terrain(
|
||||
device,
|
||||
queue,
|
||||
encoder,
|
||||
size,
|
||||
TerrainList::ShadowSolid,
|
||||
terrain,
|
||||
);
|
||||
self.draw_shadow_entities(device, queue, encoder, size);
|
||||
let t = self.shadow_targets.as_mut().expect("shadow pass");
|
||||
t.clear_rest(encoder);
|
||||
t.copy_depth1(encoder);
|
||||
self.draw_terrain(
|
||||
device,
|
||||
queue,
|
||||
encoder,
|
||||
size,
|
||||
TerrainList::ShadowTranslucent,
|
||||
terrain,
|
||||
);
|
||||
let mut comp = std::mem::take(&mut self.shadow_comp);
|
||||
for pass in &mut comp {
|
||||
let group = self.bind(device, queue, pass, size);
|
||||
let t = self.shadow_targets.as_ref().expect("shadow pass");
|
||||
let mut attachments: Vec<Option<wgpu::RenderPassColorAttachment>> = Vec::new();
|
||||
for &(location, buffer) in &pass.writes {
|
||||
let l = location as usize;
|
||||
if attachments.len() <= l {
|
||||
attachments.resize(l + 1, None);
|
||||
}
|
||||
// Overwritten whole.
|
||||
let ops = wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
};
|
||||
attachments[l] = t.color(buffer, true).and_then(|v| attach(v, ops));
|
||||
}
|
||||
{
|
||||
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some(&pass.name),
|
||||
color_attachments: &attachments,
|
||||
timestamp_writes: self.timing.as_mut().and_then(|t| t.writes(&pass.name)),
|
||||
..Default::default()
|
||||
});
|
||||
rp.set_pipeline(&pass.pipeline);
|
||||
rp.set_bind_group(0, &group, &[]);
|
||||
rp.draw(0..6, 0..1);
|
||||
}
|
||||
if let Some(t) = &mut self.shadow_targets {
|
||||
t.main ^= pass.flip;
|
||||
}
|
||||
}
|
||||
self.shadow_comp = comp;
|
||||
}
|
||||
|
||||
/// Runs the pack over the world drawn into `world` (colour) and `world_depth`, then draws
|
||||
/// the result onto `screen`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -1978,6 +2376,10 @@ impl PackPost {
|
||||
}
|
||||
self.uniforms.update(frame, inputs, size);
|
||||
self.uniforms.eval_custom(&mut self.custom);
|
||||
if self.targets.is_none() {
|
||||
return;
|
||||
}
|
||||
self.run_shadow(device, queue, encoder, terrain);
|
||||
let Some(targets) = &self.targets else { return };
|
||||
let main = |m: u16, i: usize| usize::from(m & 1 << i != 0);
|
||||
let view = |m: u16, i: usize, alt: bool| {
|
||||
@@ -2088,7 +2490,7 @@ impl PackPost {
|
||||
let mut shown = false;
|
||||
let mut terrain_drawn = self.terrain.is_none()
|
||||
&& self.sky.is_none()
|
||||
&& self.entities.is_none()
|
||||
&& !self.entities.as_ref().is_some_and(Entities::drawn)
|
||||
&& self.clouds.is_none()
|
||||
&& self.hand.is_none();
|
||||
let late_entities = self.entities.as_ref().is_some_and(|e| {
|
||||
@@ -2249,10 +2651,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn sampler_names() {
|
||||
assert!(source("gaux1") == Source::Color(4));
|
||||
assert!(source("gdepthtex") == Source::Depth);
|
||||
assert!(source("depthtex2") == Source::Depth1);
|
||||
assert!(source("noisetex") == Source::Noise);
|
||||
assert!(source("shadowcolor0") == Source::Dummy);
|
||||
let main = |n| source(n, false, false, false);
|
||||
assert!(main("gaux1") == Source::Color(4));
|
||||
assert!(main("gdepthtex") == Source::Depth);
|
||||
assert!(main("depthtex2") == Source::Depth1);
|
||||
assert!(main("noisetex") == Source::Noise);
|
||||
// Without the shadow pass, the shadow buffers are stand-ins.
|
||||
assert!(main("shadowcolor0") == Source::Dummy);
|
||||
assert!(main("shadowtex0") == Source::Dummy);
|
||||
// With it: shadowcolor n is buffer n of the shadow programs, `shadow` is shadowtex1
|
||||
// beside `watershadow` (6.3), and colortex is not theirs.
|
||||
assert!(source("shadowcolor", false, true, false) == Source::ShadowColor(0));
|
||||
assert!(source("shadowcolor1", true, true, false) == Source::Color(1));
|
||||
assert!(source("colortex1", true, true, false) == Source::Dummy);
|
||||
assert!(source("shadow", false, true, false) == Source::ShadowDepth(0, false));
|
||||
assert!(source("shadow", false, true, true) == Source::ShadowDepth(1, false));
|
||||
assert!(source("watershadow", false, true, true) == Source::ShadowDepth(0, false));
|
||||
assert!(source("shadowtex1HW", false, true, false) == Source::ShadowDepth(1, true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//! A shader pack's shadow buffers (spec 6.3): the shadow map's depth (`shadowtex0`, and
|
||||
//! `shadowtex1` without translucent geometry), and the colour buffers `shadowcolor0/1`, each
|
||||
//! with two sides that `shadowcomp` programs flip as composite programs flip colortex (6.1.6).
|
||||
//! Square, `shadowMapResolution` pixels.
|
||||
|
||||
type Ops<T> = wgpu::Operations<T>;
|
||||
type Color = wgpu::Color;
|
||||
|
||||
/// Loaded and stored.
|
||||
pub(super) fn load<T>() -> Ops<T> {
|
||||
wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(c: [f32; 4]) -> Ops<Color> {
|
||||
wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: c[0].into(),
|
||||
g: c[1].into(),
|
||||
b: c[2].into(),
|
||||
a: c[3].into(),
|
||||
}),
|
||||
store: wgpu::StoreOp::Store,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the shadow pass writes and the programs read.
|
||||
pub(super) struct ShadowTargets {
|
||||
pub size: u32,
|
||||
/// `shadowtex0`, written by the shadow pass.
|
||||
pub depth: (wgpu::Texture, wgpu::TextureView),
|
||||
/// `shadowtex1`: a copy of `shadowtex0` taken before translucent terrain, when read.
|
||||
pub depth1: Option<(wgpu::Texture, wgpu::TextureView)>,
|
||||
/// Both sides of each shadowcolor buffer used.
|
||||
pub color: [Option<[wgpu::TextureView; 2]>; 2],
|
||||
/// The clear colour of each buffer cleared every frame.
|
||||
pub clears: [Option<[f32; 4]>; 2],
|
||||
/// Bit n set: B is shadowcolor n's "main".
|
||||
pub main: u16,
|
||||
/// Nothing cleared yet this frame: the first pass into the shadow buffers clears them as it
|
||||
/// begins (`clear_ops`), which saves a pass that loads and stores them all on tiled GPUs.
|
||||
fresh: bool,
|
||||
/// Bit n set: shadowcolor n was cleared that way.
|
||||
cleared: u8,
|
||||
/// Depth comparison for `sampler2DShadow` (hardware filtering): linear, as GL filters it.
|
||||
pub comparison: wgpu::Sampler,
|
||||
}
|
||||
|
||||
fn target(
|
||||
device: &wgpu::Device,
|
||||
label: &str,
|
||||
size: u32,
|
||||
format: wgpu::TextureFormat,
|
||||
copy: wgpu::TextureUsages,
|
||||
) -> (wgpu::Texture, wgpu::TextureView) {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width: size,
|
||||
height: size,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | copy,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&Default::default());
|
||||
(texture, view)
|
||||
}
|
||||
|
||||
impl ShadowTargets {
|
||||
/// The buffers of `shadow` the pack uses: `colors` (bit n: shadowcolor n), `depth1` when
|
||||
/// some program reads `shadowtex1`. The resolution is kept within the device's limit.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
shadow: &horizon_shaders::Shadow,
|
||||
formats: [wgpu::TextureFormat; 2],
|
||||
colors: u16,
|
||||
depth1: bool,
|
||||
) -> Self {
|
||||
let size = shadow
|
||||
.resolution
|
||||
.clamp(1, device.limits().max_texture_dimension_2d);
|
||||
let copy = wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST;
|
||||
let depth = wgpu::TextureFormat::Depth32Float;
|
||||
let color = std::array::from_fn(|n| {
|
||||
(colors & 1 << n != 0).then(|| {
|
||||
[0, 1].map(|side| {
|
||||
let label = format!("Shader pack shadowcolor{n} {}", ["A", "B"][side]);
|
||||
target(
|
||||
device,
|
||||
&label,
|
||||
size,
|
||||
formats[n],
|
||||
wgpu::TextureUsages::empty(),
|
||||
)
|
||||
.1
|
||||
})
|
||||
})
|
||||
});
|
||||
Self {
|
||||
size,
|
||||
depth: target(device, "Shader pack shadowtex0", size, depth, copy),
|
||||
depth1: depth1.then(|| target(device, "Shader pack shadowtex1", size, depth, copy)),
|
||||
color,
|
||||
clears: std::array::from_fn(|n| {
|
||||
let b = &shadow.colors[n];
|
||||
b.clear.then(|| b.clear_color.unwrap_or([1.0; 4]))
|
||||
}),
|
||||
main: 0,
|
||||
fresh: false,
|
||||
cleared: 0,
|
||||
comparison: device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Shader pack shadow comparison"),
|
||||
compare: Some(wgpu::CompareFunction::LessEqual),
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Side `alt` (of "main" and "alt") of shadowcolor `n`.
|
||||
pub fn color(&self, n: usize, alt: bool) -> Option<&wgpu::TextureView> {
|
||||
let side = usize::from(self.main & 1 << n != 0) ^ usize::from(alt);
|
||||
self.color.get(n)?.as_ref().map(|c| &c[side])
|
||||
}
|
||||
|
||||
/// A new frame: the shadow map and the shadowcolor buffers cleared every frame (6.3) are
|
||||
/// cleared by the first pass that begins (`clear_ops`), or else by `clear_rest`.
|
||||
pub fn begin_frame(&mut self) {
|
||||
self.fresh = true;
|
||||
self.cleared = 0;
|
||||
}
|
||||
|
||||
/// The load operations of a pass into the shadow map and shadowcolor buffers `writes`:
|
||||
/// clears in the frame's first one, loads after.
|
||||
pub fn clear_ops(
|
||||
&mut self,
|
||||
writes: impl Iterator<Item = usize>,
|
||||
) -> (Ops<f32>, [Ops<Color>; 2]) {
|
||||
if !std::mem::take(&mut self.fresh) {
|
||||
return (load(), [load(); 2]);
|
||||
}
|
||||
let mut colors = [load(); 2];
|
||||
for n in writes.filter(|&n| n < 2) {
|
||||
if let Some(c) = self.clears[n] {
|
||||
colors[n] = clear(c);
|
||||
self.cleared |= 1 << n;
|
||||
}
|
||||
}
|
||||
let depth = wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store: wgpu::StoreOp::Store,
|
||||
};
|
||||
(depth, colors)
|
||||
}
|
||||
|
||||
/// Clears what no pass has cleared this frame: all of it when no shadow program drew, the
|
||||
/// cleared shadowcolor buffers the first one did not write.
|
||||
pub fn clear_rest(&mut self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let depth = std::mem::take(&mut self.fresh);
|
||||
let cleared = std::mem::replace(&mut self.cleared, 0b11);
|
||||
let attachments: Vec<_> = (0..2)
|
||||
.filter(|n| cleared & 1 << n == 0)
|
||||
.filter_map(|n| {
|
||||
Some(Some(wgpu::RenderPassColorAttachment {
|
||||
view: self.color(n, false)?,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: clear(self.clears[n]?),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
if !depth && attachments.is_empty() {
|
||||
return;
|
||||
}
|
||||
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Shader pack shadow clear"),
|
||||
color_attachments: &attachments,
|
||||
depth_stencil_attachment: depth.then_some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth.1,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store: wgpu::StoreOp::Store,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
/// `shadowtex1`: the shadow map as it is now (before translucent geometry).
|
||||
pub fn copy_depth1(&self, encoder: &mut wgpu::CommandEncoder) {
|
||||
if let Some((copy, _)) = &self.depth1 {
|
||||
encoder.copy_texture_to_texture(
|
||||
self.depth.0.as_image_copy(),
|
||||
copy.as_image_copy(),
|
||||
self.depth.0.size(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -209,7 +209,7 @@ pub fn tilt_matrix(tilt: f32) -> Mat4 {
|
||||
}
|
||||
|
||||
/// The world direction of the shadow light (7.1): the sun by day, the moon by night.
|
||||
fn shadow_light(frame: &Frame, shadow: &Shadow) -> Vec3 {
|
||||
pub fn shadow_light(frame: &Frame, shadow: &Shadow) -> Vec3 {
|
||||
let sun_angle = (frame.sky.sun_angle / 360.0 + 0.25).rem_euclid(1.0);
|
||||
let angle = if sun_angle < 0.5 {
|
||||
frame.sky.sun_angle
|
||||
@@ -219,6 +219,19 @@ fn shadow_light(frame: &Frame, shadow: &Shadow) -> Vec3 {
|
||||
body(angle, shadow.sun_path_rotation).normalize()
|
||||
}
|
||||
|
||||
/// `shadow_camera`'s view and projection in wgpu's clip space (depth 0..1), for culling.
|
||||
pub fn shadow_culling(frame: &Frame, shadow: &Shadow) -> Mat4 {
|
||||
let (view, gl) = shadow_camera(shadow_light(frame, shadow), frame.camera, shadow);
|
||||
// GL's depth -w..w to wgpu's 0..w.
|
||||
let depth = Mat4::from_cols(
|
||||
Vec4::X,
|
||||
Vec4::Y,
|
||||
Vec4::new(0.0, 0.0, 0.5, 0.0),
|
||||
Vec4::new(0.0, 0.0, 0.5, 1.0),
|
||||
);
|
||||
depth * gl * view
|
||||
}
|
||||
|
||||
/// Distance from the snapped point to the shadow camera, toward the light: the middle of the
|
||||
/// default near and far planes (OQ-6).
|
||||
const SHADOW_EYE: f64 = 128.0;
|
||||
|
||||
@@ -77,6 +77,8 @@ pub struct ItemInfo {
|
||||
pub consumable: Option<horizon_world::consumable::Consumable<String, ConsumeEffect>>,
|
||||
/// `use_remainder`: what a finished use leaves (`UseRemainder`).
|
||||
pub use_remainder: Option<String>,
|
||||
/// `use_cooldown`: the cooldown a use starts (`UseCooldown`).
|
||||
pub use_cooldown: Option<crate::cooldowns::UseCooldown>,
|
||||
pub model: String,
|
||||
/// Main-hand `attack_damage` / `attack_speed` modifier amounts.
|
||||
pub attack_damage: f32,
|
||||
@@ -568,6 +570,9 @@ impl Items {
|
||||
use_remainder: c["minecraft:use_remainder"]["id"]
|
||||
.as_str()
|
||||
.map(str::to_owned),
|
||||
use_cooldown: c
|
||||
.get("minecraft:use_cooldown")
|
||||
.and_then(crate::cooldowns::UseCooldown::from_json),
|
||||
model: c["minecraft:item_model"]
|
||||
.as_str()
|
||||
.unwrap_or(name)
|
||||
|
||||
@@ -937,6 +937,20 @@ pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
|
||||
match entity {
|
||||
BlockEntity::Sign(sign) => Some(Tag::compound(sign.encode())),
|
||||
BlockEntity::Spawner(s) => Some(s.update_tag()),
|
||||
// SkullBlockEntity: the profile is the whole reason a head differs.
|
||||
BlockEntity::Skull(s) => {
|
||||
let mut entries = Vec::new();
|
||||
if let Some(profile) = &s.profile {
|
||||
entries.push(("profile", profile.clone()));
|
||||
}
|
||||
if let Some(sound) = &s.note_block_sound {
|
||||
entries.push(("note_block_sound", Tag::String(sound.as_str().into())));
|
||||
}
|
||||
if let Some(name) = &s.custom_name {
|
||||
entries.push(("custom_name", name.clone()));
|
||||
}
|
||||
Some(Tag::compound(entries))
|
||||
}
|
||||
BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None,
|
||||
// CampfireBlockEntity.getUpdateTag: the items alone.
|
||||
BlockEntity::Campfire(c) => Some(Tag::compound([(
|
||||
|
||||
@@ -46,6 +46,7 @@ pub mod confirm_screen;
|
||||
pub mod container_screen;
|
||||
pub mod containers;
|
||||
pub mod control;
|
||||
pub mod cooldowns;
|
||||
pub mod crafting;
|
||||
pub mod crash;
|
||||
pub mod creative;
|
||||
@@ -54,6 +55,8 @@ pub mod datapack;
|
||||
pub mod debug_chart;
|
||||
pub mod debug_keys;
|
||||
pub mod debug_overlay;
|
||||
pub mod dialog;
|
||||
pub mod dialog_screen;
|
||||
pub mod discord_presence;
|
||||
pub mod dynamic_light;
|
||||
pub mod effects;
|
||||
|
||||
@@ -69,18 +69,10 @@ pub fn register(m: &mut Mob) {
|
||||
}
|
||||
/// Chicken.aiStep: wing flapping, slowed falling and laying eggs.
|
||||
pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let a = &mut m.anim;
|
||||
a.flap_o = a.flap;
|
||||
a.flap_speed_o = a.flap_speed;
|
||||
a.flap_speed = (a.flap_speed + if m.on_ground { -1.0 } else { 4.0 } * 0.3).clamp(0.0, 1.0);
|
||||
if !m.on_ground && a.flapping < 1.0 {
|
||||
a.flapping = 1.0;
|
||||
}
|
||||
a.flapping *= 0.9;
|
||||
chicken_flap(m);
|
||||
if !m.on_ground && m.velocity.y < 0.0 {
|
||||
m.velocity.y *= 0.6;
|
||||
}
|
||||
a.flap += a.flapping * 2.0;
|
||||
if m.alive() && !m.is_baby() && !m.extra.jockey {
|
||||
m.extra.egg_time -= 1;
|
||||
if m.extra.egg_time <= 0 {
|
||||
@@ -95,6 +87,21 @@ pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Chicken.aiStep's wings: `flapSpeed` rises in the air and falls on the
|
||||
/// ground, `flapping` restarts at 1 in the air and decays, and `flap` turns
|
||||
/// by it. It runs on a client too, for the chickens it only displays (the
|
||||
/// falling slowdown and the eggs are the server's).
|
||||
pub fn chicken_flap(m: &mut Mob) {
|
||||
let a = &mut m.anim;
|
||||
a.flap_o = a.flap;
|
||||
a.flap_speed_o = a.flap_speed;
|
||||
a.flap_speed = (a.flap_speed + if m.on_ground { -1.0 } else { 4.0 } * 0.3).clamp(0.0, 1.0);
|
||||
if !m.on_ground && a.flapping < 1.0 {
|
||||
a.flapping = 1.0;
|
||||
}
|
||||
a.flapping *= 0.9;
|
||||
a.flap += a.flapping * 2.0;
|
||||
}
|
||||
/// Farm animal climate from the biome tags (`spawns_warm/cold_variant_farm_animals`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Climate {
|
||||
@@ -125,3 +132,39 @@ pub fn sheep_color(climate: Climate, random: &mut impl RandomSource) -> u8 {
|
||||
6
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_core::geometry::Vec3;
|
||||
|
||||
/// `chicken_flap` reads only the ground flag: any mob type will do.
|
||||
fn chicken() -> Mob {
|
||||
Mob::new(1, crate::mobs::sensor_scan_tests::kind(), Vec3::ZERO, 0.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_falling_chicken_flaps_and_a_landed_one_folds_its_wings() {
|
||||
let mut m = chicken();
|
||||
m.on_ground = true;
|
||||
chicken_flap(&mut m);
|
||||
assert_eq!(m.anim.flap_speed, 0.0);
|
||||
assert_eq!(m.anim.flap, 0.0);
|
||||
// In the air flapSpeed rises by 1.2 (clamped to 1), flapping restarts
|
||||
// at 1 and decays by 0.9, and flap turns by twice flapping.
|
||||
m.on_ground = false;
|
||||
chicken_flap(&mut m);
|
||||
assert_eq!(m.anim.flap_speed, 1.0);
|
||||
assert_eq!(m.anim.flapping, 0.9);
|
||||
assert_eq!(m.anim.flap, 1.8);
|
||||
chicken_flap(&mut m);
|
||||
assert_eq!(m.anim.flap_o, 1.8);
|
||||
assert_eq!(m.anim.flap_speed_o, 1.0);
|
||||
assert_eq!(m.anim.flap, 3.6);
|
||||
// Landed, flapSpeed falls by 0.3 a tick and flapping decays.
|
||||
m.on_ground = true;
|
||||
chicken_flap(&mut m);
|
||||
assert!((m.anim.flap_speed - 0.7).abs() < 1.0e-6);
|
||||
assert!((m.anim.flapping - 0.81).abs() < 1.0e-6);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,6 +167,11 @@ pub enum MotionEvent {
|
||||
InsidePortal {
|
||||
pos: BlockPos,
|
||||
},
|
||||
/// `LayeredCauldronBlock.handleEntityOnFireInside`: a burning player in
|
||||
/// a water or powder snow cauldron; the server lowers its fill level.
|
||||
CauldronExtinguish {
|
||||
pos: BlockPos,
|
||||
},
|
||||
/// `WitherRoseBlock.entityInside`: the player's box swept through a
|
||||
/// wither rose; the server adds its Wither unless peaceful.
|
||||
InsideWitherRose,
|
||||
@@ -1277,22 +1282,31 @@ impl MotionWorld<'_, '_, '_> {
|
||||
continue;
|
||||
}
|
||||
let powder_snow = name == "minecraft:powder_snow";
|
||||
let lava_cauldron = name == "minecraft:lava_cauldron";
|
||||
// A filled cauldron's content top in blocks: the lava's 15/16
|
||||
// (LavaCauldronBlock.FILLED_SHAPE), or a layered cauldron's
|
||||
// getPixelContentHeight, 6 + 3 per level (FILLED_SHAPES).
|
||||
let content_top = match name {
|
||||
"minecraft:lava_cauldron" => Some(15.0 / 16.0),
|
||||
"minecraft:water_cauldron" | "minecraft:powder_snow_cauldron" => {
|
||||
let level = self
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("level"))
|
||||
.and_then(|l| l.parse::<u8>().ok())
|
||||
.unwrap_or(1);
|
||||
Some((6.0 + 3.0 * f64::from(level)) / 16.0)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// getEntityInsideCollisionShape is the whole block but for powder
|
||||
// snow (its collision shape, the whole block when it is empty),
|
||||
// filled cauldrons, end portals and tripwires; Horizon doesn't
|
||||
// follow the player into the water and powder snow cauldrons, end
|
||||
// portals or tripwires yet.
|
||||
if matches!(
|
||||
name,
|
||||
"minecraft:water_cauldron"
|
||||
| "minecraft:powder_snow_cauldron"
|
||||
| "minecraft:end_portal"
|
||||
| "minecraft:tripwire"
|
||||
) {
|
||||
// follow the player into those last two.
|
||||
if matches!(name, "minecraft:end_portal" | "minecraft:tripwire") {
|
||||
continue;
|
||||
}
|
||||
let inside = !(powder_snow || lava_cauldron) || {
|
||||
let inside = !(powder_snow || content_top.is_some()) || {
|
||||
let context = self.context();
|
||||
let binding = self.collision_binding;
|
||||
let shape = binding.collision_shape_with_context(
|
||||
@@ -1305,12 +1319,12 @@ impl MotionWorld<'_, '_, '_> {
|
||||
|| {
|
||||
let offset = Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z));
|
||||
let mut boxes: Vec<_> = shape.moved(offset).boxes().to_vec();
|
||||
if lava_cauldron {
|
||||
// LavaCauldronBlock.FILLED_SHAPE: the cauldron's
|
||||
// shape or its lava, Block.column(12, 4, 15).
|
||||
if let Some(top) = content_top {
|
||||
// The cauldron's shape or its content,
|
||||
// Block.column(12, 4, top).
|
||||
boxes.push(Aabb::new(
|
||||
Vec3::new(2.0 / 16.0, 4.0 / 16.0, 2.0 / 16.0).add_vector(offset),
|
||||
Vec3::new(14.0 / 16.0, 15.0 / 16.0, 14.0 / 16.0).add_vector(offset),
|
||||
Vec3::new(14.0 / 16.0, top, 14.0 / 16.0).add_vector(offset),
|
||||
));
|
||||
}
|
||||
self.player
|
||||
@@ -1320,11 +1334,15 @@ impl MotionWorld<'_, '_, '_> {
|
||||
}
|
||||
};
|
||||
if inside && visited.insert(p.pack()) {
|
||||
// CactusBlock, CampfireBlock and LavaCauldronBlock.entityInside
|
||||
// (`entity.hurt`), and WitherRoseBlock's server-side effect.
|
||||
// CactusBlock, CampfireBlock and the cauldrons' entityInside
|
||||
// (`entity.hurt`, the fire and the fill level), and
|
||||
// WitherRoseBlock's server-side effect.
|
||||
match name {
|
||||
"minecraft:cactus" => self.environment_hurt("minecraft:cactus", 1.0)?,
|
||||
"minecraft:lava_cauldron" => self.lava_cauldron_inside()?,
|
||||
"minecraft:water_cauldron" | "minecraft:powder_snow_cauldron" => {
|
||||
self.layered_cauldron_inside(p);
|
||||
}
|
||||
"minecraft:wither_rose" => {
|
||||
self.player.events.push(MotionEvent::InsideWitherRose);
|
||||
}
|
||||
@@ -1395,6 +1413,18 @@ impl MotionWorld<'_, '_, '_> {
|
||||
self.player.ignite_for_ticks(300)?;
|
||||
self.environment_hurt("minecraft:lava", 4.0)
|
||||
}
|
||||
/// `LayeredCauldronBlock.entityInside`: on a server, a burning player
|
||||
/// asks for the cauldron's `handleEntityOnFireInside` (runBefore
|
||||
/// EXTINGUISH, so while still burning), then EXTINGUISH
|
||||
/// (`Entity.clearFire`) puts the fire out.
|
||||
fn layered_cauldron_inside(&mut self, pos: BlockPos) {
|
||||
if self.player.fire_ticks > 0 && !self.player.spectator {
|
||||
self.player
|
||||
.events
|
||||
.push(MotionEvent::CauldronExtinguish { pos });
|
||||
}
|
||||
self.player.fire_ticks = self.player.fire_ticks.min(0);
|
||||
}
|
||||
/// `WebBlock.entityInside`: stuck at a quarter of the speed, half with
|
||||
/// the Weaving effect.
|
||||
fn web_inside(&mut self) {
|
||||
@@ -2457,6 +2487,63 @@ mod tests {
|
||||
assert!(away.fire_ticks <= 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_water_cauldron_puts_out_a_burning_player() {
|
||||
let root = std::env::var_os("HORIZON_TEST_RESOURCES")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION)
|
||||
});
|
||||
if !root.join("movement-properties.nbt").exists() {
|
||||
return;
|
||||
}
|
||||
let assets = Assets::load(&root).unwrap();
|
||||
let render = assets.reload(&root).unwrap();
|
||||
let binding = crate::collisions::load(&root, assets.registry).unwrap();
|
||||
let resources = MotionResources::load(&root, &assets).unwrap();
|
||||
let mut scene = World::test_scene(&assets, &render, 1).unwrap();
|
||||
let water = assets
|
||||
.registry
|
||||
.resolve(&horizon_world::chunk::BlockState {
|
||||
name: "minecraft:water_cauldron".into(),
|
||||
properties: [("level".to_owned(), "3".to_owned())].into(),
|
||||
})
|
||||
.unwrap();
|
||||
scene.set(20, 4, 20, water).unwrap();
|
||||
let mut tick = |player: &mut PlayerMotion| {
|
||||
MotionWorld {
|
||||
entities: &[],
|
||||
player,
|
||||
scene: &mut scene,
|
||||
assets: &assets,
|
||||
collision_binding: &binding,
|
||||
resources: &resources,
|
||||
}
|
||||
.controlled_simulation_tick(Default::default())
|
||||
.unwrap();
|
||||
};
|
||||
let asks = |player: &PlayerMotion| {
|
||||
player
|
||||
.events
|
||||
.iter()
|
||||
.filter(|e| matches!(e, MotionEvent::CauldronExtinguish { .. }))
|
||||
.count()
|
||||
};
|
||||
// Burning, on the cauldron's floor in its water: put out, and the
|
||||
// server is asked to lower the water.
|
||||
let mut burning = PlayerMotion::new(&resources, Vec3::new(20.5, 4.25, 20.5)).unwrap();
|
||||
burning.fire_ticks = 100;
|
||||
tick(&mut burning);
|
||||
assert!(burning.fire_ticks <= 0, "the water must put the fire out");
|
||||
assert_eq!(asks(&burning), 1);
|
||||
// Not burning: nothing to lower.
|
||||
let mut dry = PlayerMotion::new(&resources, Vec3::new(20.5, 4.25, 20.5)).unwrap();
|
||||
tick(&mut dry);
|
||||
assert_eq!(asks(&dry), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standing_in_a_wither_rose_asks_for_its_effect() {
|
||||
let root = std::env::var_os("HORIZON_TEST_RESOURCES")
|
||||
|
||||
@@ -55,6 +55,10 @@ pub enum Event {
|
||||
PackPush(cfg::ResourcePackPush),
|
||||
/// ClientboundResourcePackPopPacket: one pack, or every pack.
|
||||
PackPop(Option<u128>),
|
||||
/// `show_dialog` in configuration: the dialog itself.
|
||||
ShowDialog(horizon_world::nbt::Tag),
|
||||
/// `clear_dialog` in configuration.
|
||||
ClearDialog,
|
||||
/// `ClientboundTransferPacket`: the server sent us to another address.
|
||||
/// The connection ends right after; the game reconnects there with the
|
||||
/// stored cookies.
|
||||
@@ -234,6 +238,25 @@ impl Session {
|
||||
w.shutdown();
|
||||
}
|
||||
}
|
||||
/// ServerboundCustomClickActionPacket (a dialog's answer), in whichever
|
||||
/// phase the connection is.
|
||||
pub fn send_custom_click(&self, id: &str, payload: Option<horizon_world::nbt::Tag>) {
|
||||
let click = cfg::CustomClickAction {
|
||||
id: id.to_owned(),
|
||||
payload,
|
||||
};
|
||||
let mut writer = self.writer.lock().unwrap();
|
||||
let body = if self.configuring.load(Ordering::Relaxed) {
|
||||
cfg::Serverbound::CustomClickAction(click).encode()
|
||||
} else {
|
||||
play::Serverbound::CustomClickAction(click).encode()
|
||||
};
|
||||
if let Some(w) = writer.as_mut()
|
||||
&& w.send(&body).is_err()
|
||||
{
|
||||
w.shutdown();
|
||||
}
|
||||
}
|
||||
pub fn disconnect(&mut self) {
|
||||
if let Some(w) = self.writer.lock().unwrap().take() {
|
||||
w.shutdown();
|
||||
@@ -602,6 +625,13 @@ fn configure(
|
||||
cfg::Clientbound::ResourcePackPop(p) => {
|
||||
let _ = send.send(Event::PackPop(p.id));
|
||||
}
|
||||
// The game shows it; the answer goes back from there.
|
||||
cfg::Clientbound::ShowDialog(d) => {
|
||||
let _ = send.send(Event::ShowDialog(d.dialog));
|
||||
}
|
||||
cfg::Clientbound::ClearDialog(_) => {
|
||||
let _ = send.send(Event::ClearDialog);
|
||||
}
|
||||
cfg::Clientbound::CookieRequest(q) => {
|
||||
let payload = cookies.lock().unwrap().get(&q.key).cloned();
|
||||
reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse {
|
||||
|
||||
@@ -831,6 +831,7 @@ impl PackScreen {
|
||||
d::label(&mut out, &lines, mx, my, self.width - 50, true);
|
||||
for ((bx, by), key) in buttons.into_iter().zip(["gui.yes", "gui.no"]) {
|
||||
let hover = d::inside(mouse, bx, by, 150, 20);
|
||||
crate::widgets::widget_cursor(hover, true);
|
||||
d::button(&mut out, m, &tr(key), bx, by, 150, 20, true, hover);
|
||||
}
|
||||
return out;
|
||||
@@ -856,6 +857,8 @@ impl PackScreen {
|
||||
} else {
|
||||
"gui.done"
|
||||
});
|
||||
// The cursor follows the mouse; the highlight also keyboard focus.
|
||||
crate::widgets::widget_cursor(hover, true);
|
||||
d::button(
|
||||
&mut out,
|
||||
m,
|
||||
|
||||
@@ -572,6 +572,23 @@ impl Projectile {
|
||||
}
|
||||
(self.position.y > -128.0, Hit::None)
|
||||
}
|
||||
/// AbstractHurtingProjectile.applyInertia, on both server and client.
|
||||
pub fn apply_hurting_inertia(&mut self, water: bool) {
|
||||
// WitherSkull.getInertia: 0.73 for dangerous skulls.
|
||||
let inertia = match self.kind {
|
||||
ProjectileKind::WitherSkull { dangerous: true } => 0.73,
|
||||
_ if water => 0.8,
|
||||
_ => 0.95,
|
||||
};
|
||||
let v = self.velocity;
|
||||
let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9);
|
||||
self.velocity = Vec3::new(
|
||||
(v.x + v.x / len * self.acceleration) * inertia,
|
||||
(v.y + v.y / len * self.acceleration) * inertia,
|
||||
(v.z + v.z / len * self.acceleration) * inertia,
|
||||
);
|
||||
}
|
||||
|
||||
/// One tick: returns whether to keep the projectile and what it hit.
|
||||
pub fn tick(&mut self, w: &impl ProjectileWorld) -> (bool, Hit) {
|
||||
self.previous = self.position;
|
||||
@@ -584,19 +601,7 @@ impl Projectile {
|
||||
ProjectileKind::SmallFireball
|
||||
| ProjectileKind::LargeFireball { .. }
|
||||
| ProjectileKind::WitherSkull { .. } => {
|
||||
// WitherSkull.getInertia: 0.73 for dangerous skulls.
|
||||
let inertia = match self.kind {
|
||||
ProjectileKind::WitherSkull { dangerous: true } => 0.73,
|
||||
_ if water => 0.8,
|
||||
_ => 0.95,
|
||||
};
|
||||
let v = self.velocity;
|
||||
let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9);
|
||||
self.velocity = Vec3::new(
|
||||
(v.x + v.x / len * self.acceleration) * inertia,
|
||||
(v.y + v.y / len * self.acceleration) * inertia,
|
||||
(v.z + v.z / len * self.acceleration) * inertia,
|
||||
);
|
||||
self.apply_hurting_inertia(water);
|
||||
}
|
||||
// Arrows tick with `arrows::tick`.
|
||||
ProjectileKind::Arrow { .. } => {}
|
||||
@@ -819,6 +824,21 @@ mod tests {
|
||||
// (0.1 + 0.1) * 0.95
|
||||
assert!((p.velocity.x - 0.19).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fireball_inertia_preserves_custom_acceleration() {
|
||||
let mut p = Projectile::fireball(
|
||||
ProjectileKind::SmallFireball,
|
||||
Vec3::new(0.0, 100.0, 0.0),
|
||||
None,
|
||||
[1.0, 0.0, 0.0],
|
||||
);
|
||||
// A redirected projectile can carry a different acceleration power.
|
||||
p.acceleration = 0.2;
|
||||
p.tick(&Empty(vec![]));
|
||||
assert!((p.velocity.x - 0.285).abs() < 1e-9);
|
||||
assert!((p.position.x - 0.285).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -559,6 +559,17 @@ pub fn encode_block_entity(
|
||||
entries.push(("creaking", uuid_tag(uuid)));
|
||||
}
|
||||
}
|
||||
BlockEntity::Skull(s) => {
|
||||
if let Some(profile) = &s.profile {
|
||||
entries.push(("profile", profile.clone()));
|
||||
}
|
||||
if let Some(sound) = &s.note_block_sound {
|
||||
entries.push(("note_block_sound", string(sound)));
|
||||
}
|
||||
if let Some(name) = &s.custom_name {
|
||||
entries.push(("custom_name", name.clone()));
|
||||
}
|
||||
}
|
||||
BlockEntity::Spawner(s) => entries.extend(s.save()),
|
||||
BlockEntity::TrialSpawner(s) => entries.extend(s.save()),
|
||||
BlockEntity::Vault(v) => entries.extend(v.save()),
|
||||
@@ -634,6 +645,18 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
|
||||
};
|
||||
return Some((pos, BlockEntity::Beacon(Box::new(beacon))));
|
||||
}
|
||||
// A skull's block entity id is not its block's name (every head block).
|
||||
if id == "minecraft:skull" {
|
||||
return Some((
|
||||
pos,
|
||||
BlockEntity::Skull(crate::containers::Skull::new(
|
||||
tag.get("profile").cloned(),
|
||||
text(tag.get("note_block_sound")),
|
||||
tag.get("custom_name")
|
||||
.and_then(crate::block_entity_nbt::component),
|
||||
)),
|
||||
));
|
||||
}
|
||||
// A spawner's block entity id is not its block's name.
|
||||
let block = match id.as_str() {
|
||||
"minecraft:mob_spawner" => "minecraft:spawner",
|
||||
@@ -718,7 +741,8 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
|
||||
| BlockEntity::Beacon(_)
|
||||
| BlockEntity::Lectern(_)
|
||||
| BlockEntity::Banner(_)
|
||||
| BlockEntity::CreakingHeart(_) => {}
|
||||
| BlockEntity::CreakingHeart(_)
|
||||
| BlockEntity::Skull(_) => {}
|
||||
BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag),
|
||||
BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag),
|
||||
BlockEntity::Vault(v) => **v = crate::vault::Vault::load(tag),
|
||||
@@ -3936,6 +3960,54 @@ mod tests {
|
||||
}
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn skull_block_entity_keeps_its_profile() {
|
||||
// A placed `player_head` as vanilla saves it: the owning player's
|
||||
// `profile` survives load, encode and `canonical`.
|
||||
let saved = horizon_world::nbt::parse_snbt(
|
||||
r#"{id:"minecraft:skull",x:10,y:64,z:20,profile:{name:"Steve",id:[I;1,2,3,4],properties:[{name:"textures",value:"abc"}]},note_block_sound:"minecraft:entity.player.hurt",custom_name:"Trophy"}"#,
|
||||
)
|
||||
.unwrap()
|
||||
.0;
|
||||
let (pos, back) = decode_block_entity(&saved).expect("skull");
|
||||
assert_eq!(pos, (10, 64, 20));
|
||||
let crate::containers::BlockEntity::Skull(skull) = &back else {
|
||||
panic!("not a skull");
|
||||
};
|
||||
assert_eq!(skull.profile, saved.get("profile").cloned());
|
||||
assert_eq!(
|
||||
skull.note_block_sound.as_deref(),
|
||||
Some("minecraft:entity.player.hurt")
|
||||
);
|
||||
assert_eq!(back.id(), "minecraft:skull");
|
||||
let tag = encode_block_entity(pos, &back, "minecraft:player_head");
|
||||
assert_eq!(
|
||||
crate::block_entity_nbt::id(&tag).as_deref(),
|
||||
Some("minecraft:skull")
|
||||
);
|
||||
assert_eq!(tag.get("profile"), saved.get("profile"));
|
||||
let (_, again) = decode_block_entity(&tag).expect("skull again");
|
||||
let crate::containers::BlockEntity::Skull(again) = again else {
|
||||
panic!("not a skull");
|
||||
};
|
||||
assert_eq!(again.profile, skull.profile);
|
||||
// A profile-less head (skeleton, creeper) round-trips too.
|
||||
let plain = encode_block_entity(
|
||||
pos,
|
||||
&crate::containers::BlockEntity::Skull(crate::containers::Skull::default()),
|
||||
"minecraft:creeper_head",
|
||||
);
|
||||
let (_, decoded) = decode_block_entity(&plain).expect("plain skull");
|
||||
assert!(matches!(decoded, crate::containers::BlockEntity::Skull(_)));
|
||||
// The heads and skulls have one; the piston's head is no skull.
|
||||
use crate::containers::BlockEntity;
|
||||
assert!(matches!(
|
||||
BlockEntity::for_block("minecraft:player_wall_head"),
|
||||
Some(BlockEntity::Skull(_))
|
||||
));
|
||||
assert!(BlockEntity::for_block("minecraft:piston_head").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uuid_text_round_trips() {
|
||||
let u = [-158327916, 1572358581, -2125825222, -487948715];
|
||||
|
||||
@@ -130,6 +130,47 @@ pub fn profile_skin_url(profile: &serde_json::Value) -> Option<String> {
|
||||
unpack(value, Signature::Unsigned, &TEXTURE_URIS).skin
|
||||
}
|
||||
|
||||
/// `profile_skin_url` on a block entity's `profile` NBT (`SkullBlockEntity`):
|
||||
/// the same `properties` list, held as a compound. A name-only profile (a
|
||||
/// string tag) has no properties and no skin URL.
|
||||
pub fn profile_skin_url_nbt(profile: &horizon_world::nbt::Tag) -> Option<String> {
|
||||
let properties = match profile.get("properties")? {
|
||||
horizon_world::nbt::Tag::List(list) => list,
|
||||
_ => return None,
|
||||
};
|
||||
let value = properties.iter().find_map(|p| {
|
||||
let name = nbt_text(p.get("name"))?;
|
||||
(name == "textures")
|
||||
.then(|| nbt_text(p.get("value")))
|
||||
.flatten()
|
||||
})?;
|
||||
unpack(&value, Signature::Unsigned, &TEXTURE_URIS).skin
|
||||
}
|
||||
|
||||
/// The profile's uuid as u128: `id` as an int array (block entity NBT) or a
|
||||
/// uuid string (older and component forms). Used for `DefaultPlayerSkin.get`
|
||||
/// when a head's skin is not downloaded yet.
|
||||
pub fn profile_uuid_nbt(profile: &horizon_world::nbt::Tag) -> Option<u128> {
|
||||
match profile.get("id")? {
|
||||
horizon_world::nbt::Tag::IntArray(v) if v.len() == 4 => Some(
|
||||
v.iter()
|
||||
.fold(0u128, |a, &w| (a << 32) | u128::from(w as u32)),
|
||||
),
|
||||
horizon_world::nbt::Tag::String(s) => {
|
||||
let digits: String = s.to_string_lossy().chars().filter(|c| *c != '-').collect();
|
||||
u128::from_str_radix(&digits, 16).ok()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option<String> {
|
||||
match tag {
|
||||
Some(horizon_world::nbt::Tag::String(s)) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `MinecraftProfileTexture.getHash`: the base name of the URL's path.
|
||||
pub fn texture_hash(url: &str) -> Option<String> {
|
||||
let rest = url.split_once("://")?.1;
|
||||
@@ -457,6 +498,42 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn skull_block_entity_profiles_supply_head_skins() {
|
||||
let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0=";
|
||||
let profile = horizon_world::nbt::parse_snbt(&format!(
|
||||
r#"{{name:"T",id:[I;-158327916,1572358581,-2125825222,-487948715],properties:[{{name:"textures",value:"{value}"}}]}}"#
|
||||
))
|
||||
.unwrap()
|
||||
.0;
|
||||
assert_eq!(
|
||||
super::profile_skin_url_nbt(&profile).as_deref(),
|
||||
Some("https://textures.minecraft.net/texture/abc123")
|
||||
);
|
||||
assert_eq!(
|
||||
super::profile_uuid_nbt(&profile),
|
||||
Some(
|
||||
[-158327916, 1572358581, -2125825222, -487948715]
|
||||
.iter()
|
||||
.fold(0u128, |a, &w: &i32| (a << 32) | u128::from(w as u32))
|
||||
)
|
||||
);
|
||||
// A name-only profile (a string tag) has no properties: no url, no id.
|
||||
let named = horizon_world::nbt::Tag::String("MHF_Blaze".into());
|
||||
assert_eq!(super::profile_skin_url_nbt(&named), None);
|
||||
assert_eq!(super::profile_uuid_nbt(&named), None);
|
||||
// A uuid in string form decodes too.
|
||||
let text_id = horizon_world::nbt::parse_snbt(
|
||||
r#"{name:"T",id:"e843a1f4-0000-0001-0000-000200000003"}"#,
|
||||
)
|
||||
.unwrap()
|
||||
.0;
|
||||
assert_eq!(
|
||||
super::profile_uuid_nbt(&text_id),
|
||||
Some(u128::from_str_radix("e843a1f4000000010000000200000003", 16).unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha1_and_base64() {
|
||||
let hex: String = sha1(b"abc").iter().map(|b| format!("{b:02x}")).collect();
|
||||
|
||||
@@ -317,6 +317,7 @@ pub fn button(
|
||||
hover: bool,
|
||||
) {
|
||||
crate::widgets::record(&label.plain(), [x, y, w, h], active);
|
||||
crate::widgets::widget_cursor(hover, active);
|
||||
let sprite = if !active {
|
||||
"gui/sprites/widget/button_disabled"
|
||||
} else if hover {
|
||||
|
||||
@@ -1,8 +1,47 @@
|
||||
//! The labelled widgets and focus targets drawn in the last frame, for the
|
||||
//! control socket: a script clicks a button by its label (`horizon-ctl
|
||||
//! click-button Respawn`) or any widget by its id in [`tree`] (`horizon-ctl
|
||||
//! click done`), whatever screen drew it.
|
||||
use std::cell::RefCell;
|
||||
//! click done`), whatever screen drew it. Also the mouse cursor the widget
|
||||
//! under the mouse asks for.
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
/// The mouse cursor a frame's widgets asked for (`CursorTypes`; the others
|
||||
/// aren't asked for yet).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Cursor {
|
||||
#[default]
|
||||
Arrow,
|
||||
PointingHand,
|
||||
NotAllowed,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// `GuiGraphicsExtractor.requestCursor`: the last request since [`take_cursor`].
|
||||
static CURSOR: Cell<Cursor> = const { Cell::new(Cursor::Arrow) };
|
||||
}
|
||||
|
||||
/// `GuiGraphicsExtractor.requestCursor`: the last request of a frame wins.
|
||||
pub fn request_cursor(cursor: Cursor) {
|
||||
CURSOR.set(cursor);
|
||||
}
|
||||
|
||||
/// `AbstractWidget.handleCursor`: a hovered widget asks for the pointing
|
||||
/// hand, or for not-allowed when it is inactive.
|
||||
pub fn widget_cursor(hovered: bool, active: bool) {
|
||||
if hovered {
|
||||
request_cursor(if active {
|
||||
Cursor::PointingHand
|
||||
} else {
|
||||
Cursor::NotAllowed
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor the frame asked for, and back to the arrow for the next one
|
||||
/// (the window shows the arrow unless a widget asks).
|
||||
pub fn take_cursor() -> Cursor {
|
||||
CURSOR.replace(Cursor::Arrow)
|
||||
}
|
||||
|
||||
/// A labelled widget in GUI pixels (the coordinates screens take input in).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -133,6 +172,29 @@ pub fn record_as(label: &str, [x, y, w, h]: [f32; 4], enabled: bool, kind: Kind)
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cursor_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hovered_widgets_ask_for_the_hand_or_not_allowed() {
|
||||
let _ = take_cursor();
|
||||
widget_cursor(false, true);
|
||||
assert_eq!(take_cursor(), Cursor::Arrow);
|
||||
widget_cursor(true, true);
|
||||
assert_eq!(take_cursor(), Cursor::PointingHand);
|
||||
// Taken: the next frame starts from the arrow.
|
||||
assert_eq!(take_cursor(), Cursor::Arrow);
|
||||
widget_cursor(true, false);
|
||||
assert_eq!(take_cursor(), Cursor::NotAllowed);
|
||||
// The last request of a frame wins.
|
||||
widget_cursor(true, false);
|
||||
widget_cursor(false, true);
|
||||
widget_cursor(true, true);
|
||||
assert_eq!(take_cursor(), Cursor::PointingHand);
|
||||
}
|
||||
}
|
||||
|
||||
/// Once per event loop turn with the count of rendered frames: when a new
|
||||
/// frame was drawn since the last call, its buttons become the last frame's.
|
||||
pub fn end_frame(frames: u64) {
|
||||
|
||||
@@ -7,7 +7,7 @@ rust-version = "1.85"
|
||||
description = "Write Horizon mods in Rust: WebAssembly components for the horizon:mod world (docs/mods.md)"
|
||||
|
||||
[dependencies]
|
||||
wit-bindgen = { version = "0.57.1", default-features = false, features = ["macros", "realloc"] }
|
||||
wit-bindgen = { version = "0.60.0", default-features = false, features = ["macros", "realloc"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -128,9 +128,20 @@ interface ui {
|
||||
selected: option<u32>,
|
||||
}
|
||||
/// A thing on a mod's screen or settings page.
|
||||
/// A button as the options pages have them (200 × 20): a click is
|
||||
/// `ui-events::select(id, 0)`. Mods cycle its label for a choice
|
||||
/// ("Corner: Top Left").
|
||||
record button-widget {
|
||||
/// The mod's own name for the widget.
|
||||
id: u32,
|
||||
/// Up to 256 characters.
|
||||
label: string,
|
||||
}
|
||||
variant widget {
|
||||
/// Text the player reads.
|
||||
text(text-widget),
|
||||
/// A button.
|
||||
button(button-widget),
|
||||
/// An item's icon and name.
|
||||
item(item-widget),
|
||||
/// Rows the player picks from.
|
||||
@@ -211,6 +222,20 @@ interface input {
|
||||
held: func() -> option<held-item>;
|
||||
/// The events since the last call, oldest first.
|
||||
poll: func() -> list<event>;
|
||||
/// A mapping as the player has bound it.
|
||||
record mapping-state {
|
||||
/// The bound key's name as Controls shows it: `W`, `Space`, `LMB`.
|
||||
label: string,
|
||||
/// Held down now (as of this frame for a mod with a `frame` hook,
|
||||
/// else this tick).
|
||||
down: bool,
|
||||
}
|
||||
/// A movement or click mapping as the player has bound it: `key.forward`,
|
||||
/// `key.left`, `key.back`, `key.right`, `key.jump`, `key.sneak`,
|
||||
/// `key.sprint`, `key.attack` or `key.use`. None for another name.
|
||||
mapping: func(name: string) -> option<mapping-state>;
|
||||
/// Clicks of the attack and use buttons in the last second.
|
||||
clicks-per-second: func() -> tuple<u32, u32>;
|
||||
}
|
||||
|
||||
/// Capability `render` (experimental: the manifest needs
|
||||
@@ -218,6 +243,13 @@ interface input {
|
||||
/// own renderer, kept until the mod replaces them (no call per frame). A mod
|
||||
/// never supplies shader code.
|
||||
interface render {
|
||||
/// A corner of the screen, as `hud`'s panels use them.
|
||||
enum corner {
|
||||
top-left,
|
||||
top-right,
|
||||
bottom-left,
|
||||
bottom-right,
|
||||
}
|
||||
/// A rectangle in GUI pixels: the top left corner and the size.
|
||||
record rect {
|
||||
x: f32,
|
||||
@@ -287,6 +319,26 @@ interface render {
|
||||
/// turns, the player doesn't, and the player's Distortion Effects option
|
||||
/// scales it (0 turns it off).
|
||||
shake: func(strength: f32, seconds: f32);
|
||||
/// Replaces the mod's corner panel: shapes in GUI pixels from the top
|
||||
/// left of a `width` × `height` box that the game places in `corner`,
|
||||
/// stacked with the game's overlays and the other mods' panels (under
|
||||
/// the status effects at the top right), as `hud`'s panels are.
|
||||
set-corner: func(corner: corner, width: f32, height: f32, shapes: list<shape>);
|
||||
/// Removes the mod's corner panel.
|
||||
clear-corner: func();
|
||||
/// The width of one line of text in GUI pixels, in the HUD's font: exact
|
||||
/// for Latin letters (U+0000 to U+024F), 6 per other character.
|
||||
text-width: func(text: string) -> f32;
|
||||
record frame-rate {
|
||||
/// Frames drawn in the last second.
|
||||
fps: u32,
|
||||
/// The slowest frame's rate, and the 1% low (the 99th percentile
|
||||
/// frame time's rate), over the last 5 seconds.
|
||||
min: u32,
|
||||
low: u32,
|
||||
}
|
||||
/// The game's frame counter, recomputed twice a second.
|
||||
frame-stats: func() -> frame-rate;
|
||||
}
|
||||
|
||||
/// What the game calls. Only the hooks `init` asks for are ever called.
|
||||
|
||||
@@ -3,7 +3,7 @@ name = "horizon-mods"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.86"
|
||||
rust-version = "1.95"
|
||||
description = "Horizon's mod runtime: sandboxed WebAssembly components (docs/mods.md)"
|
||||
|
||||
[dependencies]
|
||||
@@ -12,11 +12,11 @@ serde_json = "1"
|
||||
toml = "1.1.6"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
log = "0.4"
|
||||
# The 36 LTS line: security fixes until August 2027, and it builds on the client's Rust.
|
||||
wasmtime = { version = "36.0.18", default-features = false, features = ["runtime", "cranelift", "component-model", "std"], optional = true }
|
||||
# The 48 LTS line: security fixes until August 2028, on the same wasm-tools (0.254) as wit-component and the SDK's wit-bindgen.
|
||||
wasmtime = { version = "48.0.7", default-features = false, features = ["runtime", "cranelift", "component-model", "std"], optional = true }
|
||||
# Turns a mod's core module into a component (cargo horizon-mod build, the tests).
|
||||
wit-component = { version = "0.239", optional = true }
|
||||
wit-parser = { version = "0.239", optional = true }
|
||||
wit-component = { version = "0.254", optional = true }
|
||||
wit-parser = { version = "0.254", optional = true }
|
||||
# The registry index's checks (feature `index`): SHA-256, and minisign signatures (no dependencies of its own).
|
||||
sha2 = { version = "0.10", optional = true }
|
||||
minisign-verify = { version = "0.3", optional = true }
|
||||
|
||||
@@ -138,7 +138,9 @@ impl Capability {
|
||||
Capability::Registries => "add blocks and items to your worlds",
|
||||
Capability::Ui => "show its own screens and a settings page",
|
||||
Capability::Render => "draw on your screen and shake the camera",
|
||||
Capability::Input => "take over the use button on its own items, and add keys",
|
||||
Capability::Input => {
|
||||
"see the keys you hold and your clicks, take over the use button on its own items, and add keys"
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The capability a component import needs, `Ok(None)` for one every
|
||||
|
||||
@@ -37,7 +37,7 @@ use bindings::{
|
||||
/// The widget model a `ui` screen or settings page shows (WIT `interface
|
||||
/// ui`), for the game to draw with its menus' own widgets.
|
||||
pub use ui_bindings::horizon::mods::ui::{
|
||||
ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget,
|
||||
ButtonWidget, ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget,
|
||||
};
|
||||
use ui_bindings::{UiHost, horizon::mods::ui};
|
||||
/// Capability `render`'s imports (docs/mods.md): the game draws the shapes.
|
||||
@@ -52,8 +52,8 @@ use render_bindings::horizon::mods::input;
|
||||
pub use render_bindings::horizon::mods::input::{Event as InputEvent, HeldItem, ItemUse};
|
||||
/// What capability `render` asks the game to draw (WIT `interface render`).
|
||||
pub use render_bindings::horizon::mods::render::{
|
||||
FillShape, ItemShape, Point as RenderPoint, QuadShape, Rect as RenderRect, Shape, SpriteShape,
|
||||
TextShape,
|
||||
Corner as RenderCorner, FillShape, FrameRate, ItemShape, Point as RenderPoint, QuadShape,
|
||||
Rect as RenderRect, Shape, SpriteShape, TextShape,
|
||||
};
|
||||
use render_bindings::{RenderHost, horizon::mods::render};
|
||||
|
||||
@@ -90,6 +90,16 @@ pub struct Snapshot {
|
||||
pub gui_size: (f32, f32),
|
||||
/// The main hand's stack (capability `input`'s `held`).
|
||||
pub held: Option<HeldItem>,
|
||||
/// The game's frame counter: fps, min, 1% low (`render.frame-stats`).
|
||||
pub frame: (u32, u32, u32),
|
||||
/// The movement and click mappings `input.mapping` answers for:
|
||||
/// (mapping, the bound key's label, held).
|
||||
pub mappings: Vec<(&'static str, String, bool)>,
|
||||
/// Attack and use clicks in the last second.
|
||||
pub cps: (u32, u32),
|
||||
/// The HUD font's advance per character from U+0000
|
||||
/// (`render.text-width`); empty: 6 each.
|
||||
pub font_widths: Arc<[f32]>,
|
||||
}
|
||||
|
||||
/// What mods asked the game to show since the last [`Mods::drain`].
|
||||
@@ -180,6 +190,8 @@ struct State {
|
||||
ui: UiState,
|
||||
/// Capability `render`'s HUD shapes, drawn until replaced.
|
||||
shapes: Vec<Shape>,
|
||||
/// Capability `render`'s corner panel.
|
||||
corner: Option<CornerPanel>,
|
||||
input: InputState,
|
||||
/// Capability `storage`'s folder; made on first `set`.
|
||||
data_dir: PathBuf,
|
||||
@@ -321,6 +333,7 @@ impl Mods {
|
||||
panel: None,
|
||||
ui: UiState::default(),
|
||||
shapes: Vec::new(),
|
||||
corner: None,
|
||||
input: InputState::default(),
|
||||
data_dir,
|
||||
storage_budget: STORAGE_WRITE_BUDGET,
|
||||
@@ -513,6 +526,19 @@ impl Mods {
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref()?.store.data().panel.as_ref())
|
||||
}
|
||||
/// The running mods' corner panels (capability `render`), in load order.
|
||||
pub fn corner_panels(&self) -> impl Iterator<Item = &CornerPanel> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref()?.store.data().corner.as_ref())
|
||||
}
|
||||
/// Some running mod has a `frame` hook: the game refreshes the snapshot
|
||||
/// every frame for it.
|
||||
pub fn wants_frames(&self) -> bool {
|
||||
self.entries
|
||||
.iter()
|
||||
.any(|e| e.run.as_ref().is_some_and(|r| r.hooks.frame))
|
||||
}
|
||||
/// Some running mod claimed items (capability `input`).
|
||||
pub fn claims_any(&self) -> bool {
|
||||
self.inputs().any(|i| !i.claimed.is_empty())
|
||||
@@ -731,6 +757,10 @@ fn clip_widgets(widgets: Vec<UiWidget>) -> Vec<UiWidget> {
|
||||
t.text = clip(t.text);
|
||||
UiWidget::Text(t)
|
||||
}
|
||||
UiWidget::Button(mut b) => {
|
||||
b.label = clip(b.label);
|
||||
UiWidget::Button(b)
|
||||
}
|
||||
UiWidget::Item(mut i) => {
|
||||
i.item = clip(i.item);
|
||||
i.name = clip(i.name);
|
||||
@@ -852,6 +882,16 @@ impl input::Host for State {
|
||||
fn poll(&mut self) -> Vec<InputEvent> {
|
||||
self.input.events.drain(..).collect()
|
||||
}
|
||||
fn mapping(&mut self, name: String) -> Option<input::MappingState> {
|
||||
let (_, label, down) = self.snapshot.mappings.iter().find(|m| m.0 == name)?;
|
||||
Some(input::MappingState {
|
||||
label: label.clone(),
|
||||
down: *down,
|
||||
})
|
||||
}
|
||||
fn clicks_per_second(&mut self) -> (u32, u32) {
|
||||
self.snapshot.cps
|
||||
}
|
||||
}
|
||||
|
||||
/// HUD shapes one mod may keep (capability `render`).
|
||||
@@ -859,33 +899,76 @@ const SHAPES: usize = 1024;
|
||||
/// The longest jolt `render.shake` makes, in seconds.
|
||||
const SHAKE_SECONDS: f32 = 10.0;
|
||||
|
||||
/// A mod's corner panel: shapes in a `width` × `height` box the game
|
||||
/// places in `corner`, stacked with the other overlays.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CornerPanel {
|
||||
pub corner: RenderCorner,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub shapes: Vec<Shape>,
|
||||
}
|
||||
|
||||
fn clip_shapes(shapes: Vec<Shape>) -> Vec<Shape> {
|
||||
shapes
|
||||
.into_iter()
|
||||
.take(SHAPES)
|
||||
.map(|shape| match shape {
|
||||
Shape::Sprite(mut s) => {
|
||||
s.sprite = clip(s.sprite);
|
||||
Shape::Sprite(s)
|
||||
}
|
||||
Shape::Item(mut i) => {
|
||||
i.item = clip(i.item);
|
||||
i.scale = if i.scale.is_finite() {
|
||||
i.scale.clamp(0.0, 16.0)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
Shape::Item(i)
|
||||
}
|
||||
Shape::Text(mut t) => {
|
||||
t.text = clip(t.text);
|
||||
t.color &= 0xFF_FFFF;
|
||||
Shape::Text(t)
|
||||
}
|
||||
other => other,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl render::Host for State {
|
||||
fn set_hud(&mut self, shapes: Vec<Shape>) {
|
||||
self.shapes = shapes
|
||||
.into_iter()
|
||||
.take(SHAPES)
|
||||
.map(|shape| match shape {
|
||||
Shape::Sprite(mut s) => {
|
||||
s.sprite = clip(s.sprite);
|
||||
Shape::Sprite(s)
|
||||
}
|
||||
Shape::Item(mut i) => {
|
||||
i.item = clip(i.item);
|
||||
i.scale = if i.scale.is_finite() {
|
||||
i.scale.clamp(0.0, 16.0)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
Shape::Item(i)
|
||||
}
|
||||
Shape::Text(mut t) => {
|
||||
t.text = clip(t.text);
|
||||
t.color &= 0xFF_FFFF;
|
||||
Shape::Text(t)
|
||||
}
|
||||
other => other,
|
||||
})
|
||||
.collect();
|
||||
self.shapes = clip_shapes(shapes);
|
||||
}
|
||||
fn set_corner(&mut self, corner: RenderCorner, width: f32, height: f32, shapes: Vec<Shape>) {
|
||||
let size = |v: f32| {
|
||||
if v.is_finite() {
|
||||
v.clamp(0.0, 1024.0)
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
};
|
||||
self.corner = Some(CornerPanel {
|
||||
corner,
|
||||
width: size(width),
|
||||
height: size(height),
|
||||
shapes: clip_shapes(shapes),
|
||||
});
|
||||
}
|
||||
fn clear_corner(&mut self) {
|
||||
self.corner = None;
|
||||
}
|
||||
fn text_width(&mut self, text: String) -> f32 {
|
||||
let widths = &self.snapshot.font_widths;
|
||||
text.chars()
|
||||
.map(|c| widths.get(c as usize).copied().unwrap_or(6.0))
|
||||
.sum::<f32>()
|
||||
.ceil()
|
||||
}
|
||||
fn frame_stats(&mut self) -> FrameRate {
|
||||
let (fps, min, low) = self.snapshot.frame;
|
||||
FrameRate { fps, min, low }
|
||||
}
|
||||
fn gui_size(&mut self) -> (f32, f32) {
|
||||
self.snapshot.gui_size
|
||||
|
||||
@@ -52,7 +52,7 @@ fn definition(resolve: &Resolve, kind: &TypeDefKind) -> String {
|
||||
match kind {
|
||||
TypeDefKind::Option(t) => format!("option<{}>", ty(resolve, t)),
|
||||
TypeDefKind::List(t) => format!("list<{}>", ty(resolve, t)),
|
||||
TypeDefKind::FixedSizeList(t, n) => format!("list<{}, {n}>", ty(resolve, t)),
|
||||
TypeDefKind::FixedLengthList(t, n) => format!("list<{}, {n}>", ty(resolve, t)),
|
||||
TypeDefKind::Result(r) => match (&r.ok, &r.err) {
|
||||
(None, None) => "result".into(),
|
||||
(ok, None) => format!("result<{}>", of(ok)),
|
||||
@@ -82,7 +82,7 @@ fn signature(resolve: &Resolve, f: &Function) -> String {
|
||||
let params: Vec<_> = f
|
||||
.params
|
||||
.iter()
|
||||
.map(|(name, t)| format!("{name}: {}", ty(resolve, t)))
|
||||
.map(|p| format!("{}: {}", p.name, ty(resolve, &p.ty)))
|
||||
.collect();
|
||||
let result = f
|
||||
.result
|
||||
|
||||
@@ -98,7 +98,7 @@ fn player() -> Snapshot {
|
||||
day_time: 24000 + 6000,
|
||||
}),
|
||||
gui_size: (427.0, 240.0),
|
||||
held: None,
|
||||
..Snapshot::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,7 +449,7 @@ fn ui_screens_settings_and_events() {
|
||||
assert_eq!(mods.settings_widgets(0).len(), 3);
|
||||
assert!(mods.entries()[0].has_ui_settings());
|
||||
mods.ui_settings_opened(0);
|
||||
assert_eq!(mods.settings_widgets(0).len(), 1);
|
||||
assert_eq!(mods.settings_widgets(0).len(), 2);
|
||||
// `/ui_close` closes the mod's own screen.
|
||||
assert!(mods.command("ui_close"));
|
||||
assert!(mods.drain().contains(&Output::CloseScreen { owner: 0 }));
|
||||
@@ -461,7 +461,6 @@ fn render_shapes_and_shakes() {
|
||||
let mut mods = load("horizon_mods_test_ui_guest.hmod");
|
||||
mods.set_snapshot(Snapshot {
|
||||
gui_size: (427.0, 240.0),
|
||||
held: None,
|
||||
..Snapshot::default()
|
||||
});
|
||||
assert_eq!(mods.hud_shapes().count(), 0);
|
||||
@@ -546,6 +545,47 @@ fn input_claims_keys_and_events() {
|
||||
assert_eq!(chat(&mut mods), ["holding minecraft:stick x3 in 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_panels_text_width_and_readings() {
|
||||
let mut mods = load("horizon_mods_test_ui_guest.hmod");
|
||||
// A font of 5-pixel glyphs, 3-pixel spaces.
|
||||
let mut widths = vec![5.0f32; 0x250];
|
||||
widths[' ' as usize] = 3.0;
|
||||
mods.set_snapshot(Snapshot {
|
||||
frame: (60, 41, 52),
|
||||
mappings: vec![("key.forward", "W".into(), true)],
|
||||
cps: (7, 2),
|
||||
font_widths: widths.into(),
|
||||
..Snapshot::default()
|
||||
});
|
||||
assert!(mods.command("corner"));
|
||||
let panels: Vec<_> = mods.corner_panels().cloned().collect();
|
||||
assert_eq!(panels.len(), 1);
|
||||
// "60 fps": five glyphs and a space, plus the box's 4.
|
||||
assert_eq!(
|
||||
(panels[0].width, panels[0].height),
|
||||
(5.0 * 5.0 + 3.0 + 4.0, 12.0)
|
||||
);
|
||||
assert_eq!(panels[0].shapes.len(), 2);
|
||||
assert!(matches!(
|
||||
panels[0].corner,
|
||||
horizon_mods::RenderCorner::TopRight
|
||||
));
|
||||
assert!(matches!(
|
||||
&mods.settings_widgets(0)[0],
|
||||
horizon_mods::UiWidget::Button(b) if b.id == 3 && b.label == "Corner: Top Right"
|
||||
));
|
||||
mods.drain();
|
||||
assert!(mods.command("readings"));
|
||||
assert_eq!(
|
||||
mods.drain(),
|
||||
[Output::Chat {
|
||||
name: "Test UI Guest".into(),
|
||||
text: "60 41 52; forward W true; cps 7 2; other true".into(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_only_mods_load_without_an_engine() {
|
||||
let manifest = r#"
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! of each widget, `/ui_settings` sets a settings page, `/ui_close` closes
|
||||
//! the screen; the `ui-events` calls answer in chat so the host sees them.
|
||||
//! `/render_hud`, `/render_clear` and `/render_shake` test `render`;
|
||||
//! `/input_claim`, `/input_poll` and `/input_held` test `input`.
|
||||
//! `/input_claim`, `/input_poll` and `/input_held` test `input`;
|
||||
//! `/corner` and `/readings` the calls the official extras mods use.
|
||||
use horizon_mod_sdk::{
|
||||
Mod, Registration, chat,
|
||||
input::{self, Event},
|
||||
@@ -92,6 +93,8 @@ impl Mod for Guest {
|
||||
"input_claim",
|
||||
"input_poll",
|
||||
"input_held",
|
||||
"corner",
|
||||
"readings",
|
||||
]
|
||||
.into_iter()
|
||||
.fold(Registration::new(), Registration::command);
|
||||
@@ -107,6 +110,49 @@ impl Mod for Guest {
|
||||
"ui_close" => ui::close_screen(),
|
||||
"render_hud" => render::set_hud(&shapes()),
|
||||
"render_clear" => render::set_hud(&[]),
|
||||
// An FPS-counter-like box: as wide as its text plus 4.
|
||||
"corner" => {
|
||||
let text = "60 fps";
|
||||
let w = render::text_width(text) + 4.0;
|
||||
render::set_corner(
|
||||
render::Corner::TopRight,
|
||||
w,
|
||||
12.0,
|
||||
&[
|
||||
Shape::Fill(FillShape {
|
||||
rect: Rect {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
w,
|
||||
h: 12.0,
|
||||
},
|
||||
color: 0x78000000,
|
||||
}),
|
||||
Shape::Text(TextShape {
|
||||
text: text.into(),
|
||||
at: Point { x: 2.0, y: 2.0 },
|
||||
color: 0xFFFFFF,
|
||||
centered: false,
|
||||
shadow: true,
|
||||
}),
|
||||
],
|
||||
);
|
||||
ui::set_settings(&[Widget::Button(ui::ButtonWidget {
|
||||
id: 3,
|
||||
label: "Corner: Top Right".into(),
|
||||
})]);
|
||||
}
|
||||
"readings" => {
|
||||
let f = render::frame_stats();
|
||||
let fwd = input::mapping("key.forward")
|
||||
.map_or("none".into(), |m| format!("{} {}", m.label, m.down));
|
||||
let (l, r) = input::clicks_per_second();
|
||||
let none = input::mapping("key.inventory").is_none();
|
||||
chat::show(&format!(
|
||||
"{} {} {}; forward {fwd}; cps {l} {r}; other {none}",
|
||||
f.fps, f.min, f.low
|
||||
));
|
||||
}
|
||||
"input_claim" => {
|
||||
input::claim_items(&["minecraft:stick".into()]);
|
||||
input::register_key("wheel", "Open the wheel", "key.keyboard.r")?;
|
||||
@@ -147,11 +193,17 @@ impl Mod for Guest {
|
||||
chat::show("closed");
|
||||
}
|
||||
fn ui_settings_opened(&mut self) {
|
||||
ui::set_settings(&[Widget::Text(TextWidget {
|
||||
id: 1,
|
||||
text: "fresh".into(),
|
||||
color: 0x33CC33,
|
||||
})]);
|
||||
ui::set_settings(&[
|
||||
Widget::Text(TextWidget {
|
||||
id: 1,
|
||||
text: "fresh".into(),
|
||||
color: 0x33CC33,
|
||||
}),
|
||||
Widget::Button(ui::ButtonWidget {
|
||||
id: 3,
|
||||
label: "Corner: Top Right".into(),
|
||||
}),
|
||||
]);
|
||||
chat::show("settings opened");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -814,7 +814,6 @@ pub fn carry(
|
||||
if kind == "structure" {
|
||||
let path = rel.trim_start_matches("worldgen/structure/");
|
||||
let structure = format!("{ns}:{}", path.trim_end_matches(".json"));
|
||||
changed |= crate::legacy_structure_mods::yung::disables(&structure, &mut v);
|
||||
changed |=
|
||||
crate::worldgen::add_piece_counts(&structure, &mut v, &piece_counts);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
//! conversion.
|
||||
pub(crate) mod ctov;
|
||||
pub(crate) mod lithostitched;
|
||||
pub(crate) mod yung;
|
||||
|
||||
#[cfg(test)]
|
||||
fn data() -> crate::processors::ProcessorData {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -20,3 +20,4 @@ pub mod pipeline;
|
||||
pub mod processors;
|
||||
pub mod report;
|
||||
pub mod worldgen;
|
||||
mod yung;
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! What is not here is taken out of its list later and counted
|
||||
//! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an
|
||||
//! `equipment` map, not 1.21.1's `HandItems` and `ArmorItems`).
|
||||
use crate::legacy_structure_mods::{ctov, lithostitched, yung};
|
||||
use crate::legacy_structure_mods::{ctov, lithostitched};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
@@ -177,12 +177,12 @@ fn carry_at(
|
||||
let mut out = Vec::with_capacity(expanded.len());
|
||||
for p in expanded {
|
||||
let kind = p["processor_type"].as_str().unwrap_or_default().to_owned();
|
||||
// Lithostitched's and YUNG's processors are carried apart from this
|
||||
// code (`legacy_structure_mods`).
|
||||
// Lithostitched's processors are carried apart from this code
|
||||
// (`legacy_structure_mods`).
|
||||
let replacement = lithostitched::processor(&kind, &p, data, carried).or_else(|| {
|
||||
match pillar_type(&kind).or_else(|| yung::pillar_type(&kind)) {
|
||||
match pillar_type(&kind) {
|
||||
Some(to) => Some(vec![pillar(&p, to, data, carried, depth)]),
|
||||
None => as_data(&kind, &p, data).or_else(|| yung::processor(&kind, &p)),
|
||||
None => as_data(&kind, &p, data),
|
||||
}
|
||||
});
|
||||
match replacement {
|
||||
@@ -860,8 +860,10 @@ mod tests {
|
||||
"horizon:bottom_pillar",
|
||||
"horizon:close_off_fluid_sources",
|
||||
"horizon:close_off_air_sources",
|
||||
"horizon:yung_pillar",
|
||||
"horizon:stair_pillar"
|
||||
// YUNG's processors stay Java (dropped later) until the
|
||||
// specification covers them.
|
||||
"betterfortresses:pillar_processor",
|
||||
"betterfortresses:stair_pillar_processor"
|
||||
]
|
||||
);
|
||||
// The named list is written in once; its own pillar loses its list.
|
||||
@@ -878,8 +880,7 @@ mod tests {
|
||||
p[4]["weighted_list_of_replacement_blocks"],
|
||||
json!([{"block": "minecraft:prismarine", "weight": 1}])
|
||||
);
|
||||
assert_eq!(p[6]["pillar"], "minecraft:red_nether_bricks");
|
||||
assert_eq!(carried["repurposed_structures:pillar_processor"], 2);
|
||||
assert_eq!(carried["betterfortresses:stair_pillar_processor"], 1);
|
||||
assert!(!carried.contains_key("betterfortresses:stair_pillar_processor"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,10 +14,11 @@
|
||||
//! as it is is listed, so the coverage report can say what generates and how
|
||||
//! closely.
|
||||
//!
|
||||
//! YUNG's, Lithostitched's and CTOV's worldgen files are converted by
|
||||
//! YUNG's API's files are carried as written ([`crate::yung`]).
|
||||
//! Lithostitched's and CTOV's worldgen files are converted by
|
||||
//! `legacy_structure_mods`, called from [`upgrade`], [`crate::carry`] and the
|
||||
//! processors.
|
||||
use crate::legacy_structure_mods::{lithostitched, yung};
|
||||
use crate::{legacy_structure_mods::lithostitched, yung};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
@@ -262,7 +263,7 @@ fn upgrade_types(
|
||||
let lost = &mut report.rules_lost;
|
||||
// YUNG's and Lithostitched's types are converted apart from this code.
|
||||
if let Some(changed) =
|
||||
yung::upgrade(kind, v, set_tags, lost).or_else(|| lithostitched::upgrade(kind, v, lost))
|
||||
yung::upgrade(kind, v, lost).or_else(|| lithostitched::upgrade(kind, v, lost))
|
||||
{
|
||||
report.mapped += usize::from(changed);
|
||||
return changed;
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! YUNG's API's worldgen, carried as the mods write it (clean room:
|
||||
//! `cleanroom/structures/spec-yungsapi.md`).
|
||||
//!
|
||||
//! The game reads `yungsapi:yung_jigsaw` structures and
|
||||
//! `yungsapi:yung_single_element` pool elements as they ship
|
||||
//! (`horizon_world::worldgen::structure::jigsaw::Draws::Yung`), so their files
|
||||
//! pass through unchanged. What the game does not run yet is counted by name
|
||||
//! in the carry report: the fields whose behaviour the specification leaves
|
||||
//! open. YUNG's other structure, placement and processor types are left to the
|
||||
//! general code, which lists them as unsupported or drops them.
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const JIGSAW: &str = "yungsapi:yung_jigsaw";
|
||||
const ELEMENT: &str = "yungsapi:yung_single_element";
|
||||
/// A terrain adaptation that adapts nothing.
|
||||
const NO_ADAPTATION: &str = "yungsapi:none";
|
||||
|
||||
fn count(lost: &mut BTreeMap<String, usize>, rule: String) {
|
||||
*lost.entry(rule).or_default() += 1;
|
||||
}
|
||||
|
||||
/// Whether a field changes generation in a way the game does not run yet:
|
||||
/// present, and not the value that changes nothing.
|
||||
fn active(v: &Value, field: &str) -> bool {
|
||||
match &v[field] {
|
||||
Value::Null | Value::Bool(false) => false,
|
||||
Value::Object(o) => o.get("type").and_then(Value::as_str) != Some(NO_ADAPTATION),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A `yung_jigsaw` structure: `Some(false)` (carried as it is), else `None`.
|
||||
pub(crate) fn upgrade(kind: &str, v: &Value, lost: &mut BTreeMap<String, usize>) -> Option<bool> {
|
||||
if kind != "structure" || v["type"] != JIGSAW {
|
||||
return None;
|
||||
}
|
||||
// spec-yungsapi §2: OPEN-Y1, OPEN-Y2 and §5.
|
||||
for field in [
|
||||
"adapt_noise",
|
||||
"max_y",
|
||||
"min_y",
|
||||
"enhanced_terrain_adaptation",
|
||||
] {
|
||||
if active(v, field) {
|
||||
count(lost, format!("{JIGSAW} {field}"));
|
||||
}
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
/// A `yung_single_element` pool element, carried as it is; whether it was one.
|
||||
pub(crate) fn upgrade_pool_element(element: &Value, lost: &mut BTreeMap<String, usize>) -> bool {
|
||||
if element["element_type"] != ELEMENT {
|
||||
return false;
|
||||
}
|
||||
// spec-yungsapi §4 and §5. `name`, `max_count`, `is_priority`,
|
||||
// `min_required_depth` and `ignore_bounds` are run (§3, §3.2).
|
||||
for field in ["condition", "enhanced_terrain_adaptation", "modifiers"] {
|
||||
if active(element, field) {
|
||||
count(lost, format!("{ELEMENT} {field}"));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn jigsaws_and_elements_are_carried_as_written() {
|
||||
let mut lost = BTreeMap::new();
|
||||
let dungeon =
|
||||
json!({"type": JIGSAW, "start_pool": "a:b", "size": 10, "adapt_noise": false});
|
||||
assert_eq!(upgrade("structure", &dungeon, &mut lost), Some(false));
|
||||
assert!(lost.is_empty());
|
||||
let stronghold = json!({"type": JIGSAW, "max_y": 0,
|
||||
"enhanced_terrain_adaptation": {"type": "yungsapi:carved"}});
|
||||
assert_eq!(upgrade("structure", &stronghold, &mut lost), Some(false));
|
||||
assert_eq!(lost[&format!("{JIGSAW} max_y")], 1);
|
||||
assert_eq!(lost[&format!("{JIGSAW} enhanced_terrain_adaptation")], 1);
|
||||
assert_eq!(
|
||||
upgrade("structure", &json!({"type": "minecraft:jigsaw"}), &mut lost),
|
||||
None
|
||||
);
|
||||
assert_eq!(upgrade("structure_set", &dungeon, &mut lost), None);
|
||||
|
||||
let mut lost = BTreeMap::new();
|
||||
let pile = json!({"element_type": ELEMENT, "name": "loot_pile_0", "max_count": 1,
|
||||
"enhanced_terrain_adaptation": {"type": NO_ADAPTATION}, "is_priority": true,
|
||||
"min_required_depth": 2, "ignore_bounds": true});
|
||||
assert!(upgrade_pool_element(&pile, &mut lost));
|
||||
assert!(lost.is_empty());
|
||||
let gated = json!({"element_type": ELEMENT, "condition": {"type": "yungsapi:not"}});
|
||||
assert!(upgrade_pool_element(&gated, &mut lost));
|
||||
assert_eq!(lost[&format!("{ELEMENT} condition")], 1);
|
||||
let single = json!({"element_type": "minecraft:single_pool_element"});
|
||||
assert!(!upgrade_pool_element(&single, &mut lost));
|
||||
}
|
||||
}
|
||||
@@ -185,13 +185,22 @@ pub(crate) fn import_manifest(lock: &Lock, minecraft: &Path) -> Result<Value, St
|
||||
}
|
||||
let checksum = digest(&source, "sha1")?;
|
||||
if !lock.manifest_accepted(&checksum) {
|
||||
return Err(format!(
|
||||
"{} is a {version} version file Horizon does not know yet (sha1 {checksum}); \
|
||||
Mojang may have republished it. Update Horizon, or report it if this is the latest release.",
|
||||
source.display()
|
||||
));
|
||||
}
|
||||
if !(destination.exists() && digest(&destination, "sha1")? == checksum) {
|
||||
// Another launcher's rewrite of Mojang's file (HMCL and PCL add their own fields to
|
||||
// the same jars, #1772), or one Mojang republished: Mojang's own copy saved as the
|
||||
// imported one is used instead.
|
||||
let pinned = lock.pin("manifest_sha1")?;
|
||||
if !(destination.exists() && lock.manifest_accepted(&digest(&destination, "sha1")?)) {
|
||||
return Err(format!(
|
||||
"{} is not a {version} version file Horizon knows (sha1 {checksum}): your \
|
||||
launcher may have rewritten it, or Mojang republished it. Prepare from the \
|
||||
Horizon launcher, which downloads Mojang's own, or save \
|
||||
https://piston-meta.mojang.com/v1/packages/{pinned}/{version}.json as {} \
|
||||
and prepare again.",
|
||||
source.display(),
|
||||
destination.display()
|
||||
));
|
||||
}
|
||||
} else if !(destination.exists() && digest(&destination, "sha1")? == checksum) {
|
||||
fs::create_dir_all(&lock.directory).map_err(|e| e.to_string())?;
|
||||
fs::copy(&source, &destination).map_err(|e| e.to_string())?;
|
||||
}
|
||||
@@ -1089,6 +1098,50 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A launcher that rewrites Mojang's version file in the official layout (HMCL, PCL: the same
|
||||
/// id and jars, its own fields, #1772) is refused with what to do, and Mojang's own copy saved
|
||||
/// as the imported one is then used.
|
||||
#[test]
|
||||
fn a_rewritten_version_file_falls_back_to_mojangs() {
|
||||
let root = std::env::temp_dir().join(format!("horizon-rewritten-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let mojang = r#"{"id":"9.9","javaVersion":{"majorVersion":25},"downloads":{"client":{"sha1":"c"},"server":{"sha1":"s"}}}"#;
|
||||
let rewritten = r#"{"id":"9.9","javaVersion":{"majorVersion":25},"downloads":{"client":{"sha1":"c"},"server":{"sha1":"s"}},"patches":[],"root":true}"#;
|
||||
let minecraft = root.join("minecraft");
|
||||
fs::create_dir_all(minecraft.join("versions/9.9")).unwrap();
|
||||
fs::write(minecraft.join("versions/9.9/9.9.json"), rewritten).unwrap();
|
||||
fs::write(root.join("mojang.json"), mojang).unwrap();
|
||||
let pinned = digest(&root.join("mojang.json"), "sha1").unwrap();
|
||||
fs::write(
|
||||
root.join("research-lock.json"),
|
||||
format!(
|
||||
r#"{{"minecraft":{{"version":"9.9","java_major":25,"manifest_sha1":"{pinned}","client_sha1":"c","server_sha1":"s"}}}}"#
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let lock = Lock::read(&root).unwrap();
|
||||
let destination = lock.directory.join("manifest.json");
|
||||
|
||||
let error = import_manifest(&lock, &minecraft).unwrap_err();
|
||||
assert!(error.contains("may have rewritten it"), "{error}");
|
||||
assert!(
|
||||
error.contains(&format!("packages/{pinned}/9.9.json")),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
error.contains(&destination.display().to_string()),
|
||||
"{error}"
|
||||
);
|
||||
assert!(!destination.exists());
|
||||
|
||||
fs::create_dir_all(&lock.directory).unwrap();
|
||||
fs::copy(root.join("mojang.json"), &destination).unwrap();
|
||||
let manifest = import_manifest(&lock, &minecraft).unwrap();
|
||||
assert!(manifest.get("patches").is_none());
|
||||
assert_eq!(digest(&destination, "sha1").unwrap(), pinned);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
/// scanfee's Prism Launcher 26.3 install on a Mac (#1487): Prism keeps natives under its own
|
||||
/// names and never downloads Netty's native transport, which the game runs without. Preparing
|
||||
/// still checks every other library, and the transport whenever the launcher has it.
|
||||
|
||||
@@ -45,6 +45,32 @@ packet!(
|
||||
packet!(KnownPack { namespace: String => Str, id: String => Str, version: String => Str });
|
||||
packet!(SelectKnownPacks { packs: Vec<KnownPack> => List<KnownPack> });
|
||||
packet!(CodeOfConduct { text: String => Str });
|
||||
packet!(
|
||||
/// ClientboundShowDialogPacket.CONTEXT_FREE_STREAM_CODEC: the dialog
|
||||
/// itself (`Dialog.DIRECT_CODEC` as NBT).
|
||||
ShowDialog { dialog: Tag => Nbt }
|
||||
);
|
||||
packet!(
|
||||
/// ServerboundCustomClickActionPacket: a `custom` click event's id and
|
||||
/// payload (a dialog's answer).
|
||||
CustomClickAction { id: String => Ident, payload: Option<Tag> => ClickPayload }
|
||||
);
|
||||
/// ServerboundCustomClickActionPacket.UNTRUSTED_TAG_CODEC: an optional tag
|
||||
/// (`End` when there is none) behind its length, 65536 bytes at most.
|
||||
pub struct ClickPayload;
|
||||
impl Codec<Option<Tag>> for ClickPayload {
|
||||
fn read(r: &mut Reader) -> Result<Option<Tag>> {
|
||||
let n = r.count(65536)?;
|
||||
let tag = Reader::new(r.bytes(n)?).nbt()?;
|
||||
Ok((tag != Tag::End).then_some(tag))
|
||||
}
|
||||
fn write(v: &Option<Tag>, w: &mut Writer) {
|
||||
let mut tag = Writer::new();
|
||||
tag.nbt(v.as_ref().unwrap_or(&Tag::End));
|
||||
w.varint(tag.data.len() as i32);
|
||||
w.bytes(&tag.data);
|
||||
}
|
||||
}
|
||||
|
||||
packet_enum!(Clientbound, crate::ids::configuration::clientbound {
|
||||
CookieRequest(CookieRequest) = COOKIE_REQUEST,
|
||||
@@ -63,6 +89,7 @@ packet_enum!(Clientbound, crate::ids::configuration::clientbound {
|
||||
UpdateTags(UpdateTags) = UPDATE_TAGS,
|
||||
SelectKnownPacks(SelectKnownPacks) = SELECT_KNOWN_PACKS,
|
||||
ClearDialog(Empty) = CLEAR_DIALOG,
|
||||
ShowDialog(ShowDialog) = SHOW_DIALOG,
|
||||
CodeOfConduct(CodeOfConduct) = CODE_OF_CONDUCT,
|
||||
});
|
||||
|
||||
@@ -142,6 +169,7 @@ packet_enum!(Serverbound, crate::ids::configuration::serverbound {
|
||||
ResourcePack(ResourcePackResponse) = RESOURCE_PACK,
|
||||
SelectKnownPacks(SelectKnownPacks) = SELECT_KNOWN_PACKS,
|
||||
AcceptCodeOfConduct(Empty) = ACCEPT_CODE_OF_CONDUCT,
|
||||
CustomClickAction(CustomClickAction) = CUSTOM_CLICK_ACTION,
|
||||
});
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -208,6 +236,10 @@ mod tests {
|
||||
Clientbound::CodeOfConduct(CodeOfConduct {
|
||||
text: "Be nice".into(),
|
||||
}),
|
||||
Clientbound::ShowDialog(ShowDialog {
|
||||
dialog: Tag::compound([("type", Tag::String("minecraft:notice".into()))]),
|
||||
}),
|
||||
Clientbound::ClearDialog(Empty),
|
||||
] {
|
||||
round_trip(p, Clientbound::encode, Clientbound::decode);
|
||||
}
|
||||
@@ -219,8 +251,28 @@ mod tests {
|
||||
Serverbound::ResourcePack(ResourcePackResponse { id: 5, action: 1 }),
|
||||
Serverbound::SelectKnownPacks(SelectKnownPacks { packs: vec![] }),
|
||||
Serverbound::AcceptCodeOfConduct(Empty),
|
||||
Serverbound::CustomClickAction(CustomClickAction {
|
||||
id: "authme:prejoin-register/submit".into(),
|
||||
payload: Some(Tag::compound([("password", Tag::String("hunter2".into()))])),
|
||||
}),
|
||||
Serverbound::CustomClickAction(CustomClickAction {
|
||||
id: "minecraft:x".into(),
|
||||
payload: None,
|
||||
}),
|
||||
] {
|
||||
round_trip(p, Serverbound::encode, Serverbound::decode);
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes vanilla writes: the length, then the tag (a lone `End` byte
|
||||
/// for none).
|
||||
#[test]
|
||||
fn click_payload_is_length_prefixed() {
|
||||
let mut w = Writer::new();
|
||||
ClickPayload::write(&None, &mut w);
|
||||
assert_eq!(w.data, [1, 0]);
|
||||
let mut w = Writer::new();
|
||||
ClickPayload::write(&Some(Tag::Byte(1)), &mut w);
|
||||
assert_eq!(w.data, [2, 1, 1]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,9 @@ use crate::{
|
||||
packets::{
|
||||
Empty,
|
||||
configuration::{
|
||||
ClientInformation, CookieRequest, CookieResponse, CustomPayload, Disconnect, KeepAlive,
|
||||
Ping, ResourcePackPop, ResourcePackPush, ResourcePackResponse, StoreCookie, Transfer,
|
||||
UpdateTags,
|
||||
ClientInformation, CookieRequest, CookieResponse, CustomClickAction, CustomPayload,
|
||||
Disconnect, KeepAlive, Ping, ResourcePackPop, ResourcePackPush, ResourcePackResponse,
|
||||
StoreCookie, Transfer, UpdateTags,
|
||||
},
|
||||
login::Property,
|
||||
},
|
||||
@@ -176,6 +176,9 @@ packet!(
|
||||
}
|
||||
);
|
||||
packet!(ContainerSetData { container: i32 => VarInt, id: i16 => Short, value: i16 => Short });
|
||||
// ClientboundCooldownPacket: the cooldown group (an identifier) and the ticks
|
||||
// its entry lasts (0 ends it).
|
||||
packet!(Cooldown { group: String => Ident, duration: i32 => VarInt });
|
||||
packet!(ContainerSetSlot { container: i32 => VarInt, state: i32 => VarInt, slot: i16 => Short, item: Option<Stack> => Slot });
|
||||
/// A holder reference: registry id + 1, or 0 for an inline value (unsupported).
|
||||
pub struct HolderId;
|
||||
@@ -190,6 +193,35 @@ impl Codec<i32> for HolderId {
|
||||
w.varint(v + 1)
|
||||
}
|
||||
}
|
||||
/// `Holder<Dialog>` as Dialog.STREAM_CODEC sends it: an entry of the
|
||||
/// `minecraft:dialog` registry the server sent in configuration, or the
|
||||
/// dialog itself.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum DialogHolder {
|
||||
Registry(i32),
|
||||
Direct(Tag),
|
||||
}
|
||||
impl Codec<DialogHolder> for DialogHolder {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
Ok(match r.varint()? {
|
||||
0 => Self::Direct(r.nbt()?),
|
||||
id => Self::Registry(id - 1),
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
match v {
|
||||
Self::Registry(id) => w.varint(id + 1),
|
||||
Self::Direct(tag) => {
|
||||
w.varint(0);
|
||||
w.nbt(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
packet!(
|
||||
/// ClientboundShowDialogPacket.
|
||||
ShowDialog { dialog: DialogHolder => DialogHolder }
|
||||
);
|
||||
packet!(
|
||||
/// ChatType.Bound.
|
||||
ChatTypeBound { chat_type: i32 => HolderId, name: Tag => Nbt, target: Option<Tag> => Opt<Nbt> }
|
||||
@@ -1761,6 +1793,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA,
|
||||
ContainerSetSlot(ContainerSetSlot) = CONTAINER_SET_SLOT,
|
||||
CookieRequest(CookieRequest) = COOKIE_REQUEST,
|
||||
Cooldown(Cooldown) = COOLDOWN,
|
||||
CustomPayload(CustomPayload) = CUSTOM_PAYLOAD,
|
||||
Disconnect(Disconnect) = DISCONNECT,
|
||||
DisguisedChat(DisguisedChat) = DISGUISED_CHAT,
|
||||
@@ -1854,6 +1887,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT,
|
||||
UpdateTags(UpdateTags) = UPDATE_TAGS,
|
||||
TrackedWaypoint(TrackedWaypoint) = WAYPOINT,
|
||||
ClearDialog(Empty) = CLEAR_DIALOG,
|
||||
ShowDialog(ShowDialog) = SHOW_DIALOG,
|
||||
});
|
||||
packet!(
|
||||
/// ClientboundClearTitlesPacket: whether to also reset the timings.
|
||||
@@ -2229,6 +2264,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
|
||||
ContainerClose(ContainerClose) = CONTAINER_CLOSE,
|
||||
CookieResponse(CookieResponse) = COOKIE_RESPONSE,
|
||||
CustomPayload(CustomPayload) = CUSTOM_PAYLOAD,
|
||||
CustomClickAction(CustomClickAction) = CUSTOM_CLICK_ACTION,
|
||||
EditBook(EditBook) = EDIT_BOOK,
|
||||
Interact(Interact) = INTERACT,
|
||||
KeepAlive(KeepAlive) = KEEP_ALIVE,
|
||||
@@ -2894,6 +2930,24 @@ mod tests {
|
||||
round_trip(beacon, Serverbound::encode, Serverbound::decode);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cooldown_packet_carries_its_group_and_ticks() {
|
||||
let packet = Clientbound::Cooldown(Cooldown {
|
||||
group: "minecraft:ender_pearl".into(),
|
||||
duration: 20,
|
||||
});
|
||||
round_trip(packet, Clientbound::encode, Clientbound::decode);
|
||||
// The group is an identifier, the ticks a VarInt; a duration of 0
|
||||
// removes the entry.
|
||||
let body = Clientbound::encode(&Clientbound::Cooldown(Cooldown {
|
||||
group: "minecraft:ender_pearl".into(),
|
||||
duration: 0,
|
||||
}));
|
||||
assert_eq!(body[0], crate::ids::play::clientbound::COOLDOWN as u8);
|
||||
assert_eq!(&body[1..3], [21, b'm']);
|
||||
assert_eq!(body[body.len() - 1], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_game_mode_uses_the_game_type_varint() {
|
||||
for mode in 0..=3 {
|
||||
@@ -3024,6 +3078,7 @@ mod tests {
|
||||
w.varint(101);
|
||||
assert!(BookPages::read(&mut Reader::new(&w.data)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boss_event_round_trips() {
|
||||
let add = Clientbound::BossEvent(BossEvent {
|
||||
@@ -3061,4 +3116,28 @@ mod tests {
|
||||
Clientbound::decode,
|
||||
);
|
||||
}
|
||||
|
||||
/// A registry entry is its id + 1, the dialog itself a 0 then its NBT.
|
||||
#[test]
|
||||
fn dialogs_round_trip() {
|
||||
let notice = Tag::compound([("type", Tag::String("minecraft:notice".into()))]);
|
||||
for dialog in [DialogHolder::Registry(3), DialogHolder::Direct(notice)] {
|
||||
crate::packets::round_trip(
|
||||
Clientbound::ShowDialog(ShowDialog { dialog }),
|
||||
Clientbound::encode,
|
||||
Clientbound::decode,
|
||||
);
|
||||
}
|
||||
let mut w = Writer::new();
|
||||
DialogHolder::write(&DialogHolder::Registry(3), &mut w);
|
||||
assert_eq!(w.data, [4]);
|
||||
crate::packets::round_trip(
|
||||
Serverbound::CustomClickAction(CustomClickAction {
|
||||
id: "minecraft:custom".into(),
|
||||
payload: None,
|
||||
}),
|
||||
Serverbound::encode,
|
||||
Serverbound::decode,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! - [`Properties`]: `shaders.properties` and the id files, with their conditional directives (3.1, 1.5).
|
||||
//! - [`Lang`]: the pack's translated names (8.4).
|
||||
//! - [`preprocess`]: a stage file through `#include` and the GLSL preprocessor, lines mapped back (1.4, 1.5).
|
||||
//! - [`translate_composite`], [`translate_gbuffers`]: a program into naga modules and its interface (1.6, 2.2).
|
||||
//! - [`translate_composite`], [`translate_gbuffers`], [`translate_shadow`]: a program into naga modules and its interface (1.6, 2.2).
|
||||
//! - [`Config`] and [`draw_buffers`]: the buffer settings and output lists stage files carry (1.7, 6.1).
|
||||
//! - [`load_post`]: a dimension's `prepare`, `deferred`, `composite` and `final` programs, in order (2.1).
|
||||
//! - [`Macros`] and [`eval_condition`]: the macros packs test, and the `#if` arithmetic (1.5).
|
||||
@@ -45,5 +45,5 @@ pub use preprocess::{Diagnostic, Origin, Preprocessed, preprocess};
|
||||
pub use properties::{Entry, Note, Properties};
|
||||
pub use translate::{
|
||||
AlphaTest, DRAW_UNIFORMS, Error, GbuffersInputs, Interface, Program, Sampler, Target, Uniform,
|
||||
translate_composite, translate_gbuffers,
|
||||
translate_composite, translate_gbuffers, translate_shadow,
|
||||
};
|
||||
|
||||
@@ -15,7 +15,9 @@ use std::collections::BTreeSet;
|
||||
use crate::config::{self, Config};
|
||||
use crate::custom::Custom;
|
||||
use crate::{GbuffersInputs, Macros, Pack, Preprocessed, Program, Properties, Target};
|
||||
use crate::{eval_condition, preprocess, translate_composite, translate_gbuffers};
|
||||
use crate::{
|
||||
eval_condition, preprocess, translate_composite, translate_gbuffers, translate_shadow,
|
||||
};
|
||||
|
||||
/// Which group of 2.1 a program belongs to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -28,8 +30,32 @@ pub enum Group {
|
||||
Gbuffers,
|
||||
/// A gbuffers program drawing translucent geometry, after deferred (2.1).
|
||||
Translucent,
|
||||
/// A shadow program: the game's geometry from the shadow light, into the shadow buffers.
|
||||
Shadow,
|
||||
/// `shadowcomp`..`shadowcomp99`: composite-style programs over the shadow buffers.
|
||||
ShadowComp,
|
||||
}
|
||||
|
||||
impl Group {
|
||||
/// Whether the group writes the shadow buffers, where buffer n is shadowcolor n.
|
||||
pub fn shadow(self) -> bool {
|
||||
matches!(self, Group::Shadow | Group::ShadowComp)
|
||||
}
|
||||
}
|
||||
|
||||
/// The samplers whose use turns the shadow pass on (2.5, 6.3).
|
||||
const SHADOW_SAMPLERS: [&str; 9] = [
|
||||
"shadow",
|
||||
"watershadow",
|
||||
"shadowtex0",
|
||||
"shadowtex1",
|
||||
"shadowtex0HW",
|
||||
"shadowtex1HW",
|
||||
"shadowcolor",
|
||||
"shadowcolor0",
|
||||
"shadowcolor1",
|
||||
];
|
||||
|
||||
/// A blend factor of `blend.<program>` (3.2), as GL names it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Factor {
|
||||
@@ -216,6 +242,23 @@ pub struct Post {
|
||||
pub weather: Option<PostProgram>,
|
||||
/// What draws the first-person hand and held items.
|
||||
pub hand: Option<PostProgram>,
|
||||
/// Some program reads a shadow buffer, or `shadow.enabled=true`: the shadow pass runs (2.5).
|
||||
pub shadow_pass: bool,
|
||||
/// When it runs: what draws solid and cutout terrain from the light (`shadow`), and
|
||||
/// translucent terrain (`shadow_water` or `shadow`), into the shadow buffers (2.4).
|
||||
pub shadow: Option<PostProgram>,
|
||||
pub shadow_water: Option<PostProgram>,
|
||||
/// What draws entities (`shadow_entities` or `shadow`) and block entities (`shadow_block` or
|
||||
/// `shadow`) from the light, unless `shadowEntities`/`shadowBlockEntities` is false.
|
||||
pub shadow_entities: Option<PostProgram>,
|
||||
pub shadow_block: Option<PostProgram>,
|
||||
/// `shadowEntities=false` with `shadowPlayer=true`: of the entities, only the player casts.
|
||||
pub shadow_only_player: bool,
|
||||
/// `shadowBlockEntities=false` with `shadowLightBlockEntities=true`: only block entities
|
||||
/// whose block emits light cast.
|
||||
pub shadow_only_lit_blocks: bool,
|
||||
/// `shadowcomp`..`shadowcomp99`, after the shadow pass (2.1).
|
||||
pub shadow_comp: Vec<PostProgram>,
|
||||
/// Translucent entities draw after deferred (`separateEntityDraws`, 3.2).
|
||||
pub translucent_late: bool,
|
||||
/// Particles draw after deferred (`particles.ordering`, `particles.before.deferred`, 3.2).
|
||||
@@ -280,6 +323,14 @@ pub fn load_post(
|
||||
clouds: None,
|
||||
weather: None,
|
||||
hand: None,
|
||||
shadow_pass: false,
|
||||
shadow: None,
|
||||
shadow_water: None,
|
||||
shadow_entities: None,
|
||||
shadow_block: None,
|
||||
shadow_only_player: false,
|
||||
shadow_only_lit_blocks: false,
|
||||
shadow_comp: Vec::new(),
|
||||
translucent_late: false,
|
||||
particles_late: false,
|
||||
custom: Custom::parse(properties),
|
||||
@@ -434,10 +485,106 @@ pub fn load_post(
|
||||
Some(_) => true,
|
||||
None => !flag("particles.before.deferred").unwrap_or(false),
|
||||
};
|
||||
load_shadow(
|
||||
&mut loader,
|
||||
inputs.terrain.as_ref(),
|
||||
inputs.entities.as_ref(),
|
||||
);
|
||||
post.config = std::mem::take(&mut post.config).finish();
|
||||
post
|
||||
}
|
||||
|
||||
/// Whether the shadow pass runs (2.5) and, when it does, its programs: `shadow_solid` and
|
||||
/// `shadow_cutout` are not used (2.4, Legacy); the game's solid and cutout terrain is one draw.
|
||||
/// `shadow_entities` and `shadow_block` read the entities' vertices (`entities`).
|
||||
fn load_shadow(
|
||||
loader: &mut Loader<'_>,
|
||||
terrain: Option<&GbuffersInputs>,
|
||||
entities: Option<&GbuffersInputs>,
|
||||
) {
|
||||
let post = &*loader.post;
|
||||
let gbuffers = [
|
||||
&post.terrain,
|
||||
&post.water,
|
||||
&post.sky,
|
||||
&post.sky_textured,
|
||||
&post.entities,
|
||||
&post.block,
|
||||
&post.entities_translucent,
|
||||
&post.particles,
|
||||
&post.clouds,
|
||||
&post.weather,
|
||||
&post.hand,
|
||||
];
|
||||
let reads = (post.programs.iter())
|
||||
.chain(gbuffers.into_iter().flatten())
|
||||
.flat_map(|p| &p.program.interface.samplers)
|
||||
.any(|s| SHADOW_SAMPLERS.contains(&s.name.as_str()));
|
||||
let forced = match loader.properties.get("shadow.enabled").map(str::trim) {
|
||||
Some("true") => Some(true),
|
||||
Some("false") => Some(false),
|
||||
_ => None,
|
||||
};
|
||||
let on = forced.unwrap_or(reads);
|
||||
loader.post.shadow_pass = on;
|
||||
if !on {
|
||||
return;
|
||||
}
|
||||
let names =
|
||||
std::iter::once("shadowcomp".to_owned()).chain((1..=99).map(|n| format!("shadowcomp{n}")));
|
||||
for name in names {
|
||||
let program = loader.load(name, Group::ShadowComp, |v, f| {
|
||||
translate_composite(v, f, Target::Buffers)
|
||||
});
|
||||
loader.post.shadow_comp.extend(program);
|
||||
}
|
||||
let properties = loader.properties;
|
||||
let mut load = |names: &[&str], inputs: Option<&GbuffersInputs>| {
|
||||
let inputs = inputs?;
|
||||
names.iter().find_map(|name| {
|
||||
let p = loader.load(name.to_string(), Group::Shadow, |v, f| {
|
||||
translate_shadow(v, f, inputs)
|
||||
});
|
||||
p.map(|mut p| {
|
||||
p.blend = blend(properties, &p.name).flatten();
|
||||
p
|
||||
})
|
||||
})
|
||||
};
|
||||
// `shadowTerrain`, `shadowTranslucent`, `shadowEntities` and `shadowBlockEntities` (3.2)
|
||||
// leave their part out of the shadow pass; all are on by default (OQ-19). `shadowPlayer`
|
||||
// and `shadowLightBlockEntities` (E, off by default) keep the player, and block entities
|
||||
// that emit light, when the first two are off.
|
||||
let keep = |key: &str| properties.get(key).is_none_or(|v| v.trim() != "false");
|
||||
let set = |key: &str| properties.get(key).is_some_and(|v| v.trim() == "true");
|
||||
let only_player = !keep("shadowEntities") && set("shadowPlayer");
|
||||
let only_lit = !keep("shadowBlockEntities") && set("shadowLightBlockEntities");
|
||||
let shadow = keep("shadowTerrain")
|
||||
.then(|| load(&["shadow"], terrain))
|
||||
.flatten();
|
||||
let water = keep("shadowTranslucent")
|
||||
.then(|| load(&["shadow_water", "shadow"], terrain))
|
||||
.flatten();
|
||||
let shadow_entities = (keep("shadowEntities") || only_player)
|
||||
.then(|| load(&["shadow_entities", "shadow"], entities))
|
||||
.flatten();
|
||||
let shadow_block = (keep("shadowBlockEntities") || only_lit)
|
||||
.then(|| load(&["shadow_block", "shadow"], entities))
|
||||
.flatten();
|
||||
if shadow.is_none() && terrain.is_some() {
|
||||
loader
|
||||
.post
|
||||
.notes
|
||||
.push("shadow: no program; the shadow map stays clear".to_owned());
|
||||
}
|
||||
loader.post.shadow = shadow;
|
||||
loader.post.shadow_water = water;
|
||||
loader.post.shadow_entities = shadow_entities;
|
||||
loader.post.shadow_block = shadow_block;
|
||||
loader.post.shadow_only_player = only_player;
|
||||
loader.post.shadow_only_lit_blocks = only_lit;
|
||||
}
|
||||
|
||||
struct Loader<'a> {
|
||||
pack: &'a Pack,
|
||||
folder: &'a str,
|
||||
@@ -505,9 +652,17 @@ impl Loader<'_> {
|
||||
};
|
||||
self.post.config.read(&vertex);
|
||||
self.post.config.read(&fragment);
|
||||
let buffers = config::draw_buffers(&fragment).unwrap_or_else(|| (0..8).collect());
|
||||
let mut buffers = config::draw_buffers(&fragment).unwrap_or_else(|| (0..8).collect());
|
||||
if group.shadow() {
|
||||
// Output n writes shadowcolor n (6.3); there are two.
|
||||
let kept = buffers
|
||||
.iter()
|
||||
.position(|&b| b >= 2)
|
||||
.unwrap_or(buffers.len());
|
||||
buffers.truncate(kept);
|
||||
}
|
||||
let mipmaps = match group {
|
||||
Group::Gbuffers | Group::Translucent => 0,
|
||||
Group::Gbuffers | Group::Translucent | Group::Shadow | Group::ShadowComp => 0,
|
||||
_ => {
|
||||
let mut own = Config::default();
|
||||
own.read(&fragment);
|
||||
@@ -696,6 +851,90 @@ mod tests {
|
||||
assert!(post.programs.iter().any(|p| p.name == "composite3"));
|
||||
}
|
||||
|
||||
/// The shadow pass runs when a program reads a shadow buffer or `shadow.enabled` says so;
|
||||
/// then `shadow`, `shadow_water` and the `shadowcomp` series load, writing shadowcolor0/1.
|
||||
#[test]
|
||||
fn shadow_programs_load_when_a_shadow_buffer_is_read() {
|
||||
let reads = "#version 120\nuniform sampler2D shadowtex0;\nvarying vec2 uv;\n\
|
||||
void main() { gl_FragColor = texture2D(shadowtex0, uv); }\n";
|
||||
let shadow = "#version 120\nvarying vec2 uv;\nvoid main() {\n/* RENDERTARGETS: 1,0,4 */\n\
|
||||
gl_FragData[0] = vec4(1.0); gl_FragData[1] = vec4(0.5); gl_FragData[2] = vec4(0.0);\n}\n";
|
||||
let files = [
|
||||
("shaders/composite.vsh", VSH),
|
||||
("shaders/composite.fsh", reads),
|
||||
("shaders/shadow.vsh", VSH),
|
||||
("shaders/shadow.fsh", shadow),
|
||||
("shaders/shadowcomp1.vsh", VSH),
|
||||
("shaders/shadowcomp1.fsh", FSH),
|
||||
("shaders/shadow_block.vsh", VSH),
|
||||
("shaders/shadow_block.fsh", FSH),
|
||||
];
|
||||
let pack = Pack::from_zip_bytes("t", zip(&files)).unwrap();
|
||||
let game = crate::GbuffersInputs {
|
||||
declarations: "layout(location = 0) in vec3 hz_v_pos;".into(),
|
||||
body: " hz_Vertex = vec4(hz_v_pos, 1.0);\n".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let inputs = GameInputs {
|
||||
terrain: Some(game.clone()),
|
||||
entities: Some(game),
|
||||
..Default::default()
|
||||
};
|
||||
let load = |properties: &str| {
|
||||
let properties = Properties::parse(properties, &Macros::default());
|
||||
load_post(&pack, "", &properties, &Macros::standard(), &inputs)
|
||||
};
|
||||
let post = load("");
|
||||
assert!(post.shadow_pass);
|
||||
let shadow = post.shadow.as_ref().expect("shadow");
|
||||
assert_eq!(
|
||||
(shadow.group, &shadow.buffers[..]),
|
||||
(Group::Shadow, &[1, 0][..])
|
||||
);
|
||||
// shadow_water falls back to shadow.
|
||||
assert_eq!(
|
||||
post.shadow_water.as_ref().map(|p| p.name.as_str()),
|
||||
Some("shadow")
|
||||
);
|
||||
// Entities fall back to shadow; block entities have their own program.
|
||||
let name = |p: &Option<PostProgram>| p.as_ref().map(|p| p.name.clone());
|
||||
assert_eq!(
|
||||
(name(&post.shadow_entities), name(&post.shadow_block)),
|
||||
(Some("shadow".into()), Some("shadow_block".into()))
|
||||
);
|
||||
let off = load("shadowEntities=false\nshadowBlockEntities = false");
|
||||
assert!(
|
||||
off.shadow.is_some() && off.shadow_entities.is_none() && off.shadow_block.is_none()
|
||||
);
|
||||
// shadowPlayer and shadowLightBlockEntities keep a part of each.
|
||||
let some = load(
|
||||
"shadowEntities=false\nshadowPlayer=true\nshadowBlockEntities=false\nshadowLightBlockEntities=true",
|
||||
);
|
||||
assert!(some.shadow_entities.is_some() && some.shadow_only_player);
|
||||
assert!(some.shadow_block.is_some() && some.shadow_only_lit_blocks);
|
||||
assert!(!post.shadow_only_player && !post.shadow_only_lit_blocks);
|
||||
let comp: Vec<_> = post
|
||||
.shadow_comp
|
||||
.iter()
|
||||
.map(|p| (p.name.as_str(), p.group))
|
||||
.collect();
|
||||
assert_eq!(comp, [("shadowcomp1", Group::ShadowComp)]);
|
||||
// DRAWBUFFERS:3 names no shadowcolor buffer.
|
||||
assert!(post.shadow_comp[0].buffers.is_empty());
|
||||
let post = load("shadow.enabled = false");
|
||||
assert!(!post.shadow_pass && post.shadow.is_none() && post.shadow_comp.is_empty());
|
||||
// Nothing reads a shadow buffer.
|
||||
let pack = Pack::from_zip_bytes("t", zip(&files[2..])).unwrap();
|
||||
let none = |properties: &str| {
|
||||
let properties = Properties::parse(properties, &Macros::default());
|
||||
load_post(&pack, "", &properties, &Macros::standard(), &inputs)
|
||||
};
|
||||
assert!(!none("").shadow_pass);
|
||||
assert!(none("shadow.enabled=true").shadow.is_some());
|
||||
let post = none("shadow.enabled=true\nshadowTranslucent=false");
|
||||
assert!(post.shadow.is_some() && post.shadow_water.is_none());
|
||||
}
|
||||
|
||||
/// Water falls back to the terrain chain and blends by default, as the sky does; entities
|
||||
/// and block entities fall back along theirs; `blend.*` overrides.
|
||||
#[test]
|
||||
|
||||
@@ -154,7 +154,7 @@ pub fn translate_composite(
|
||||
fragment: &Preprocessed,
|
||||
target: Target,
|
||||
) -> Result<Program, Vec<Error>> {
|
||||
translate(vertex, fragment, target, None)
|
||||
translate(vertex, fragment, target, None, false)
|
||||
}
|
||||
|
||||
/// Translates a gbuffers-style program (`gbuffers_terrain`...) drawing the game's geometry
|
||||
@@ -165,7 +165,18 @@ pub fn translate_gbuffers(
|
||||
target: Target,
|
||||
inputs: &GbuffersInputs,
|
||||
) -> Result<Program, Vec<Error>> {
|
||||
translate(vertex, fragment, target, Some(inputs))
|
||||
translate(vertex, fragment, target, Some(inputs), false)
|
||||
}
|
||||
|
||||
/// Translates a shadow program (`shadow`, `shadow_water`...) drawing the game's geometry
|
||||
/// described by `inputs` from the shadow light: its model-view and projection matrices are the
|
||||
/// shadow camera's (5.2).
|
||||
pub fn translate_shadow(
|
||||
vertex: &Preprocessed,
|
||||
fragment: &Preprocessed,
|
||||
inputs: &GbuffersInputs,
|
||||
) -> Result<Program, Vec<Error>> {
|
||||
translate(vertex, fragment, Target::Buffers, Some(inputs), true)
|
||||
}
|
||||
|
||||
/// The matrices of the compatibility profile in a gbuffers-style program, from the frame's.
|
||||
@@ -183,7 +194,13 @@ fn translate(
|
||||
fragment: &Preprocessed,
|
||||
target: Target,
|
||||
gbuffers: Option<&GbuffersInputs>,
|
||||
shadow: bool,
|
||||
) -> Result<Program, Vec<Error>> {
|
||||
let matrices = if shadow {
|
||||
GBUFFERS_MATRICES.replace("gbuffer", "shadow")
|
||||
} else {
|
||||
GBUFFERS_MATRICES.to_owned()
|
||||
};
|
||||
let mut v = Stage::scan(vertex, ShaderStage::Vertex);
|
||||
let mut f = Stage::scan(fragment, ShaderStage::Fragment);
|
||||
v.gbuffers = gbuffers.is_some();
|
||||
@@ -200,6 +217,9 @@ fn translate(
|
||||
"gbufferProjectionInverse",
|
||||
] {
|
||||
uniforms.insert(name.to_owned(), "mat4".to_owned());
|
||||
if shadow {
|
||||
uniforms.insert(name.replace("gbuffer", "shadow"), "mat4".to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut samplers: BTreeMap<String, String> = BTreeMap::new();
|
||||
@@ -327,7 +347,7 @@ fn translate(
|
||||
hz_MultiTexCoord0 = hz_Vertex;\n hz_Color = vec4(1.0);\n hz_Normal = vec3(0.0, 0.0, 1.0);\n",
|
||||
),
|
||||
Some(inputs) => {
|
||||
vertex_main.push_str(GBUFFERS_MATRICES);
|
||||
vertex_main.push_str(&matrices);
|
||||
vertex_main.push_str(&inputs.body);
|
||||
}
|
||||
}
|
||||
@@ -361,7 +381,7 @@ fn translate(
|
||||
.unwrap();
|
||||
let mut fragment_main = String::from("\nvoid main() {\n");
|
||||
if gbuffers.is_some() {
|
||||
fragment_main.push_str(GBUFFERS_MATRICES);
|
||||
fragment_main.push_str(&matrices);
|
||||
}
|
||||
fragment_main.push_str(fog);
|
||||
if f.frag_coord {
|
||||
@@ -795,7 +815,7 @@ mod tests {
|
||||
let files: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), *t)).collect();
|
||||
let pack = Pack::from_zip_bytes("P.zip", zip(&files)).unwrap();
|
||||
let m = Macros::standard();
|
||||
let inputs = GbuffersInputs {
|
||||
let game = GbuffersInputs {
|
||||
declarations: "layout(location = 0) in vec3 game_pos;\nlayout(location = 1) in uvec2 game_uv;".into(),
|
||||
body: " hz_Vertex = vec4(game_pos, 1.0);\n hz_MultiTexCoord0 = vec4(vec2(game_uv) / 32768.0, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord1 = vec4(240.0, 240.0, 0.0, 1.0);\n hz_Color = vec4(1.0);\n hz_Normal = vec3(0.0, 1.0, 0.0);\n"
|
||||
@@ -807,7 +827,7 @@ mod tests {
|
||||
&preprocess(&pack, "gbuffers_terrain.vsh", &m),
|
||||
&preprocess(&pack, "gbuffers_terrain.fsh", &m),
|
||||
Target::Buffers,
|
||||
&inputs,
|
||||
&game,
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{e:?}"));
|
||||
let names: Vec<&str> = p
|
||||
@@ -842,6 +862,19 @@ mod tests {
|
||||
inputs.contains(&"game_pos") && inputs.contains(&"game_uv"),
|
||||
"{inputs:?}"
|
||||
);
|
||||
// From the light, the compatibility matrices are the shadow camera's.
|
||||
let shadow = translate_shadow(
|
||||
&preprocess(&pack, "gbuffers_terrain.vsh", &m),
|
||||
&preprocess(&pack, "gbuffers_terrain.fsh", &m),
|
||||
&game,
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{e:?}"));
|
||||
let names: Vec<&str> = (shadow.interface.uniforms.iter())
|
||||
.map(|u| u.name.as_str())
|
||||
.collect();
|
||||
for name in ["shadowModelView", "shadowProjection", "gbufferModelView"] {
|
||||
assert!(names.contains(&name), "{name} missing from {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -180,8 +180,14 @@ fn real_packs_read() {
|
||||
};
|
||||
let post = load_post(&pack, &folder, &shaders, &Macros::standard(), &inputs);
|
||||
println!(
|
||||
" dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, water {:?}, sky {:?} {:?}, entities {:?} {:?}, {} notes, {:.0} ms",
|
||||
" dimension {id} (folder `{folder}`): {} post programs, shadow pass {} ({:?}, {:?}, {:?}, {:?}, {} shadowcomp), terrain {:?}, water {:?}, sky {:?} {:?}, entities {:?} {:?}, {} notes, {:.0} ms",
|
||||
post.programs.len(),
|
||||
post.shadow_pass,
|
||||
post.shadow.as_ref().map(|t| &t.name),
|
||||
post.shadow_water.as_ref().map(|t| &t.name),
|
||||
post.shadow_entities.as_ref().map(|t| &t.name),
|
||||
post.shadow_block.as_ref().map(|t| &t.name),
|
||||
post.shadow_comp.len(),
|
||||
post.terrain.as_ref().map(|t| &t.name),
|
||||
post.water.as_ref().map(|t| &t.name),
|
||||
post.sky.as_ref().map(|t| &t.name),
|
||||
|
||||
@@ -158,6 +158,13 @@ impl<'r> BlockCollisionRegistry<'r> {
|
||||
empty_shape: flags & 4 != 0,
|
||||
})
|
||||
}
|
||||
/// Whether a scan keeps `state` in the cells around its box: a large
|
||||
/// collision shape or a moving piston. States outside the registry count.
|
||||
pub fn reaches_out(&self, state: BlockStateId) -> bool {
|
||||
self.scan_flags
|
||||
.get(state.0 as usize)
|
||||
.is_none_or(|flags| flags & 3 != 0)
|
||||
}
|
||||
pub fn collision_shape<W: DynamicCollisionWorld>(
|
||||
&self,
|
||||
world: &mut W,
|
||||
|
||||
@@ -41,6 +41,13 @@ pub trait BlockCollisionWorld {
|
||||
position: BlockPos,
|
||||
context: &CollisionContext<'_>,
|
||||
) -> Result<VoxelShape, Self::Error>;
|
||||
/// Whether a block of the chunk's section `section_y` (block y >> 4) may
|
||||
/// have a large collision shape or be a moving piston: the only blocks
|
||||
/// the scan keeps outside the box's own cells. False lets the scan pass
|
||||
/// that section's outer cells without reading them; true reads them all.
|
||||
fn may_reach_out(&mut self, _chunk: Self::Chunk, _section_y: i32) -> Result<bool, Self::Error> {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -88,6 +95,8 @@ pub struct BlockCollisionScan<'w, 'c, W: BlockCollisionWorld> {
|
||||
count: usize,
|
||||
budget: usize,
|
||||
chunk: Option<(ChunkPos, W::Chunk)>,
|
||||
/// `may_reach_out` of the last section an outer cell was in.
|
||||
reach: Option<(ChunkPos, i32, bool)>,
|
||||
failed: bool,
|
||||
}
|
||||
impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> {
|
||||
@@ -137,16 +146,36 @@ impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> {
|
||||
count,
|
||||
budget: candidate_budget,
|
||||
chunk: None,
|
||||
reach: None,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Move the cursor `n` cells further along its row; `n` must not pass
|
||||
/// the row's end.
|
||||
fn skip(&mut self, n: usize) {
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let [width, height, _] = self.sizes;
|
||||
self.index += n;
|
||||
self.cursor[0] += n;
|
||||
if self.cursor[0] == width {
|
||||
self.cursor[0] = 0;
|
||||
self.cursor[1] += 1;
|
||||
if self.cursor[1] == height {
|
||||
self.cursor[1] = 0;
|
||||
self.cursor[2] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find_next(&mut self) -> Result<Option<BlockCollisionHit>, CollisionScanError<W::Error>> {
|
||||
while self.index < self.count {
|
||||
if self.index >= self.budget {
|
||||
return Err(CollisionScanError::VisitBudget);
|
||||
}
|
||||
let [width, height, _] = self.sizes;
|
||||
let [width, height, depth] = self.sizes;
|
||||
let relative = self.cursor;
|
||||
self.index += 1;
|
||||
self.cursor[0] += 1;
|
||||
@@ -184,6 +213,41 @@ impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> {
|
||||
let Some(chunk) = chunk else {
|
||||
continue;
|
||||
};
|
||||
// An outer cell only counts for a block reaching out of its own
|
||||
// cell: most sections hold none, so their outer cells go unread
|
||||
// (the result is the same, with a fifth of the block reads for a
|
||||
// mob's box).
|
||||
if kind != 0 {
|
||||
let section_y = p.y >> 4;
|
||||
let reaches = match self.reach {
|
||||
Some((at, y, reaches)) if at == chunk_position && y == section_y => reaches,
|
||||
_ => {
|
||||
let reaches = self
|
||||
.world
|
||||
.may_reach_out(chunk, section_y)
|
||||
.map_err(CollisionScanError::World)?;
|
||||
self.reach = Some((chunk_position, section_y, reaches));
|
||||
reaches
|
||||
}
|
||||
};
|
||||
if !reaches {
|
||||
// On a row along the box's bottom, top or sides every
|
||||
// cell is outer: the rest of it in this chunk is passed
|
||||
// at once (never beyond the budget, which still ends the
|
||||
// scan where it would have).
|
||||
if relative[1] == 0
|
||||
|| relative[1] == height - 1
|
||||
|| relative[2] == 0
|
||||
|| relative[2] == depth - 1
|
||||
{
|
||||
let rest = (width - 1 - relative[0])
|
||||
.min(15 - (p.x & 15) as usize)
|
||||
.min(self.budget.saturating_sub(self.index));
|
||||
self.skip(rest);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let block = self
|
||||
.world
|
||||
.collision_block(chunk, p)
|
||||
|
||||
@@ -573,6 +573,29 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
self.game_event_state(pos, "minecraft:block_destroy", state);
|
||||
}
|
||||
}
|
||||
/// `BigDripleafBlock.entityInside` on a server level: an entity standing on
|
||||
/// a flat leaf (`canEntityTilt`: on the ground, its feet above the leaf's
|
||||
/// lowest top, 11/16, less 4/16: 0.6875) tilts it UNSTABLE unless the leaf
|
||||
/// is powered; `setTiltAndScheduleTick` with no sound (UNSTABLE causes no
|
||||
/// vibration) and the next state in 10 ticks.
|
||||
pub(crate) fn big_dripleaf_entity_inside(
|
||||
&mut self,
|
||||
pos: BlockPos,
|
||||
on_ground: bool,
|
||||
feet_y: f64,
|
||||
) {
|
||||
let b = self.b;
|
||||
let state = self.state(pos);
|
||||
if !b.data(state).is(Class::BigDripleaf)
|
||||
|| b.table.text(state, b.props.tilt) != "none"
|
||||
|| !(on_ground && feet_y > f64::from(pos.y) + f64::from(0.6875_f32))
|
||||
|| self.has_neighbor_signal(pos)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.set_block(pos, b.table.set_text(state, b.props.tilt, "unstable"), 2);
|
||||
self.schedule_tick(pos, b.block(state), 10);
|
||||
}
|
||||
/// `BigDripleafBlock.resetTilt`.
|
||||
pub(crate) fn big_dripleaf_reset_tilt(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
let b = self.b;
|
||||
|
||||
@@ -749,6 +749,19 @@ impl Behaviours {
|
||||
) {
|
||||
self.sim(level, ticks).entity_inside(pos);
|
||||
}
|
||||
/// `BigDripleafBlock.entityInside` for an entity whose box is inside
|
||||
/// `pos`: whether it is on the ground and its feet's y (`canEntityTilt`).
|
||||
pub fn entity_on_big_dripleaf<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
pos: BlockPos,
|
||||
on_ground: bool,
|
||||
feet_y: f64,
|
||||
) {
|
||||
self.sim(level, ticks)
|
||||
.big_dripleaf_entity_inside(pos, on_ground, feet_y);
|
||||
}
|
||||
/// Redstone signal queries (`SignalGetter`).
|
||||
pub fn has_neighbor_signal<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
|
||||
@@ -1283,3 +1283,44 @@ fn player_breaks_fire_with_extinguish_not_generic_break_event() {
|
||||
assert_eq!(w.get(pos), w.b().air());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_dripleaf_tilts_under_an_entity_standing_on_it() {
|
||||
let mut w = world!();
|
||||
w.floor(0, 2, "clay");
|
||||
let pos = BlockPos::new(0, 1, 0);
|
||||
let leaf = w.id("big_dripleaf", &[("facing", "north")]);
|
||||
w.put(pos, leaf);
|
||||
let stand = |w: &mut World, on_ground: bool, feet: f64| {
|
||||
w.f.behaviours
|
||||
.entity_on_big_dripleaf(&mut w.level, &mut w.ticks, pos, on_ground, feet);
|
||||
};
|
||||
// canEntityTilt: in the air, or with its feet at or under 0.6875, nothing.
|
||||
stand(&mut w, false, 1.9375);
|
||||
stand(&mut w, true, 1.6875);
|
||||
assert_eq!(w.prop(pos, "tilt"), "none");
|
||||
// Standing on the leaf's top (15/16): UNSTABLE, then PARTIAL and FULL
|
||||
// 10 ticks apart, and back to NONE 100 ticks later.
|
||||
stand(&mut w, true, 1.9375);
|
||||
assert_eq!(w.prop(pos, "tilt"), "unstable");
|
||||
for _ in 0..10 {
|
||||
w.tick();
|
||||
}
|
||||
assert_eq!(w.prop(pos, "tilt"), "partial");
|
||||
for _ in 0..10 {
|
||||
w.tick();
|
||||
}
|
||||
assert_eq!(w.prop(pos, "tilt"), "full");
|
||||
// A tilted leaf doesn't restart under the entity.
|
||||
stand(&mut w, true, 1.9375);
|
||||
assert_eq!(w.prop(pos, "tilt"), "full");
|
||||
for _ in 0..100 {
|
||||
w.tick();
|
||||
}
|
||||
assert_eq!(w.prop(pos, "tilt"), "none");
|
||||
// A powered leaf doesn't tilt.
|
||||
let power = w.id("redstone_block", &[]);
|
||||
w.put(BlockPos::new(1, 1, 0), power);
|
||||
stand(&mut w, true, 1.9375);
|
||||
assert_eq!(w.prop(pos, "tilt"), "none");
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ pub mod start_checks;
|
||||
pub mod stronghold;
|
||||
pub mod template;
|
||||
pub mod temple;
|
||||
pub mod yung;
|
||||
|
||||
use crate::{
|
||||
nbt::{self, Limits},
|
||||
|
||||
@@ -306,7 +306,6 @@ mod tests {
|
||||
legacy: false,
|
||||
projection,
|
||||
waterlogging: None,
|
||||
yung: None,
|
||||
enhanced_terrain: own.map(Arc::new),
|
||||
ground_level: 1,
|
||||
})
|
||||
|
||||
@@ -39,9 +39,6 @@ pub enum PoolElement {
|
||||
legacy: bool,
|
||||
projection: Projection,
|
||||
waterlogging: Option<bool>,
|
||||
/// YUNG's API's rules on the piece (`"horizon:yungsapi"`), read only
|
||||
/// by its assembler ([`super::yung`]).
|
||||
yung: Option<Box<super::yung::Rules>>,
|
||||
/// The piece's own terrain kernel in a structure that has one
|
||||
/// (`"horizon:enhanced_terrain_adaptation"`).
|
||||
enhanced_terrain: Option<Arc<super::enhanced_terrain::Adaptation>>,
|
||||
@@ -123,7 +120,7 @@ impl PoolElement {
|
||||
Ok(match kind {
|
||||
"minecraft:empty_pool_element" => Self::Empty,
|
||||
// YUNG's API's element places what a single element places; its
|
||||
// `name` and `max_count` are the pool entry's (`Pool::limits`).
|
||||
// own fields are the pool entry's rules (`Pool::rules`).
|
||||
"minecraft:single_pool_element"
|
||||
| "minecraft:legacy_single_pool_element"
|
||||
| "yungsapi:yung_single_element" => {
|
||||
@@ -149,10 +146,6 @@ impl PoolElement {
|
||||
Some("ignore_waterlogging") => Some(false),
|
||||
_ => None,
|
||||
},
|
||||
yung: value
|
||||
.get("horizon:yungsapi")
|
||||
.map(|rules| super::yung::Rules::decode(rules, resources).map(Box::new))
|
||||
.transpose()?,
|
||||
enhanced_terrain: value
|
||||
.get("horizon:enhanced_terrain_adaptation")
|
||||
.map(|a| super::enhanced_terrain::Adaptation::decode(a).map(Arc::new))
|
||||
@@ -248,13 +241,10 @@ impl PoolElement {
|
||||
.first()
|
||||
.map(|e| e.shuffled_jigsaws(resources, position, rotation, random))
|
||||
.unwrap_or_default(),
|
||||
Self::Single { template, yung, .. } => {
|
||||
Self::Single { template, .. } => {
|
||||
let mut jigsaws = template_jigsaws(resources, template, position, rotation);
|
||||
shuffle(&mut jigsaws, random);
|
||||
// YUNG's elements keep the shuffled order.
|
||||
if yung.is_none() {
|
||||
jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority));
|
||||
}
|
||||
jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority));
|
||||
jigsaws
|
||||
}
|
||||
}
|
||||
@@ -265,13 +255,6 @@ impl PoolElement {
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
/// YUNG's API's rules, on a piece of one of its structures.
|
||||
pub fn yung(&self) -> Option<&super::yung::Rules> {
|
||||
match self {
|
||||
Self::Single { yung, .. } => yung.as_deref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The piece's own terrain kernel, in place of its structure's.
|
||||
pub fn enhanced_terrain(&self) -> Option<&super::enhanced_terrain::Adaptation> {
|
||||
match self {
|
||||
@@ -340,9 +323,8 @@ pub struct Pool {
|
||||
pub(super) templates: Vec<Arc<PoolElement>>,
|
||||
/// The elements with their weights, in file order (`rawTemplates`).
|
||||
pub(super) raw: Vec<(Arc<PoolElement>, i32)>,
|
||||
/// Per entry of `raw`: a YUNG element's `name` and `max_count`, the most
|
||||
/// pieces of that name in one start.
|
||||
limits: Vec<Option<(Arc<str>, i32)>>,
|
||||
/// Per entry of `raw`: a YUNG element's rules.
|
||||
rules: Vec<Rules>,
|
||||
pub(super) fallback: String,
|
||||
max_size: OnceLock<i32>,
|
||||
}
|
||||
@@ -382,6 +364,37 @@ impl Pool {
|
||||
})
|
||||
}
|
||||
}
|
||||
/// A `yungsapi:yung_single_element`'s own fields (spec-yungsapi §3, §3.2).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Rules {
|
||||
/// `name` and `max_count`: the most pieces of that name in one start,
|
||||
/// the start not counted.
|
||||
limit: Option<(Arc<str>, i32)>,
|
||||
/// `is_priority`: tried before the pool's other entries, in the
|
||||
/// shuffled order and without a weighted draw.
|
||||
priority: bool,
|
||||
/// `min_required_depth`: the least depth of the parent piece (the start
|
||||
/// is depth 0).
|
||||
min_depth: i32,
|
||||
/// `ignore_bounds`: placed without the free-space test.
|
||||
ignore_bounds: bool,
|
||||
}
|
||||
impl Rules {
|
||||
fn of(element: &Value) -> Self {
|
||||
if element["element_type"] != "yungsapi:yung_single_element" {
|
||||
return Self::default();
|
||||
}
|
||||
Self {
|
||||
limit: element["name"]
|
||||
.as_str()
|
||||
.zip(element["max_count"].as_i64())
|
||||
.map(|(name, max)| (name.into(), max as i32)),
|
||||
priority: element["is_priority"].as_bool().unwrap_or(false),
|
||||
min_depth: element["min_required_depth"].as_i64().unwrap_or(0) as i32,
|
||||
ignore_bounds: element["ignore_bounds"].as_bool().unwrap_or(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Lazily decoded template pools.
|
||||
pub struct Pools {
|
||||
raw: BTreeMap<String, String>,
|
||||
@@ -410,7 +423,7 @@ impl Pools {
|
||||
}
|
||||
let pool = self.raw.get(name).and_then(|json| {
|
||||
let value: Value = serde_json::from_str(json).ok()?;
|
||||
let (mut templates, mut raw, mut limits) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (mut templates, mut raw, mut rules) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for entry in value["elements"].as_array()? {
|
||||
let element =
|
||||
match PoolElement::decode(&entry["element"], resources, bindings, None) {
|
||||
@@ -427,22 +440,12 @@ impl Pools {
|
||||
templates.push(element.clone());
|
||||
}
|
||||
raw.push((element, weight as i32));
|
||||
let fields = &entry["element"];
|
||||
limits.push(
|
||||
match (fields["name"].as_str(), fields["max_count"].as_i64()) {
|
||||
(Some(name), Some(max))
|
||||
if fields["element_type"] == "yungsapi:yung_single_element" =>
|
||||
{
|
||||
Some((name.into(), max as i32))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
);
|
||||
rules.push(Rules::of(&entry["element"]));
|
||||
}
|
||||
Some(Arc::new(Pool {
|
||||
templates,
|
||||
raw,
|
||||
limits,
|
||||
rules,
|
||||
fallback: value["fallback"]
|
||||
.as_str()
|
||||
.unwrap_or("minecraft:empty")
|
||||
@@ -621,9 +624,10 @@ pub trait JigsawContext {
|
||||
pub enum Draws {
|
||||
/// JigsawPlacement's.
|
||||
Vanilla,
|
||||
/// YUNG's API's `yungsapi:yung_jigsaw` (spec-yungsapi §2.1, §3.1): pools
|
||||
/// are drawn by weight from their file entries, without replacement, and
|
||||
/// an element at its `max_count` is skipped.
|
||||
/// YUNG's API's `yungsapi:yung_jigsaw` (spec-yungsapi §2.1, §3.1, §3.2):
|
||||
/// pools are drawn by weight from their file entries, without
|
||||
/// replacement, priority entries first, and an element at its
|
||||
/// `max_count` or too shallow is skipped.
|
||||
Yung,
|
||||
}
|
||||
|
||||
@@ -632,14 +636,28 @@ enum Candidates {
|
||||
/// Vanilla: the target pool's weight-expanded elements, then the
|
||||
/// fallback's, each shuffled up front.
|
||||
Listed(std::vec::IntoIter<Arc<PoolElement>>),
|
||||
/// YUNG's: weighted picks from each pool in turn (the fallback's only
|
||||
/// once the target's are spent), each pool's entries shuffled when it
|
||||
/// is reached.
|
||||
/// YUNG's: picks from each pool in turn (the fallback's only once the
|
||||
/// target's are spent), each pool's entries shuffled when it is
|
||||
/// reached: its priority entries in that order, then weighted picks
|
||||
/// from the others.
|
||||
Weighted {
|
||||
pools: Vec<Arc<Pool>>,
|
||||
current: Option<(Arc<Pool>, Vec<usize>)>,
|
||||
current: Option<Drawing>,
|
||||
},
|
||||
}
|
||||
/// A YUNG pool being drawn: entries (indices into `raw`) not tried yet.
|
||||
struct Drawing {
|
||||
pool: Arc<Pool>,
|
||||
priority: VecDeque<usize>,
|
||||
others: Vec<usize>,
|
||||
}
|
||||
/// An element to try.
|
||||
struct Pick {
|
||||
element: Arc<PoolElement>,
|
||||
/// Its YUNG name, counted toward `max_count` when it is placed.
|
||||
name: Option<Arc<str>>,
|
||||
ignore_bounds: bool,
|
||||
}
|
||||
impl Candidates {
|
||||
fn new(
|
||||
draws: Draws,
|
||||
@@ -667,37 +685,62 @@ impl Candidates {
|
||||
},
|
||||
}
|
||||
}
|
||||
/// The next element to try, with its YUNG name and limit.
|
||||
/// The next element to try for a jigsaw of a piece at `depth`.
|
||||
fn next(
|
||||
&mut self,
|
||||
counts: &HashMap<Arc<str>, i32>,
|
||||
depth: i32,
|
||||
random: &mut impl RandomSource,
|
||||
) -> Option<(Arc<PoolElement>, Option<Arc<str>>)> {
|
||||
) -> Option<Pick> {
|
||||
match self {
|
||||
Self::Listed(elements) => elements.next().map(|e| (e, None)),
|
||||
Self::Listed(elements) => elements.next().map(|element| Pick {
|
||||
element,
|
||||
name: None,
|
||||
ignore_bounds: false,
|
||||
}),
|
||||
Self::Weighted { pools, current } => loop {
|
||||
let (pool, order) = match current {
|
||||
Some((pool, order)) if !order.is_empty() => (pool, order),
|
||||
let drawing = match current {
|
||||
Some(d) if !d.priority.is_empty() || !d.others.is_empty() => d,
|
||||
_ => {
|
||||
let pool = pools.pop()?;
|
||||
let mut order: Vec<usize> = (0..pool.raw.len()).collect();
|
||||
shuffle(&mut order, random);
|
||||
*current = Some((pool, order));
|
||||
let (priority, others): (Vec<usize>, _) =
|
||||
order.into_iter().partition(|&i| pool.rules[i].priority);
|
||||
*current = Some(Drawing {
|
||||
pool,
|
||||
priority: priority.into(),
|
||||
others,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(at) = pool.weighted(order, random) else {
|
||||
order.clear();
|
||||
continue;
|
||||
let entry = match drawing.priority.pop_front() {
|
||||
Some(entry) => entry,
|
||||
None => {
|
||||
let Some(at) = drawing.pool.weighted(&drawing.others, random) else {
|
||||
drawing.others.clear();
|
||||
continue;
|
||||
};
|
||||
drawing.others.remove(at)
|
||||
}
|
||||
};
|
||||
let entry = order.remove(at);
|
||||
let limit = pool.limits[entry].clone();
|
||||
if let Some((name, max)) = &limit
|
||||
// spec-yungsapi §3.1 item 8: an empty element ends the
|
||||
// jigsaw (the caller's), then `max_count`, then the depth.
|
||||
let rules = &drawing.pool.rules[entry];
|
||||
if let Some((name, max)) = &rules.limit
|
||||
&& counts.get(name).copied().unwrap_or(0) >= *max
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Some((pool.raw[entry].0.clone(), limit.map(|(name, _)| name)));
|
||||
if depth < rules.min_depth {
|
||||
continue;
|
||||
}
|
||||
return Some(Pick {
|
||||
element: drawing.pool.raw[entry].0.clone(),
|
||||
name: rules.limit.as_ref().map(|(name, _)| name.clone()),
|
||||
ignore_bounds: rules.ignore_bounds,
|
||||
});
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -777,10 +820,10 @@ pub fn assemble_drawing(
|
||||
.unwrap_or_else(|| name.to_owned())
|
||||
};
|
||||
let center_pool = pools.get(&alias(config.start_pool), resources, bindings)?;
|
||||
let (rotation, element, limit) = match draws {
|
||||
let (rotation, element) = match draws {
|
||||
Draws::Vanilla => {
|
||||
let rotation = Rotation::random(random);
|
||||
(rotation, center_pool.random_template(random), None)
|
||||
(rotation, center_pool.random_template(random))
|
||||
}
|
||||
// The entries shuffled, then the rotation, then a weighted pick in
|
||||
// the shuffled order.
|
||||
@@ -789,9 +832,7 @@ pub fn assemble_drawing(
|
||||
shuffle(&mut order, random);
|
||||
let rotation = Rotation::random(random);
|
||||
let entry = order[center_pool.weighted(&order, random)?];
|
||||
let (element, _) = ¢er_pool.raw[entry];
|
||||
let limit = center_pool.limits[entry].clone().map(|(name, _)| name);
|
||||
(rotation, element.clone(), limit)
|
||||
(rotation, center_pool.raw[entry].0.clone())
|
||||
}
|
||||
};
|
||||
if matches!(element.as_ref(), PoolElement::Empty) {
|
||||
@@ -846,10 +887,10 @@ pub fn assemble_drawing(
|
||||
let low_y = (cy - v).max(context.min_y() + config.padding[0]);
|
||||
let high_y = (cy + v + 1).min(context.max_y() + 1 - config.padding[1]);
|
||||
let container = BoundingBox::new([cx - h, low_y, cz - h], [cx + h, high_y - 1, cz + h]);
|
||||
let counts = limit.into_iter().map(|name| (name, 1)).collect();
|
||||
// The start does not count toward `max_count` (spec-yungsapi §3).
|
||||
add_children_drawing(
|
||||
draws,
|
||||
counts,
|
||||
HashMap::new(),
|
||||
config,
|
||||
context,
|
||||
pools,
|
||||
@@ -1012,7 +1053,12 @@ impl Placer<'_, '_> {
|
||||
depth != self.config.max_depth,
|
||||
random,
|
||||
);
|
||||
while let Some((target, name)) = candidates.next(&self.counts, random) {
|
||||
while let Some(Pick {
|
||||
element: target,
|
||||
name,
|
||||
ignore_bounds,
|
||||
}) = candidates.next(&self.counts, depth, random)
|
||||
{
|
||||
if matches!(target.as_ref(), PoolElement::Empty) {
|
||||
break;
|
||||
}
|
||||
@@ -1074,7 +1120,7 @@ impl Placer<'_, '_> {
|
||||
let size = (expand_to + 1).max(target_box.max[1] - target_box.min[1]);
|
||||
target_box.max[1] = target_box.max[1].max(target_box.min[1] + size);
|
||||
}
|
||||
if !children_free.borrow().fits(&target_box) {
|
||||
if !ignore_bounds && !children_free.borrow().fits(&target_box) {
|
||||
continue;
|
||||
}
|
||||
children_free.borrow_mut().removed.push(target_box);
|
||||
|
||||
@@ -1025,7 +1025,6 @@ mod tests {
|
||||
legacy: false,
|
||||
projection: Projection::Rigid,
|
||||
waterlogging: None,
|
||||
yung: None,
|
||||
enhanced_terrain: None,
|
||||
ground_level: 1,
|
||||
});
|
||||
|
||||
@@ -59,8 +59,6 @@ pub struct JigsawDef {
|
||||
waterlogging: bool,
|
||||
/// A carried mod's start rules (`"horizon:start_checks"`).
|
||||
checks: super::start_checks::StartChecks,
|
||||
/// Laid out by YUNG's API's assembler (`"horizon:yungsapi"`).
|
||||
yung: Option<super::yung::Config>,
|
||||
/// Vanilla's draws, or YUNG's API's for `yungsapi:yung_jigsaw`.
|
||||
draws: super::jigsaw::Draws,
|
||||
/// Laid out by Repurposed Structures' and Moog's piece-limited
|
||||
@@ -111,9 +109,6 @@ pub struct StructureDef {
|
||||
/// A structure library's terrain kernel
|
||||
/// (`"horizon:enhanced_terrain_adaptation"`).
|
||||
pub enhanced_terrain: Option<super::enhanced_terrain::StructureAdaptation>,
|
||||
/// Another loaded structure turns this one's type off
|
||||
/// (`"horizon:disables"`): it never starts.
|
||||
pub disabled: bool,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Reduction {
|
||||
@@ -311,19 +306,8 @@ impl StructureRegistry {
|
||||
biome_set: &dyn Fn(&Value) -> Result<BTreeSet<BiomeId>, DecodeError>,
|
||||
) -> Result<Self, DecodeError> {
|
||||
let mut defs = Vec::new();
|
||||
let (mut types, mut disables) = (Vec::new(), BTreeSet::new());
|
||||
for (name, json) in structures {
|
||||
let v: Value = serde_json::from_str(json)?;
|
||||
types.push(v["type"].as_str().unwrap_or_default().to_owned());
|
||||
// YUNG's mods turn their vanilla counterparts off (the
|
||||
// DisableVanilla*Mixin on ChunkGenerator.tryGenerateStructure).
|
||||
disables.extend(
|
||||
v["horizon:disables"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|t| Some(t.as_str()?.to_owned())),
|
||||
);
|
||||
let draws = match v["type"].as_str() {
|
||||
Some("yungsapi:yung_jigsaw") => super::jigsaw::Draws::Yung,
|
||||
_ => super::jigsaw::Draws::Vanilla,
|
||||
@@ -347,7 +331,6 @@ impl StructureRegistry {
|
||||
padding: pair(v.get("dimension_padding"), "bottom", "top", 0),
|
||||
waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"),
|
||||
checks: super::start_checks::StartChecks::decode(v.get("horizon:start_checks")),
|
||||
yung: v.get("horizon:yungsapi").map(super::yung::Config::decode),
|
||||
piece_limited: v
|
||||
.get("horizon:piece_limited")
|
||||
.map(super::piece_limited::Config::decode),
|
||||
@@ -408,12 +391,8 @@ impl StructureRegistry {
|
||||
.get("horizon:enhanced_terrain_adaptation")
|
||||
.map(super::enhanced_terrain::StructureAdaptation::decode)
|
||||
.transpose()?,
|
||||
disabled: false,
|
||||
});
|
||||
}
|
||||
for (def, kind) in defs.iter_mut().zip(&types) {
|
||||
def.disabled = disables.contains(kind);
|
||||
}
|
||||
let index = |name: &str| defs.iter().position(|d| d.name == name);
|
||||
let mut out = Vec::new();
|
||||
for (name, json) in sets {
|
||||
@@ -891,9 +870,6 @@ fn try_generate(
|
||||
chunk: ChunkPos,
|
||||
) -> Option<StructureStart> {
|
||||
let def = ®istry.structures[structure];
|
||||
if def.disabled {
|
||||
return None;
|
||||
}
|
||||
context.set_valid_biomes(&def.biomes);
|
||||
let seed = context.seed();
|
||||
let mut random = WorldgenRandom::new(LegacyRandom::new(0));
|
||||
@@ -923,8 +899,8 @@ fn try_generate(
|
||||
padding: jigsaw.padding,
|
||||
waterlogging: jigsaw.waterlogging,
|
||||
};
|
||||
let (position, mut pieces) = match (&jigsaw.yung, &jigsaw.piece_limited) {
|
||||
(_, Some(limits)) => super::piece_limited::assemble(
|
||||
let (position, mut pieces) = match &jigsaw.piece_limited {
|
||||
Some(limits) => super::piece_limited::assemble(
|
||||
&config,
|
||||
limits,
|
||||
context,
|
||||
@@ -934,17 +910,7 @@ fn try_generate(
|
||||
chunk,
|
||||
start,
|
||||
)?,
|
||||
(Some(yung), None) => super::yung::assemble(
|
||||
&config,
|
||||
yung,
|
||||
context,
|
||||
®istry.pools,
|
||||
resources,
|
||||
bindings,
|
||||
&mut random,
|
||||
start,
|
||||
)?,
|
||||
(None, None) => assemble_drawing(
|
||||
None => assemble_drawing(
|
||||
jigsaw.draws,
|
||||
&config,
|
||||
context,
|
||||
@@ -1449,37 +1415,6 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_structure_turns_its_vanilla_counterpart_off() {
|
||||
let r = registry(
|
||||
&[
|
||||
(
|
||||
"minecraft:pyramid",
|
||||
json!({"type": "minecraft:desert_pyramid"}),
|
||||
),
|
||||
("minecraft:igloo", json!({"type": "minecraft:igloo"})),
|
||||
(
|
||||
"yung:temple",
|
||||
json!({"type": "minecraft:swamp_hut", "horizon:disables": ["minecraft:desert_pyramid"]}),
|
||||
),
|
||||
],
|
||||
&[],
|
||||
);
|
||||
let disabled: Vec<_> = r
|
||||
.structures
|
||||
.iter()
|
||||
.map(|d| (d.name.as_str(), d.disabled))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
disabled,
|
||||
[
|
||||
("minecraft:igloo", false),
|
||||
("minecraft:pyramid", true),
|
||||
("yung:temple", false)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclusion_zones_may_skip_the_other_sets_own() {
|
||||
let set = |avoid: Value| {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -112,6 +112,8 @@ fn invalid_or_excessive_domains_fail_before_world_queries() {
|
||||
/// and has an empty shape.
|
||||
struct Recording {
|
||||
cells: Vec<BlockPos>,
|
||||
/// Sections (block y >> 4) whose blocks never reach out of their cell.
|
||||
contained: Vec<i32>,
|
||||
}
|
||||
impl BlockCollisionWorld for Recording {
|
||||
type Error = io::Error;
|
||||
@@ -139,6 +141,40 @@ impl BlockCollisionWorld for Recording {
|
||||
) -> io::Result<VoxelShape> {
|
||||
unreachable!()
|
||||
}
|
||||
fn may_reach_out(&mut self, _: (), section_y: i32) -> io::Result<bool> {
|
||||
Ok(!self.contained.contains(§ion_y))
|
||||
}
|
||||
}
|
||||
|
||||
/// The cells the scan reads for `bounds` (Cursor3D order: x fastest, then
|
||||
/// y, then z, without the 8 corners), less the outer cells of `contained`.
|
||||
fn expected_cells(bounds: Aabb, contained: &[i32]) -> Vec<BlockPos> {
|
||||
let (min, max) = (bounds.min_position(), bounds.max_position());
|
||||
let start = BlockPos::containing(Vec3::new(min.x - 1.0e-7, min.y - 1.0e-7, min.z - 1.0e-7))
|
||||
.offset(-1, -1, -1);
|
||||
let end = BlockPos::containing(Vec3::new(max.x + 1.0e-7, max.y + 1.0e-7, max.z + 1.0e-7))
|
||||
.offset(1, 1, 1);
|
||||
let sizes = [
|
||||
end.x - start.x + 1,
|
||||
end.y - start.y + 1,
|
||||
end.z - start.z + 1,
|
||||
];
|
||||
let mut expected = Vec::new();
|
||||
for i in 0..sizes[0] * sizes[1] * sizes[2] {
|
||||
let r = [
|
||||
i % sizes[0],
|
||||
i / sizes[0] % sizes[1],
|
||||
i / sizes[0] / sizes[1],
|
||||
];
|
||||
let edges = (0..3)
|
||||
.filter(|&a| r[a] == 0 || r[a] == sizes[a] - 1)
|
||||
.count();
|
||||
let p = start.offset(r[0], r[1], r[2]);
|
||||
if edges < 3 && (edges == 0 || !contained.contains(&(p.y >> 4))) {
|
||||
expected.push(p);
|
||||
}
|
||||
}
|
||||
expected
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -150,7 +186,10 @@ fn cells_follow_the_cursor_order_without_corners() {
|
||||
Aabb::new(Vec3::new(-0.3, 0.0, -0.3), Vec3::new(0.3, 0.9, 0.3)),
|
||||
];
|
||||
for bounds in boxes {
|
||||
let mut world = Recording { cells: Vec::new() };
|
||||
let mut world = Recording {
|
||||
cells: Vec::new(),
|
||||
contained: Vec::new(),
|
||||
};
|
||||
let hits = BlockCollisionScan::new(
|
||||
&mut world,
|
||||
CollisionContext::empty(false),
|
||||
@@ -161,31 +200,76 @@ fn cells_follow_the_cursor_order_without_corners() {
|
||||
.unwrap()
|
||||
.count();
|
||||
assert_eq!(hits, 0);
|
||||
// Cursor3D: x fastest, then y, then z, skipping the 8 corners.
|
||||
let (min, max) = (bounds.min_position(), bounds.max_position());
|
||||
let start = BlockPos::containing(Vec3::new(min.x - 1.0e-7, min.y - 1.0e-7, min.z - 1.0e-7))
|
||||
.offset(-1, -1, -1);
|
||||
let end = BlockPos::containing(Vec3::new(max.x + 1.0e-7, max.y + 1.0e-7, max.z + 1.0e-7))
|
||||
.offset(1, 1, 1);
|
||||
let sizes = [
|
||||
end.x - start.x + 1,
|
||||
end.y - start.y + 1,
|
||||
end.z - start.z + 1,
|
||||
];
|
||||
let mut expected = Vec::new();
|
||||
for i in 0..sizes[0] * sizes[1] * sizes[2] {
|
||||
let r = [
|
||||
i % sizes[0],
|
||||
i / sizes[0] % sizes[1],
|
||||
i / sizes[0] / sizes[1],
|
||||
];
|
||||
let edges = (0..3)
|
||||
.filter(|&a| r[a] == 0 || r[a] == sizes[a] - 1)
|
||||
.count();
|
||||
if edges < 3 {
|
||||
expected.push(start.offset(r[0], r[1], r[2]));
|
||||
}
|
||||
}
|
||||
assert_eq!(world.cells, expected);
|
||||
assert_eq!(world.cells, expected_cells(bounds, &[]));
|
||||
}
|
||||
}
|
||||
|
||||
/// Outer cells are read only in sections that may hold a block reaching
|
||||
/// out of its cell; the box's own cells always are.
|
||||
#[test]
|
||||
fn outer_cells_of_contained_sections_are_not_read() {
|
||||
// A mob crossing from section 3 into section 4, and an item in section 0.
|
||||
let boxes = [
|
||||
(
|
||||
Aabb::new(Vec3::new(0.2, 63.5, 0.3), Vec3::new(0.8, 65.3, 0.9)),
|
||||
vec![3],
|
||||
),
|
||||
(
|
||||
Aabb::new(Vec3::new(0.2, 63.5, 0.3), Vec3::new(0.8, 65.3, 0.9)),
|
||||
vec![3, 4],
|
||||
),
|
||||
(
|
||||
Aabb::new(Vec3::new(4.4, 2.0, -7.6), Vec3::new(4.65, 2.25, -7.35)),
|
||||
vec![0],
|
||||
),
|
||||
// Across a chunk's edge: the rest of a row is passed only up to it.
|
||||
(
|
||||
Aabb::new(Vec3::new(14.2, 70.5, -0.4), Vec3::new(17.8, 71.5, 0.4)),
|
||||
vec![4],
|
||||
),
|
||||
];
|
||||
for (bounds, contained) in boxes {
|
||||
let mut world = Recording {
|
||||
cells: Vec::new(),
|
||||
contained: contained.clone(),
|
||||
};
|
||||
let hits = BlockCollisionScan::new(
|
||||
&mut world,
|
||||
CollisionContext::empty(false),
|
||||
bounds,
|
||||
false,
|
||||
1_000_000,
|
||||
)
|
||||
.unwrap()
|
||||
.count();
|
||||
assert_eq!(hits, 0);
|
||||
assert_eq!(world.cells, expected_cells(bounds, &contained));
|
||||
assert!(world.cells.len() < expected_cells(bounds, &[]).len());
|
||||
}
|
||||
}
|
||||
|
||||
/// Passing outer cells at once still stops at the candidate budget, as
|
||||
/// visiting them one by one does.
|
||||
#[test]
|
||||
fn passed_cells_count_toward_the_budget() {
|
||||
let bounds = Aabb::new(Vec3::new(0.2, 63.5, 0.3), Vec3::new(0.8, 65.3, 0.9));
|
||||
for budget in 0..80 {
|
||||
let scan = |contained: Vec<i32>| {
|
||||
let mut world = Recording {
|
||||
cells: Vec::new(),
|
||||
contained,
|
||||
};
|
||||
BlockCollisionScan::new(
|
||||
&mut world,
|
||||
CollisionContext::empty(false),
|
||||
bounds,
|
||||
false,
|
||||
budget,
|
||||
)
|
||||
.unwrap()
|
||||
.map(|hit| hit.map(|_| ()).map_err(|e| e.to_string()))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(scan(vec![3, 4]), scan(Vec::new()), "budget {budget}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
|
||||
| `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds |
|
||||
| `ui` | [`ui`](#ui) | show its own screens and a settings page |
|
||||
| `render` | [`render`](#render) | draw on your screen and shake the camera |
|
||||
| `input` | [`input`](#input) | take over the use button on its own items, and add keys |
|
||||
| `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items, and add keys |
|
||||
|
||||
## World `horizon-mod`
|
||||
|
||||
@@ -188,13 +188,21 @@ Rows the player picks one of, as an options page lists choices: a pick is `ui-ev
|
||||
| `rows` | `list<string>` | The rows' texts, at most 512, each up to 256 characters. |
|
||||
| `selected` | `option<u32>` | The row to mark as the current choice, if any. |
|
||||
|
||||
### variant `widget`
|
||||
### record `button-widget`
|
||||
|
||||
A thing on a mod's screen or settings page.
|
||||
A thing on a mod's screen or settings page. A button as the options pages have them (200 × 20): a click is `ui-events::select(id, 0)`. Mods cycle its label for a choice ("Corner: Top Left").
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `id` | `u32` | The mod's own name for the widget. |
|
||||
| `label` | `string` | Up to 256 characters. |
|
||||
|
||||
### variant `widget`
|
||||
|
||||
| Case | Payload | |
|
||||
| --- | --- | --- |
|
||||
| `text` | `text-widget` | Text the player reads. |
|
||||
| `button` | `button-widget` | A button. |
|
||||
| `item` | `item-widget` | An item's icon and name. |
|
||||
| `list` | `list-widget` | Rows the player picks from. |
|
||||
|
||||
@@ -257,12 +265,23 @@ The main hand's stack.
|
||||
| `key-down` | `string` | A key `register-key` named went down or up while playing (no screen open). The game's own mapping on that key still runs. |
|
||||
| `key-up` | `string` | |
|
||||
|
||||
### record `mapping-state`
|
||||
|
||||
A mapping as the player has bound it.
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `label` | `string` | The bound key's name as Controls shows it: `W`, `Space`, `LMB`. |
|
||||
| `down` | `bool` | Held down now (as of this frame for a mod with a `frame` hook, else this tick). |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `claim-items` | `func(ids: list<string>)` | The items whose use the mod handles instead of the game, by id (at most 64). Replaces the previous list. |
|
||||
| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`). At most 16; an unknown key is an error. |
|
||||
| `held` | `func() -> option<held-item>` | The main hand's stack, as of this tick; none when it is empty. |
|
||||
| `poll` | `func() -> list<event>` | The events since the last call, oldest first. |
|
||||
| `mapping` | `func(name: string) -> option<mapping-state>` | A movement or click mapping as the player has bound it: `key.forward`, `key.left`, `key.back`, `key.right`, `key.jump`, `key.sneak`, `key.sprint`, `key.attack` or `key.use`. None for another name. |
|
||||
| `clicks-per-second` | `func() -> tuple<u32, u32>` | Clicks of the attack and use buttons in the last second. |
|
||||
|
||||
## `render`
|
||||
|
||||
@@ -270,6 +289,17 @@ Access: capability `render`.
|
||||
|
||||
Capability `render` (experimental: the manifest needs `experimental = ["render"]`): shapes the game draws for the mod with its own renderer, kept until the mod replaces them (no call per frame). A mod never supplies shader code.
|
||||
|
||||
### enum `corner`
|
||||
|
||||
A corner of the screen, as `hud`'s panels use them.
|
||||
|
||||
| Case | |
|
||||
| --- | --- |
|
||||
| `top-left` | |
|
||||
| `top-right` | |
|
||||
| `bottom-left` | |
|
||||
| `bottom-right` | |
|
||||
|
||||
### record `rect`
|
||||
|
||||
A rectangle in GUI pixels: the top left corner and the size.
|
||||
@@ -342,11 +372,23 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun
|
||||
| `item` | `item-shape` | |
|
||||
| `text` | `text-shape` | |
|
||||
|
||||
### record `frame-rate`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `fps` | `u32` | Frames drawn in the last second. |
|
||||
| `min` | `u32` | The slowest frame's rate, and the 1% low (the 99th percentile frame time's rate), over the last 5 seconds. |
|
||||
| `low` | `u32` | |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `set-hud` | `func(shapes: list<shape>)` | Replaces the mod's HUD shapes: up to 1024, drawn every frame in order over the HUD (after the hotbar, under chat and screens), hidden with the HUD (F1). An empty list removes them. |
|
||||
| `gui-size` | `func() -> tuple<f32, f32>` | The screen's size in GUI pixels (width, height), as of this tick. |
|
||||
| `shake` | `func(strength: f32, seconds: f32)` | Shakes the camera: a jolt of `strength` (0 to 1, 1 the hardest) that fades out over `seconds` (at most 10). Jolts add up to 1. The view turns, the player doesn't, and the player's Distortion Effects option scales it (0 turns it off). |
|
||||
| `set-corner` | `func(corner: corner, width: f32, height: f32, shapes: list<shape>)` | Replaces the mod's corner panel: shapes in GUI pixels from the top left of a `width` × `height` box that the game places in `corner`, stacked with the game's overlays and the other mods' panels (under the status effects at the top right), as `hud`'s panels are. |
|
||||
| `clear-corner` | `func()` | Removes the mod's corner panel. |
|
||||
| `text-width` | `func(text: string) -> f32` | The width of one line of text in GUI pixels, in the HUD's font: exact for Latin letters (U+0000 to U+024F), 6 per other character. |
|
||||
| `frame-stats` | `func() -> frame-rate` | The game's frame counter, recomputed twice a second. |
|
||||
|
||||
## `events`
|
||||
|
||||
|
||||
@@ -99,6 +99,8 @@ What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
## Changelog
|
||||
|
||||
- Experimental: `ui` button widget; `render.set-corner`, `text-width`, `frame-stats`; `input.mapping`,
|
||||
`clicks-per-second` (what the official FPS, keystrokes and zoom mods need).
|
||||
- Experimental `input` (`experimental = ["input"]`): `claim-items`, `register-key`, `held`, `poll` (use-start,
|
||||
use-stop, key-down, key-up).
|
||||
- Experimental `render` (`experimental = ["render"]`): HUD shapes (fill, quad, sprite, item, text), `gui-size`, camera
|
||||
|
||||
+11
-9
@@ -15,7 +15,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
|
||||
| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, command, ui; tick, frame, chat and command hooks |
|
||||
| SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 |
|
||||
| Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands |
|
||||
| Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model |
|
||||
| Runtime | `crates/horizon-mods` | wasmtime 48 LTS, component model |
|
||||
| Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new [--template code\|content] / build / run / check`, and the registry's CI (`registry build / review / list`) |
|
||||
| In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods |
|
||||
| Launcher mod browser (Modrinth, CurseForge with a key) | [mod-browser.md](mod-browser.md) | resource packs, modpacks |
|
||||
@@ -87,9 +87,9 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
|
||||
| `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters |
|
||||
| `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call |
|
||||
| `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run |
|
||||
| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` |
|
||||
| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects. The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` |
|
||||
| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs); `held()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` |
|
||||
| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` |
|
||||
| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects. The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` |
|
||||
| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` |
|
||||
|
||||
| Hook (export) | When |
|
||||
|---|---|
|
||||
@@ -135,8 +135,10 @@ There is no file, socket, process or raw-input interface, on purpose.
|
||||
| native `cdylib` plugins | none | no: per OS and arch, unstable Rust ABI | yes | none | unsafe for players |
|
||||
| an embedded JVM | none per mod | yes | Java | 100+ MB, seconds of startup | see the research |
|
||||
|
||||
wasmtime 36 is a long-term-support line (security fixes until August 2027)
|
||||
that builds on the client's Rust 1.90. Only its `runtime`, `cranelift`,
|
||||
wasmtime 48 is a long-term-support line (security fixes until August 2028)
|
||||
and needs Rust 1.95. It reads WebAssembly with the same wasm-tools release
|
||||
(0.254) as the `wit-component` that packs mods and the SDK's `wit-bindgen`, so
|
||||
the build carries one copy of them. Only its `runtime`, `cranelift`,
|
||||
`component-model` and `std` features are on: no WASI, no async, no GC
|
||||
proposal, no profiling. Its cranelift backend generates native code for x86-64
|
||||
and ARM64 on Windows, macOS and Linux, which is why one `.hmod` serves them
|
||||
@@ -372,14 +374,14 @@ A pool addition holds `"elements"` as a pool does. This is what lithostitched's
|
||||
NeoForge and Fabric, and `horizon-port-pack carry` writes them from those.
|
||||
|
||||
A structure (and any of its pool elements, in place of the structure's) may
|
||||
hold `horizon:enhanced_terrain_adaptation`: YUNG's API's and
|
||||
MoogsStructureLib's terrain kernel, which carves or buries terrain around the
|
||||
hold `horizon:enhanced_terrain_adaptation`: MoogsStructureLib's terrain
|
||||
kernel, which carves or buries terrain around the
|
||||
pieces on top of vanilla's `terrain_adaptation`. `kernel_size` and
|
||||
`kernel_distance` shape the kernel; `top` and `bottom` (`carve`, `bury` or
|
||||
`none`) act above and below a piece's floor; `bottom_offset`, `padding`
|
||||
(`x`, `top`, `bottom`, `z`) and MoogsStructureLib's `band` (`bottom`, `top`,
|
||||
`piece_heights`) move the box it measures from. On a structure,
|
||||
`rigid_junctions` (YUNG's API) adds rigid pieces' junctions as well and
|
||||
`rigid_junctions` adds rigid pieces' junctions as well and
|
||||
`inflate` grows the start's box by the kernel radius. `kernel_size` 0 is
|
||||
none.
|
||||
|
||||
|
||||
+35
-9
@@ -247,9 +247,10 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
sends each target its packet).
|
||||
- hero-trading: the host and the guest each trade 20 wheat for an emerald, paying 14 with Hero I
|
||||
and 12 with Hero III; clearing the effect restores the ordinary price (#1365).
|
||||
- falling: an item and a falling block the host summons high up fall smoothly on the guest, a
|
||||
little further every tick between the server's updates (every 20 ticks), as their own
|
||||
client tick moves them (they used to hang, then jump down once a second, #1568).
|
||||
- falling: an item, a falling block and primed TNT the host summons high up fall smoothly on the
|
||||
guest, a little further every tick between the server's updates (every 20 ticks, 10 for
|
||||
TNT), as their own client tick moves them (they used to hang, then jump down once a
|
||||
second, #1568), and the TNT's fuse burns down on the guest too.
|
||||
- instant_digging: an instant survival break leaves no repeated stone hit sounds or stale server dig (#1908).
|
||||
- replant: flowers and crops replanted after a short harvest click stay planted for both players;
|
||||
the server forgets the completed instant break (#1880).
|
||||
@@ -6186,10 +6187,11 @@ CHECK_FNS.update(large_chest=check_large_chest)
|
||||
|
||||
|
||||
def check_falling(host, guest, out):
|
||||
"""ItemEntity and FallingBlockEntity tick on a client too (gravity, collisions, drag), and their
|
||||
position packets snap them (Entity's NO_OP InterpolationHandler). The server sends an item's
|
||||
and a falling block's position every 20 ticks, so between two updates the guest's own tick is
|
||||
what moves them: sampled every 2 ticks over the first 16, both are lower nearly every time."""
|
||||
"""ItemEntity, FallingBlockEntity and PrimedTnt tick on a client too (gravity, collisions, drag),
|
||||
and their position packets snap them (Entity's NO_OP InterpolationHandler). The server sends an
|
||||
item's and a falling block's position every 20 ticks and TNT's every 10, so between two updates
|
||||
the guest's own tick is what moves them: sampled every 2 ticks over the first 16, all three are
|
||||
lower nearly every time. The TNT's fuse (sent once, at spawn) counts down on the guest too."""
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
top = y + 30
|
||||
tag = 'falling_e2e'
|
||||
@@ -6198,7 +6200,10 @@ def check_falling(host, guest, out):
|
||||
f'{{Tags:["{tag}"],Item:{{id:"minecraft:diamond",count:1}},PickupDelay:32767}}')
|
||||
host('command', command=f'summon minecraft:falling_block {x + 2.5} {top} {z - 0.5} '
|
||||
f'{{Tags:["{tag}"],BlockState:{{Name:"minecraft:sand"}},DropItem:0b}}')
|
||||
heights = {'item': [], 'falling block': []}
|
||||
# Horizon's selectors don't see primed TNT yet: its fuse ends it in the air, 19 blocks down.
|
||||
host('command', command=f'summon minecraft:tnt {x + 4.5} {top} {z + 0.5} {{fuse:34s}}')
|
||||
heights = {'item': [], 'falling block': [], 'primed tnt': []}
|
||||
fuses = []
|
||||
try:
|
||||
for _ in range(8):
|
||||
items = [e['pos'][1] for e in guest.raw('entities', 48, 'minecraft:item')['entities']
|
||||
@@ -6206,8 +6211,12 @@ def check_falling(host, guest, out):
|
||||
blocks = [o['position'][1] for o in guest('status')['projectiles']
|
||||
if o.get('kind') == 'minecraft:falling_block'
|
||||
and abs(o['position'][0] - x - 2.5) < 0.5 and abs(o['position'][2] - z + 0.5) < 0.5]
|
||||
tnts = [o for o in guest('status')['projectiles'] if o.get('kind') == 'minecraft:tnt'
|
||||
and abs(o['position'][0] - x - 4.5) < 0.5 and abs(o['position'][2] - z - 0.5) < 0.5]
|
||||
heights['item'].append(items[0] if items else None)
|
||||
heights['falling block'].append(blocks[0] if blocks else None)
|
||||
heights['primed tnt'].append(tnts[0]['position'][1] if tnts else None)
|
||||
fuses.append(tnts[0]['fuse'] if tnts else None)
|
||||
guest.wait(2)
|
||||
guest.shot(out, 'falling')
|
||||
finally:
|
||||
@@ -6219,7 +6228,24 @@ def check_falling(host, guest, out):
|
||||
drops = sum(b < a for a, b in zip(seen, seen[1:]))
|
||||
# A tick or two can pass between two samples with no move; never most of them.
|
||||
assert drops >= len(seen) - 2, f'the {name} fell in {drops} of {len(seen) - 1} samples: {heights}'
|
||||
return heights
|
||||
# The server sends the TNT's fuse with each move, so each sample says how many ticks it has
|
||||
# fallen from rest: snapped to the server's place and ticking on, the guest has it exactly
|
||||
# there (it used to trail two ticks behind, interpolating towards each update).
|
||||
fell = [(h, 34 - f) for h, f in zip(heights['primed tnt'], fuses) if f is not None]
|
||||
assert fell and fell[-1][1] > fell[0][1], f'the TNT\'s fuse on the guest: {fuses}'
|
||||
off = max(abs(h - tnt_fall(top, n)) for h, n in fell)
|
||||
assert off < 0.01, f'the guest\'s TNT is {off:.3f} off its fall (height, ticks): {fell}'
|
||||
return {**heights, 'fuse': fuses}
|
||||
|
||||
|
||||
def tnt_fall(top, ticks):
|
||||
"""PrimedTnt.tick in open air from rest: its height after `ticks` ticks."""
|
||||
y, v = top, 0.0
|
||||
for _ in range(ticks):
|
||||
v -= 0.04
|
||||
y += v
|
||||
v *= 0.98
|
||||
return y
|
||||
|
||||
|
||||
CHECKS += ['falling']
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Horizon's client on a vanilla 26.3 dedicated server, end to end.
|
||||
|
||||
A vanilla server (the pinned server jar, offline mode, a flat world) and one Horizon game joined to it,
|
||||
driven by horizon-ctl. The server's console does what a server or its plugins do; the checks read what
|
||||
the game shows and what reaches the server (its console and, for custom click actions, its debug log).
|
||||
|
||||
python3 tools/server_e2e.py --bin-dir target/fast # every check
|
||||
python3 tools/server_e2e.py --bin-dir target/fast --check dialog
|
||||
|
||||
Checks:
|
||||
- dialog: `/dialog show` with a multi-action dialog (a message, a text and a boolean input, three
|
||||
buttons): the game shows it with its inputs and buttons, the text typed and the box ticked
|
||||
go back in a command template (`trigger`, run by the server) and in a custom action's
|
||||
payload (the server's "Received custom click action" line), `wait_for_response` leaves the
|
||||
waiting screen, and `/dialog clear` closes a dialog (servers used to see nothing: the game
|
||||
dropped the packets).
|
||||
- titles: a chest named with styles (`CustomName`, as a plugin's menu is): its screen's title keeps
|
||||
the colours and bold (it used to be flattened to plain grey).
|
||||
|
||||
The game runs with fresh HORIZON_HOME, launcher and XDG folders and without audio. Screenshots and both
|
||||
logs go to --out.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import lab # noqa: E402
|
||||
import test_rust_parity as base # noqa: E402
|
||||
from agent_control_e2e import Failed # noqa: E402
|
||||
from lan_e2e import Game # noqa: E402
|
||||
from test_dedicated_server_parity import Server # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PLAYER = 'Steve'
|
||||
PROPERTIES = {
|
||||
'online-mode': 'false',
|
||||
'white-list': 'false',
|
||||
'level-type': 'minecraft\\:flat',
|
||||
'generate-structures': 'false',
|
||||
'spawn-protection': '0',
|
||||
'view-distance': '3',
|
||||
'simulation-distance': '3',
|
||||
'pause-when-empty-seconds': '-1',
|
||||
}
|
||||
# MinecraftServer.handleCustomClickAction logs at debug level: the console shows that logger's debug lines.
|
||||
LOG4J = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders><Console name="out" target="SYSTEM_OUT"><PatternLayout pattern="[%level] %msg%n"/></Console></Appenders>
|
||||
<Loggers>
|
||||
<Logger name="net.minecraft.server.MinecraftServer" level="debug"/>
|
||||
<Root level="info"><AppenderRef ref="out"/></Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
"""
|
||||
|
||||
|
||||
def snbt(value):
|
||||
"""A JSON value as SNBT (strings quoted, booleans as bytes)."""
|
||||
if isinstance(value, bool):
|
||||
return '1b' if value else '0b'
|
||||
if isinstance(value, str):
|
||||
return json.dumps(value)
|
||||
if isinstance(value, list):
|
||||
return '[' + ','.join(snbt(v) for v in value) + ']'
|
||||
if isinstance(value, dict):
|
||||
return '{' + ','.join(f'{k}:{snbt(v)}' for k, v in value.items()) + '}'
|
||||
return str(value)
|
||||
|
||||
|
||||
def check_dialog(server, game, out):
|
||||
server.console('scoreboard objectives add answer trigger')
|
||||
server.console(f'scoreboard players enable {PLAYER} answer')
|
||||
dialog = {
|
||||
'type': 'minecraft:multi_action',
|
||||
'title': {'text': 'Sign in', 'color': 'gold'},
|
||||
'body': {'type': 'minecraft:plain_message', 'contents': 'Pick a number.'},
|
||||
'inputs': [
|
||||
{'type': 'minecraft:text', 'key': 'number', 'label': 'Number'},
|
||||
{'type': 'minecraft:boolean', 'key': 'agree', 'label': 'Agree', 'on_true': '1', 'on_false': '0'},
|
||||
],
|
||||
'actions': [
|
||||
{'label': 'Send', 'action': {'type': 'minecraft:dynamic/run_command',
|
||||
'template': 'trigger answer set $(number)$(agree)'}},
|
||||
{'label': 'Submit', 'action': {'type': 'minecraft:dynamic/custom', 'id': 'horizon:e2e',
|
||||
'additions': {'tag': 'x'}}},
|
||||
{'label': 'Wait', 'action': {'type': 'minecraft:dynamic/custom', 'id': 'horizon:wait'}},
|
||||
],
|
||||
'after_action': 'none',
|
||||
'pause': False, # a pausing dialog must close after an action
|
||||
}
|
||||
shown = {}
|
||||
server.console(f'dialog show {PLAYER} {snbt(dialog)}')
|
||||
game.raw('wait-for', 'screen', 'dialog', '--timeout', 30)
|
||||
state = game('state')
|
||||
shown['shown'] = state['dialog']['open']
|
||||
assert shown['shown']['title'] == 'Sign in', shown
|
||||
assert [i['key'] for i in shown['shown']['inputs']] == ['number', 'agree'], shown
|
||||
assert shown['shown']['buttons'] == ['Send', 'Submit', 'Wait'], shown
|
||||
game.shot(out, 'dialog')
|
||||
# The text, the box, then the command the template makes of them.
|
||||
game.raw('type', '4')
|
||||
game.raw('click', 'agree')
|
||||
game.raw('click', 'send')
|
||||
time.sleep(1)
|
||||
server.console(f'scoreboard players get {PLAYER} answer')
|
||||
server.wait_for(rf'{PLAYER} has 41 \[answer\]', timeout=30)
|
||||
shown['trigger'] = 41
|
||||
# A custom action: its additions and every input's tag.
|
||||
game.raw('click', 'submit')
|
||||
server.wait_for(r'Received custom click action horizon:e2e with payload', timeout=30)
|
||||
line = next(l for l in server.lines if 'horizon:e2e' in l)
|
||||
shown['custom'] = line.split('payload ', 1)[1]
|
||||
for part in ('agree:1b', 'number:"4"', 'tag:"x"'):
|
||||
assert part in shown['custom'], shown
|
||||
# after_action none: still open. Then clear it.
|
||||
assert game('state')['dialog']['open'], 'the dialog closed after an action with after_action none'
|
||||
server.console(f'dialog clear {PLAYER}')
|
||||
game.raw('wait-for', 'screen', 'playing', '--timeout', 30)
|
||||
# wait_for_response: the waiting screen until the server answers (here, never).
|
||||
server.console(f'dialog show {PLAYER} {snbt(dict(dialog, after_action="wait_for_response"))}')
|
||||
game.raw('wait-for', 'screen', 'dialog', '--timeout', 30)
|
||||
game.raw('click', 'wait')
|
||||
server.wait_for(r'Received custom click action horizon:wait', timeout=30)
|
||||
shown['waiting'] = game('state')['dialog']['screen']
|
||||
game.shot(out, 'waiting')
|
||||
assert shown['waiting'] == 'waiting_for_response', shown
|
||||
# Its Back works after 5 s, and so does Escape (clear_dialog leaves it open, as in vanilla).
|
||||
time.sleep(5.5)
|
||||
game.raw('key', 'esc', 'tap')
|
||||
game.raw('wait-for', 'screen', 'playing', '--timeout', 10)
|
||||
return shown
|
||||
|
||||
|
||||
def check_titles(server, game, out):
|
||||
# AbstractContainerScreen draws the title the server sent, its styles included (#1645). A named
|
||||
# chest is what a plugin's menu looks like: its CustomName is the open_screen title.
|
||||
x, y, z = (int(v // 1) for v in game('state')['player']['position'])
|
||||
chest = (x + 2, y, z)
|
||||
name = [{'text': 'Server ', 'color': 'gold', 'bold': True}, {'text': 'Selector', 'color': 'aqua'}]
|
||||
server.console(f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest{{CustomName:{snbt(name)}}}')
|
||||
game.wait(10)
|
||||
game.raw('interact', *chest)
|
||||
game.raw('wait-for', 'screen', 'container', '--timeout', 30)
|
||||
game.wait(5)
|
||||
title = game('screen').get('title')
|
||||
game.shot(out, 'titles')
|
||||
game.raw('key', 'esc', 'tap')
|
||||
# A list is its first component with the rest as its children: they inherit its bold.
|
||||
want = [{'text': 'Server ', 'color': '#FFAA00', 'bold': True, 'italic': False},
|
||||
{'text': 'Selector', 'color': '#55FFFF', 'bold': True, 'italic': False}]
|
||||
assert title == want, title
|
||||
return {'title': title}
|
||||
|
||||
|
||||
CHECKS = {'dialog': check_dialog, 'titles': check_titles}
|
||||
|
||||
|
||||
def run(bins, out, checks):
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
work = Path(tempfile.mkdtemp(prefix='hz-server-e2e-'))
|
||||
port = lab.free_port()
|
||||
directory = work / 'server'
|
||||
directory.mkdir()
|
||||
props = dict(PROPERTIES, **{'server-port': str(port)})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
(work / 'log4j2.xml').write_text(LOG4J)
|
||||
classpath = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
server = Server(['java', '-Xmx2g', f'-Dlog4j.configurationFile={work / "log4j2.xml"}', '-cp', classpath,
|
||||
'net.minecraft.server.Main', 'nogui'], directory, 'vanilla')
|
||||
game = Game('client', bins / 'horizon-ctl', lab.RESOURCES.resolve())
|
||||
for key in ('XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'HORIZON_LAUNCHER_HOME'):
|
||||
game.d.env[key] = str(game.work / key.lower())
|
||||
game.d.env['HORIZON_LAUNCHER_NO_SELF_UPDATE'] = '1'
|
||||
results = {}
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
server.console('gamerule spawn_mobs false')
|
||||
game('launch', wait=False, offscreen=sys.platform == 'darwin')
|
||||
game.raw('connect', f'127.0.0.1:{port}', PLAYER)
|
||||
game.raw('wait-for', 'loaded', '--timeout', 300)
|
||||
server.wait_for(rf'{PLAYER} joined the game')
|
||||
server.console(f'op {PLAYER}')
|
||||
game.wait(20)
|
||||
for name in checks:
|
||||
try:
|
||||
results[name] = {'pass': True, 'detail': CHECKS[name](server, game, out)}
|
||||
except (Failed, AssertionError, StopIteration, KeyError) as e:
|
||||
results[name] = {'pass': False, 'detail': repr(e)}
|
||||
print(f'[server] {name}: {"PASS" if results[name]["pass"] else "FAIL"} {results[name]["detail"]}')
|
||||
finally:
|
||||
(out / 'client.log').write_text(game.close())
|
||||
server.stop()
|
||||
shutil.copy(server.log_path, out / 'server.log')
|
||||
shutil.rmtree(game.work, ignore_errors=True)
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
|
||||
parser.add_argument('--check', action='append', choices=list(CHECKS), help='run only these checks (repeatable)')
|
||||
parser.add_argument('--out', default=str(ROOT / '.local/server-e2e'), help='screenshots and logs go here')
|
||||
args = parser.parse_args()
|
||||
if args.bin_dir:
|
||||
bins = Path(args.bin_dir).resolve()
|
||||
else:
|
||||
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'],
|
||||
cwd=ROOT, check=True)
|
||||
bins = ROOT / 'target/fast'
|
||||
out = Path(args.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
results = run(bins, out, args.check or list(CHECKS))
|
||||
print(json.dumps(results, indent=1))
|
||||
sys.exit(0 if results and all(r['pass'] for r in results.values()) else 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user