Merge remote-tracking branch 'origin/main' into fix/server-list-dialogs

# Conflicts:
#	crates/horizon-client/src/multiplayer.rs
This commit is contained in:
Ludovic Marie
2026-10-16 03:46:14 +02:00
78 changed files with 4566 additions and 390 deletions
+2
View File
@@ -199,6 +199,8 @@ It runs rustfmt, clippy with warnings denied, the tests of the crates you touche
[MIT](LICENSE), for the project's original work only. Dependencies keep their own licences. Minecraft is a trademark of Mojang Synergies AB; Minecraft code and assets belong to Mojang and Microsoft and are covered by the [Minecraft EULA](https://www.minecraft.net/en-us/eula). Decompiled game source and prepared resources stay on your machine and are never published.
Third-party credits and licenses: [Third-party notices](THIRD_PARTY_NOTICES.md).
## Author
Made by [Ludovic Marie](https://lu4ovic.com) ([@ludovic111](https://github.com/ludovic111)).
+31
View File
@@ -0,0 +1,31 @@
# Third-party notices
## CullLeaves
The optional leaf and mangrove-root face-culling behavior is adapted from
[CullLeaves](https://github.com/TeamMidnightDust/CullLeaves) by MidnightDust.
Its MIT license is reproduced below.
```text
MIT License
Copyright (c) 2020 MidnightDust
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
@@ -139,6 +139,7 @@ fn main() -> Result<()> {
blend_radius: 2,
smooth_lighting: true,
cutout_leaves: true,
cull_leaves: false,
};
let mut best = f64::MAX;
let mut quads = 0usize;
@@ -31,14 +31,7 @@ fn main() -> horizon_client::Result<()> {
};
let s = sprites.mips[layer as usize];
writeln!(out, "== {name}")?;
for mip in horizon_client::mipmap::generate(
base,
size.trailing_zeros(),
s.strategy,
s.alpha_cutoff_bias,
s.has_transparent,
s.item,
) {
for mip in horizon_client::mipmap::generate(base, size.trailing_zeros(), s) {
write!(out, "{}x{}", mip.width, mip.height)?;
for row in mip.pixels.chunks(mip.width as usize) {
out.push(' ');
@@ -134,6 +134,7 @@ fn scene(
blend_radius,
smooth_lighting,
cutout_leaves,
cull_leaves: false,
};
let section_y = int(&row["section_y"])?;
let started = Instant::now();
+3 -1
View File
@@ -518,7 +518,9 @@ impl ChatScreen {
}
if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) {
let parse = self.parse.as_ref().expect("parsed above");
let (range, list) = c.dispatcher.suggestions(parse, cursor_b, c.registries);
let (range, list) = c
.dispatcher
.client_suggestions(parse, cursor_b, c.registries);
self.pending = Some((range.0, list));
self.update_usage_info(m, c);
}
+24 -2
View File
@@ -930,19 +930,41 @@ impl Dispatcher {
let context = Context::new(0, start);
self.parse_nodes(0, input, start, &context, reg, reg.permission)
}
/// CommandDispatcher.getCompletionSuggestions at `cursor`.
/// CommandDispatcher.getCompletionSuggestions at `cursor`: brigadier
/// lists every child, whatever its requirement.
pub fn suggestions(
&self,
parse: &ParseResults,
cursor: usize,
reg: &Registries,
) -> (Range, Vec<Suggestion>) {
self.suggestions_within(parse, cursor, reg, u8::MAX)
}
/// The suggestions the player's chat shows: the client's tree only holds
/// the nodes the player may use (Commands.sendCommands prunes by canUse).
pub fn client_suggestions(
&self,
parse: &ParseResults,
cursor: usize,
reg: &Registries,
) -> (Range, Vec<Suggestion>) {
self.suggestions_within(parse, cursor, reg, reg.permission)
}
fn suggestions_within(
&self,
parse: &ParseResults,
cursor: usize,
reg: &Registries,
permission: u8,
) -> (Range, Vec<Suggestion>) {
let (parent, start, context) = parse.context.suggestion_context(cursor);
let start = start.min(cursor);
let truncated = &parse.input[..cursor.min(parse.input.len())];
let mut all = Vec::new();
// Brigadier lists every child, whatever its requirement.
for &child in &self.nodes[parent].children {
if self.nodes[child].permission > permission {
continue;
}
let mut builder = SuggestionsBuilder::new(truncated, start);
match &self.nodes[child].kind {
NodeKind::Literal(l) => {
@@ -185,6 +185,42 @@ fn vanilla_error_messages() {
assert_eq!(e.message.plain(), "argument.block.property.invalid");
}
#[test]
fn commands_need_allow_commands() {
// IntegratedServer.getProfilePermissions: the owner of a world without
// Allow Commands is at LevelBasedPermissionSet.ALL.
let reg = Registries {
permission: 0,
..reg()
};
let d = vanilla::game_dispatcher();
let e = d.parse("gamemode creative", &reg).executable().unwrap_err();
assert_eq!(e.message.plain(), "command.unknown.command");
assert!(d.parse("me waves", &reg).executable().is_ok());
let parse = d.parse("", &reg);
// Brigadier itself lists every literal; the chat's (client tree) only
// the ones the player may use.
assert!(
d.suggestions(&parse, 0, &reg)
.1
.iter()
.any(|s| s.text == "gamemode")
);
let root: Vec<String> = d
.client_suggestions(&parse, 0, &reg)
.1
.into_iter()
.map(|s| s.text)
.collect();
// Commands.java with CommandSelection.INTEGRATED: seed and version need no level.
assert_eq!(
root,
[
"help", "list", "me", "msg", "random", "seed", "teammsg", "tell", "tm", "trigger",
"version", "w"
]
);
}
#[test]
fn suggestions_like_vanilla() {
let root = suggestions("");
assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned()));
+2 -1
View File
@@ -164,7 +164,8 @@ fn operating_system() -> String {
)
}
fn cpu() -> String {
/// Logical processors and the CPU's name (`12x AMD Ryzen 5 5600X ...`).
pub fn cpu() -> String {
let threads = std::thread::available_parallelism().map_or(0, |n| n.get());
let name = if cfg!(target_os = "linux") {
read("/proc/cpuinfo").and_then(|t| {
+4
View File
@@ -72,6 +72,8 @@ pub struct DebugCharts {
pub ping: SampleLogger,
/// `bandwidthLogger`: bytes received per tick.
pub bandwidth: SampleLogger,
/// `MinecraftServer.smoothedTickTimeMillis`.
pub smoothed_tick_ms: f32,
previous_tick: Option<Instant>,
bytes_seen: Option<i64>,
}
@@ -110,6 +112,7 @@ impl DebugCharts {
self.bandwidth.reset();
self.previous_tick = None;
self.bytes_seen = None;
self.smoothed_tick_ms = 0.0;
}
/// One integrated server tick that started at `started` and ran its
/// tick method for `method` (`MinecraftServer.logFullTickTime` and
@@ -123,6 +126,7 @@ impl DebugCharts {
.max(method);
self.previous_tick = Some(started);
self.tick_times.log_full([full, method, 0, full - method]);
self.smoothed_tick_ms = self.smoothed_tick_ms * 0.8 + method as f32 / 1e6 * 0.199_999_99;
}
/// `BandwidthDebugMonitor.tick`: the bytes received since the last
/// tick, from the connection's running total.
+340
View File
@@ -0,0 +1,340 @@
//! `DebugScreenOverlay`: the F3 text. The entries of the default profile
//! (`DebugScreenEntries.PROFILES`) report priority lines, regular lines and
//! groups; the overlay splits them into a left and a right column and draws
//! them last, over any screen, at the debug GUI scale.
use crate::{
font::Font,
hud_layout::{GuiDraw, PoseOp, fill},
text::Text,
};
/// `extractLines`'s background: ARGB 0x90505050.
const BACKGROUND: u32 = 0x9050_5050;
/// `extractLines`'s text colour: ARGB 0xFFE0E0E0.
const TEXT: u32 = 0xFFE0_E0E0;
/// `Font.lineHeight`.
const LINE_HEIGHT: i32 = 9;
/// What the enabled entries reported (`DebugScreenDisplayer`).
#[derive(Default, Debug)]
pub struct Displayer {
left: Vec<String>,
right: Vec<String>,
lines: Vec<String>,
groups: Vec<(&'static str, Vec<String>)>,
}
impl Displayer {
/// `addPriorityLine`: to the shorter column, the left one first.
pub fn priority(&mut self, line: impl Into<String>) {
if self.left.len() > self.right.len() {
self.right.push(line.into());
} else {
self.left.push(line.into());
}
}
/// `addLine`: split between the columns after the priority lines.
pub fn line(&mut self, line: impl Into<String>) {
self.lines.push(line.into());
}
/// `addToGroup`: lines kept together, groups in the order first added.
pub fn group(&mut self, group: &'static str, lines: impl IntoIterator<Item = String>) {
let index = match self.groups.iter().position(|(g, _)| *g == group) {
Some(i) => i,
None => {
self.groups.push((group, Vec::new()));
self.groups.len() - 1
}
};
self.groups[index].1.extend(lines);
}
/// `extractRenderState`: the left and right columns, then `footer` (the
/// chart keys, shown while the overlay is open) under the left one.
pub fn columns(self, footer: &[String]) -> (Vec<String>, Vec<String>) {
let (mut left, mut right) = (self.left, self.right);
if !left.is_empty() {
left.push(String::new());
}
if !right.is_empty() {
right.push(String::new());
}
if !self.lines.is_empty() {
let mid = self.lines.len().div_ceil(2);
left.extend_from_slice(&self.lines[..mid]);
right.extend_from_slice(&self.lines[mid..]);
left.push(String::new());
if mid < self.lines.len() {
right.push(String::new());
}
}
let mid = self.groups.len().div_ceil(2);
for (i, (_, lines)) in self.groups.into_iter().enumerate() {
if lines.is_empty() {
continue;
}
let column = if i < mid { &mut left } else { &mut right };
column.extend(lines);
column.push(String::new());
}
if !footer.is_empty() {
left.push(String::new());
left.extend_from_slice(footer);
}
(left, right)
}
}
/// `Mth.wrapDegrees`.
fn wrap_degrees(angle: f32) -> f32 {
let wrapped = angle % 360.0;
if wrapped >= 180.0 {
wrapped - 360.0
} else if wrapped < -180.0 {
wrapped + 360.0
} else {
wrapped
}
}
/// `DebugEntryPosition` and `DebugEntrySectionPosition` for a camera at
/// `pos` looking `yaw`/`pitch` in `dimension` with `forced` force-loaded chunks.
pub fn position(
pos: [f64; 3],
yaw: f32,
pitch: f32,
dimension: &str,
forced: usize,
) -> Vec<String> {
let block = pos.map(|v| v.floor() as i32);
let (cx, sy, cz) = (block[0] >> 4, block[1] >> 4, block[2] >> 4);
// Direction.fromYRot: floor(yRot / 90 + 0.5) & 3 as a 2D data value.
let (direction, towards) = match ((f64::from(yaw) / 90.0 + 0.5).floor() as i32) & 3 {
0 => ("south", "Towards positive Z"),
1 => ("west", "Towards negative X"),
2 => ("north", "Towards negative Z"),
_ => ("east", "Towards positive X"),
};
vec![
format!("XYZ: {:.3} / {:.5} / {:.3}", pos[0], pos[1], pos[2]),
format!("Block: {} {} {}", block[0], block[1], block[2]),
format!(
"Chunk: {cx} {sy} {cz} [{} {} in r.{}.{}.mca]",
cx & 31,
cz & 31,
cx >> 5,
cz >> 5
),
format!(
"Facing: {direction} ({towards}) ({:.1} / {:.1})",
wrap_degrees(yaw),
wrap_degrees(pitch)
),
format!("{dimension} FC: {forced}"),
format!(
"Section-relative: {:02} {:02} {:02}",
block[0] & 15,
block[1] & 15,
block[2] & 15
),
]
}
/// `VideoMode.refreshRateLabel`: whole rates without decimals.
pub fn refresh_rate_label(hz: f64) -> String {
if hz == hz.round() {
format!("{}", hz as i64)
} else {
format!("{hz:.2}")
}
}
/// `DeviceInfo.vendorName` for a PCI vendor id.
pub fn vendor_name(id: u32) -> String {
match id {
0x10de => "NVIDIA Corporation".into(),
0x1002 | 0x1022 => "AMD".into(),
0x8086 => "Intel".into(),
0x106b => "Apple".into(),
0x5143 => "Qualcomm".into(),
0x13b5 => "ARM".into(),
0x10005 => "Mesa".into(),
0 => "unknown".into(),
other => format!("{other:#06x}"),
}
}
/// The overlay's scale against the GUI scale and the scaled screen size it
/// lays out in. `debugGuiScale`: -1 keeps the GUI scale, 0 (the default) is
/// half the largest automatic scale, n is `calculateScale(n)`; only a scale
/// below the GUI scale applies.
pub fn scale(
framebuffer: [i32; 2],
gui_scale: i32,
option: i32,
unicode: bool,
gui_size: [i32; 2],
) -> (f32, [i32; 2]) {
let scale = match option {
-1 => gui_scale,
0 => crate::window::calculate_scale(framebuffer, 0, unicode) / 2,
n => crate::window::calculate_scale(framebuffer, n, unicode),
};
if scale < gui_scale && scale > 0 {
(
scale as f32 / gui_scale as f32,
[framebuffer[0] / scale, framebuffer[1] / scale],
)
} else {
(1.0, gui_size)
}
}
/// `extractLines` for both columns under the overlay's pose: each line's
/// background first, then the text, right-aligned in the right column.
pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec<GuiDraw> {
let mut out = vec![GuiDraw::Push(vec![PoseOp::Scale(scale, scale)])];
for (lines, align_left) in [(columns[0], true), (columns[1], false)] {
let placed: Vec<(&String, i32, i32)> = lines
.iter()
.enumerate()
.filter(|(_, l)| !l.is_empty())
.map(|(i, l)| {
let w = font.width(l) as i32;
let left = if align_left { 2 } else { width - 2 - w };
(l, left, 2 + LINE_HEIGHT * i as i32)
})
.collect();
for (line, left, top) in &placed {
let w = font.width(line) as i32;
out.push(fill(
left - 1,
top - 1,
left + w + 1,
top + LINE_HEIGHT - 1,
BACKGROUND,
));
}
for (line, left, top) in placed {
out.push(GuiDraw::Text {
text: Text::literal(line.clone()),
x: left,
y: top,
color: TEXT,
shadow: false,
});
}
}
out.push(GuiDraw::Pop);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn lines(v: &[&str]) -> Vec<String> {
v.iter().map(|s| (*s).to_owned()).collect()
}
#[test]
fn columns_follow_the_vanilla_split() {
// The default profile's entries, sorted by identifier as
// DebugScreenEntryList.rebuildCurrentList does: fps, game_version,
// memory, player_position, player_section_position,
// simple_performance_impactors, system_specs, tps.
let mut d = Displayer::default();
d.priority("112 fps T: 120 (fifo) @165Hz");
d.priority("Minecraft 26.3 (26.3/vanilla)");
d.group("memory", lines(&["Mem: 25% 1046/4096MiB"]));
d.group("position", lines(&["XYZ: 1 / 2 / 3", "Block: 1 2 3"]));
d.group("position", lines(&["Section-relative: 01 02 03"]));
d.line("fancy-clouds B: 2");
d.line("Filtering: RGSS");
d.line("Terrain Rendering: multidrawindirect");
d.group(
"system",
lines(&["CPU: 12x Ryzen", "Display: 854x709 (NVIDIA)"]),
);
d.line("Integrated server @ 6.6/50.0 ms, 28 tx, 492 rx");
let footer = lines(&["Debug charts: ...", "To edit: press [F3+F6]"]);
let (left, right) = d.columns(&footer);
// As the issue's vanilla screenshot (#376) shows them.
assert_eq!(
left,
lines(&[
"112 fps T: 120 (fifo) @165Hz",
"",
"fancy-clouds B: 2",
"Filtering: RGSS",
"",
"Mem: 25% 1046/4096MiB",
"",
"XYZ: 1 / 2 / 3",
"Block: 1 2 3",
"Section-relative: 01 02 03",
"",
"",
"Debug charts: ...",
"To edit: press [F3+F6]",
])
);
assert_eq!(
right,
lines(&[
"Minecraft 26.3 (26.3/vanilla)",
"",
"Terrain Rendering: multidrawindirect",
"Integrated server @ 6.6/50.0 ms, 28 tx, 492 rx",
"",
"CPU: 12x Ryzen",
"Display: 854x709 (NVIDIA)",
"",
])
);
}
#[test]
fn position_lines_match_vanilla() {
// The issue's vanilla screenshot (#376).
assert_eq!(
position([108.5, 104.0, -51.5], -1.0, 7.1, "minecraft:overworld", 0),
lines(&[
"XYZ: 108.500 / 104.00000 / -51.500",
"Block: 108 104 -52",
"Chunk: 6 6 -4 [6 28 in r.0.-1.mca]",
"Facing: south (Towards positive Z) (-1.0 / 7.1)",
"minecraft:overworld FC: 0",
"Section-relative: 12 08 12",
])
);
assert_eq!(
position([0.0, 64.0, 0.0], 450.0, 0.0, "minecraft:the_nether", 2)[3],
"Facing: west (Towards negative X) (90.0 / 0.0)"
);
assert_eq!(refresh_rate_label(165.0), "165");
assert_eq!(refresh_rate_label(59.94), "59.94");
}
#[test]
fn debug_scale_is_half_the_automatic_scale() {
// The issue's window: 854x709 at GUI scale 2 draws F3 at scale 1.
assert_eq!(
scale([854, 709], 2, 0, false, [427, 355]),
(0.5, [854, 709])
);
// 1920x1080 at GUI scale 4: auto is 4, so F3 is at 2.
assert_eq!(
scale([1920, 1080], 4, 0, false, [480, 270]),
(0.5, [960, 540])
);
// A GUI scale already at or under the debug scale is kept.
assert_eq!(
scale([1920, 1080], 2, 0, false, [960, 540]),
(1.0, [960, 540])
);
assert_eq!(
scale([1920, 1080], 3, -1, false, [640, 360]),
(1.0, [640, 360])
);
}
}
+266
View File
@@ -0,0 +1,266 @@
//! Conservative, budgeted occlusion against full opaque block cross-sections.
//!
//! A covered projection rectangle proves that an entire bounding box is hidden.
//! Testing a few rays would miss openings between those rays.
use std::cell::Cell;
const EPSILON: f64 = 1.0e-5;
pub struct Culler {
pub camera: [f64; 3],
remaining: Cell<usize>,
}
impl Culler {
pub fn new(camera: [f64; 3], budget: usize) -> Self {
Self {
camera,
remaining: Cell::new(budget),
}
}
/// Remove only this entity's completed camera-relative mesh when hidden.
pub fn cull_vertices(
&self,
vertices: &mut Vec<crate::mesher::Vertex>,
start: usize,
opaque: impl FnMut([i32; 3]) -> bool,
) -> bool {
if start >= vertices.len() || self.remaining.get() == 0 {
return false;
}
let mut min = [f64::INFINITY; 3];
let mut max = [f64::NEG_INFINITY; 3];
for vertex in &vertices[start..] {
for a in 0..3 {
let value = f64::from(vertex.pos[a]) + self.camera[a];
if !value.is_finite() {
return false;
}
min[a] = min[a].min(value);
max[a] = max[a].max(value);
}
}
// 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
}
/// Returns true only when a complete opaque block plane covers the bounds.
/// Unknown blocks, invalid bounds and an exhausted lookup budget stay visible.
pub fn occluded(
&self,
min: [f64; 3],
max: [f64; 3],
mut opaque: impl FnMut([i32; 3]) -> bool,
) -> bool {
if (0..3).any(|a| {
!self.camera[a].is_finite()
|| !min[a].is_finite()
|| !max[a].is_finite()
|| min[a] > max[a]
}) {
return false;
}
let mut best = (0, 0.0, 0.0);
for a in 0..3 {
let (gap, sign) = if self.camera[a] < min[a] {
(min[a] - self.camera[a], 1.0)
} else {
(self.camera[a] - max[a], -1.0)
};
if gap > best.1 {
best = (a, gap, sign);
}
}
let (axis, gap, sign) = best;
if !gap.is_finite() || gap <= EPSILON {
return false;
}
let across = [(axis + 1) % 3, (axis + 2) % 3];
let Some(mut cell) = floor_cell(self.camera[axis]) else {
return false;
};
let step = sign as i32;
if (f64::from(cell) + 0.5 - self.camera[axis]) * sign <= EPSILON {
let Some(next) = cell.checked_add(step) else {
return false;
};
cell = next;
}
loop {
let depth = (f64::from(cell) + 0.5 - self.camera[axis]) * sign;
if depth >= gap - EPSILON || self.remaining.get() == 0 {
return false;
}
let mut lo = [f64::INFINITY; 2];
let mut hi = [f64::NEG_INFINITY; 2];
for corner in 0..8 {
let point: [f64; 3] = std::array::from_fn(|a| {
if corner & (1 << a) == 0 {
min[a]
} else {
max[a]
}
});
let t = depth / ((point[axis] - self.camera[axis]) * sign);
for (i, &a) in across.iter().enumerate() {
let p = self.camera[a] + t * (point[a] - self.camera[a]);
if !p.is_finite() {
return false;
}
lo[i] = lo[i].min(p);
hi[i] = hi[i].max(p);
}
}
let bounds = [
floor_cell(lo[0] - EPSILON),
floor_cell(hi[0] + EPSILON),
floor_cell(lo[1] - EPSILON),
floor_cell(hi[1] + EPSILON),
];
let [Some(x0), Some(x1), Some(y0), Some(y1)] = bounds else {
return false;
};
let mut pos = [0; 3];
pos[axis] = cell;
pos[across[0]] = x0 + ((i64::from(x1) - i64::from(x0)) / 2) as i32;
pos[across[1]] = y0 + ((i64::from(y1) - i64::from(y0)) / 2) as i32;
self.remaining.set(self.remaining.get() - 1);
if opaque(pos) {
let area = (i64::from(x1) - i64::from(x0) + 1)
.checked_mul(i64::from(y1) - i64::from(y0) + 1)
.and_then(|n| usize::try_from(n).ok());
let Some(area) = area.filter(|&n| n <= self.remaining.get()) else {
return false;
};
// Reserve the worst-case lookups before walking the rectangle.
self.remaining.set(self.remaining.get() - area);
let covered = (x0..=x1).all(|x| {
(y0..=y1).all(|y| {
pos[across[0]] = x;
pos[across[1]] = y;
opaque(pos)
})
});
if covered {
return true;
}
}
let Some(next) = cell.checked_add(step) else {
return false;
};
cell = next;
}
}
}
fn floor_cell(value: f64) -> Option<i32> {
let n = value.floor();
(n.is_finite() && n >= f64::from(i32::MIN) && n <= f64::from(i32::MAX)).then_some(n as i32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn completed_mesh_culling_preserves_prior_geometry_and_protruding_parts() {
let vertex = |pos| crate::mesher::Vertex {
pos,
uv: [0.0; 2],
layer: 0,
color: u32::MAX,
light: 0,
normal: [0; 4],
};
let prior = vertex([0.0; 3]);
let body = [vertex([8.0, -1.0, -1.0]), vertex([10.0, 1.0, 1.0])];
let wall = |p: [i32; 3]| p[0] == 4 && (-1..=0).contains(&p[1]);
let mut hidden = vec![prior];
hidden.extend(body);
assert!(Culler::new([0.0; 3], 1_000).cull_vertices(&mut hidden, 1, wall));
assert_eq!(hidden.len(), 1);
assert_eq!(hidden[0].pos, prior.pos);
// A held item or animated part beyond the wall keeps the whole model.
let mut exposed = vec![prior];
exposed.extend(body);
exposed.push(vertex([8.0, 5.0, 0.0]));
let before = exposed.clone();
assert!(!Culler::new([0.0; 3], 1_000).cull_vertices(&mut exposed, 1, wall));
assert_eq!(
bytemuck::cast_slice::<_, u8>(&exposed),
bytemuck::cast_slice::<_, u8>(&before)
);
assert!(!Culler::new([0.0; 3], 0).cull_vertices(&mut exposed, 1, |_| panic!()));
}
#[test]
fn opaque_walls_hide_bounds_in_all_directions() {
for axis in 0..3 {
for sign in [-1.0, 1.0] {
let mut min = [-2.0; 3];
let mut max = [2.0; 3];
min[axis] = if sign > 0.0 { 8.0 } else { -10.0 };
max[axis] = if sign > 0.0 { 10.0 } else { -8.0 };
let wall = if sign > 0.0 { 4 } else { -5 };
assert!(Culler::new([0.0; 3], 1_000).occluded(min, max, |p| p[axis] == wall));
}
}
}
#[test]
fn windows_slits_and_partial_walls_stay_visible() {
let min = [8.0, -4.0, -4.0];
let max = [10.0, 4.0, 4.0];
for opening in 0..3 {
assert!(!Culler::new([0.0; 3], 1_000).occluded(min, max, |p| {
p[0] == 4
&& match opening {
0 => !(p[1] == 1 && p[2] == 1),
1 => p[1] != 1,
_ => p[1] < 0,
}
}));
}
assert!(!Culler::new([0.0; 3], 1_000).occluded(min, max, |_| false));
}
#[test]
fn budgets_are_shared_and_exhaustion_fails_open() {
let culler = Culler::new([0.0; 3], 3);
let calls = Cell::new(0);
for _ in 0..2 {
assert!(!culler.occluded([8.0; 3], [10.0; 3], |_| {
calls.set(calls.get() + 1);
false
}));
}
assert_eq!(calls.get(), 3);
assert!(!Culler::new([0.0; 3], 0).occluded([8.0; 3], [10.0; 3], |_| panic!()));
assert!(!Culler::new([0.0; 3], 1).occluded([8.0; 3], [10.0; 3], |_| true));
}
#[test]
fn camera_inside_invalid_and_target_crossing_wall_stay_visible() {
let culler = Culler::new([0.0; 3], 1_000);
assert!(!culler.occluded([-1.0; 3], [1.0; 3], |_| panic!()));
assert!(!culler.occluded([f64::NAN; 3], [1.0; 3], |_| panic!()));
assert!(!culler.occluded([2.0; 3], [1.0; 3], |_| panic!()));
assert!(!culler.occluded([4.0, -1.0, -1.0], [8.0, 1.0, 1.0], |p| p[0] == 4));
assert!(!Culler::new([f64::INFINITY; 3], 1_000).occluded(
[8.0; 3],
[10.0; 3],
|_| panic!()
));
assert!(!Culler::new([f64::MAX; 3], 1_000).occluded(
[-f64::MAX; 3],
[-1.0; 3],
|_| panic!()
));
}
}
+8 -2
View File
@@ -842,8 +842,14 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
Some(Ping::Ok {
motd, players, ms, ..
}) => (
motd.lines().next().unwrap_or("").trim().to_owned(),
format!("{players} · {ms} ms"),
motd.resolve_legacy()
.plain()
.lines()
.next()
.unwrap_or("")
.trim()
.to_owned(),
format!("{} · {ms} ms", Ping::player_count(*players).plain()),
color::ACCENT,
),
Some(Ping::Failed(_)) => (
+83 -134
View File
@@ -34,6 +34,7 @@ mod dispenser;
mod dragon;
mod enchant_effects;
mod end;
mod entity_culling;
mod events;
mod explosion;
mod extras;
@@ -56,6 +57,7 @@ mod item_particles;
mod jukebox;
mod lan;
mod lan_actions;
mod lan_crafting;
mod lan_screen;
mod lan_trading;
mod leads;
@@ -966,6 +968,7 @@ struct Game<'a> {
pending_uploads: Vec<((i32, i32, i32), horizon_client::mesher::SectionMesh)>,
/// 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>,
/// A scripted flight from the control socket (`fly`).
flight: Option<control::Flight>,
/// The running agent action from the control socket (game/agent.rs).
@@ -1010,13 +1013,14 @@ struct Game<'a> {
/// position) for the guests.
lan_block_events: Vec<([i32; 3], i32, i32, u16)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
/// `ContainerOpenersCounter`: how many players (the host and the guests)
/// have each chest open.
lid_openers: HashMap<(i32, i32, i32), i32>,
lan_acting: Option<u32>,
/// Command feedback to forward to a guest.
chat_capture: Option<Vec<horizon_client::text::Text>>,
/// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends.
cmds: commands::extra::CommandExtras,
/// Allow Cheats: whether guests may be given commands.
cheats: bool,
ui: chat::UiState,
combat: combat::CombatTracker,
mount: mounts::MountState,
@@ -3611,6 +3615,9 @@ impl Game<'_> {
}
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
let mut batch = self.hud_layers(size);
// Gui.extractRenderState: the debug overlay comes after the screen
// and the toasts, so it is over everything, menus included.
self.draw_debug_overlay(&mut batch, size);
self.frame_graph
.draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas);
self.draw_pad_cursor(&mut batch);
@@ -3673,7 +3680,8 @@ impl Game<'_> {
let indicator = self.settings.attack_indicator;
let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed());
let strength = self.hand_strength.scale(0.0, self.main_hand_attack_speed());
if self.camera_type.first_person() && !spectator {
// The 3D crosshair (F3) takes the 2D one's place.
if self.camera_type.first_person() && !spectator && !self.debug_crosshair() {
let attack = (indicator == 1).then_some(strength);
let full = attack.is_some_and(|a| {
hud_layout::full_attack_indicator(a, delay, self.crosshair_living())
@@ -3791,117 +3799,6 @@ impl Game<'_> {
}
}
let atlas = &self.res.atlas;
if self.debug {
let p = self
.player
.as_ref()
.map(|p| p.position)
.unwrap_or(Vec3::ZERO);
let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
let biome = self
.world
.chunks
.get(&(block[0] >> 4, block[2] >> 4))
.map(|c| {
self.res
.biomes
.get(c.biome(block[0], block[1], block[2]))
.name
.clone()
})
.unwrap_or_default();
let light = self.world.light(block[0], block[1], block[2]);
let facing = match ((self.yaw.rem_euclid(360.0) + 45.0) / 90.0) as i32 % 4 {
0 => "south (Towards positive Z)",
1 => "west (Towards negative X)",
2 => "north (Towards negative Z)",
_ => "east (Towards positive X)",
};
let mut lines = vec![
format!("Horizon 26.3 (Rust) {:.0} fps", self.fps),
format!(
"C: {} chunks, {} sections drawn / {}",
self.world.chunks.len(),
self.renderer.as_ref().map_or(0, |r| r.drawn_sections),
self.renderer.as_ref().map_or(0, |r| r.section_count())
),
format!("Pending jobs: {}", self.streaming.pending()),
String::new(),
format!("XYZ: {:.3} / {:.5} / {:.3}", p.x, p.y, p.z),
format!("Block: {} {} {}", block[0], block[1], block[2]),
format!(
"Chunk: {} {} {} in {} {} {}",
block[0] & 15,
block[1] & 15,
block[2] & 15,
block[0] >> 4,
block[1] >> 4,
block[2] >> 4
),
format!(
"Facing: {facing} ({:.1} / {:.1})",
self.yaw.rem_euclid(360.0)
- if self.yaw.rem_euclid(360.0) > 180.0 {
360.0
} else {
0.0
},
self.pitch
),
format!(
"Light: {} (sky {}, block {})",
(light >> 4).max(light & 15),
light >> 4,
light & 15
),
format!("Biome: {biome}"),
format!(
"Day {} time {}",
self.world.day_time / 24000,
self.world.day_time % 24000
),
String::new(),
];
lines.extend(self.debug_chart_lines());
for (i, line) in lines.iter().enumerate() {
if line.is_empty() {
continue;
}
let tw = HudBatch::text_width(atlas, line);
batch.fill(
atlas,
1.0,
2.0 + i as f32 * 9.0 - 1.0,
tw + 2.0,
9.0,
rgba(80, 80, 80, 144),
);
batch.text(
atlas,
line,
2.0,
2.0 + i as f32 * 9.0,
rgba(224, 224, 224, 255),
false,
);
}
let charts = self.debug_charts.draw(
&atlas.font,
w as i32,
h as i32,
self.settings.max_fps,
1000.0 / self.clock.rate(),
self.remote.is_some(),
);
hud_layout::paint(&mut batch, atlas, &charts);
if self.debug_charts.lightmap
&& let Some(r) = &self.renderer
{
let view =
horizon_client::debug_chart::lightmap(&r.lightmap_pixels, w as i32, h as i32);
hud_layout::paint(&mut batch, atlas, &view);
}
}
if !self.ui.hide_gui
&& let Some((text, at)) = &self.message
&& at.elapsed() < Duration::from_secs(3)
@@ -5296,6 +5193,7 @@ impl Game<'_> {
alpha: f64,
mut out: Vec<Vertex>,
) -> Vec<Vertex> {
self.prepare_entity_culling(camera);
let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront {
self.yaw + 180.0
} else {
@@ -5483,9 +5381,21 @@ impl Game<'_> {
v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0))
})
});
self.res
.block_entity_render
.render(&scene, visible, &mut out);
if self.entity_culler.is_some() {
for block in visible {
let start = out.len();
self.res
.block_entity_render
.render(&scene, std::iter::once(block), &mut out);
if !off_screen(block.1) {
self.cull_entity_vertices(&mut out, start);
}
}
} else {
self.res
.block_entity_render
.render(&scene, visible, &mut out);
}
}
// Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet.
if let Some(r) = self
@@ -6156,7 +6066,6 @@ impl Game<'_> {
horizon_client::save::migrate_legacy(&save_root)?;
self.session_lock = None;
self.session_lock = Some(horizon_client::save::SessionLock::acquire(&save_root)?);
self.persist = Default::default();
self.score = Default::default();
self.fns = Default::default();
self.bosses = Default::default();
@@ -6195,6 +6104,11 @@ impl Game<'_> {
level.allow_commands = Some(o.commands(creative));
horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?;
}
// Worlds made without the Create New World screen (--world, the
// control socket) take its default: commands on for Creative only.
if created {
level.allow_commands.get_or_insert(creative);
}
horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name));
if let Some(d) = &self.options.dimension {
level.dimension = d.clone();
@@ -6290,8 +6204,7 @@ impl Game<'_> {
self.block_ticks = Ticks::new(self.level.seed as i32);
self.install_live_features();
self.tick_chunks.clear();
self.falling.clear();
self.tnts.clear();
self.clear_entities();
self.travelling = None;
self.player = None;
self.spawn = None;
@@ -6310,14 +6223,8 @@ impl Game<'_> {
self.spawn_origin = None;
self.spawn_spiral = Default::default();
self.player_spawn = None;
self.mobs.clear();
self.creatures.reset_trader();
self.portals = Default::default();
self.creatures.projectiles.clear();
self.dropped.clear();
self.particles.clear();
self.pickups.clear();
self.orbs.clear();
self.experience = Experience {
level: self.level.xp_level,
progress: self.level.xp_progress,
@@ -6413,6 +6320,7 @@ impl Game<'_> {
streaming.biome_blend = self.settings.biome_blend;
streaming.smooth_lighting = self.settings.smooth_lighting;
streaming.cutout_leaves = self.settings.cutout_leaves;
streaming.cull_leaves = self.settings.horizon.cull_leaves;
streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed));
streaming.sky_light = dim != Dim::Nether;
streaming.nether_shading = dim == Dim::Nether;
@@ -6640,11 +6548,7 @@ impl Game<'_> {
self.streaming.paused = true;
self.world = World::new(self.res.facts.air, 0);
self.player = None;
self.mobs.clear();
self.creatures.projectiles.clear();
self.dropped.clear();
self.particles.clear();
self.pickups.clear();
self.clear_entities();
self.screen = Screen::Playing;
if let Some(r) = self.renderer.as_mut() {
r.clear_sections();
@@ -6656,6 +6560,33 @@ impl Game<'_> {
self.capture(false);
Ok(())
}
/// Let go of every entity of the level (saved first): the next world
/// opened must not inherit them, nor save them as its own.
fn clear_entities(&mut self) {
self.mobs.clear();
self.dropped.clear();
self.orbs.clear();
self.creatures.projectiles.clear();
self.falling.clear();
self.tnts.clear();
self.boats.clear();
self.carts.clear();
self.armor_stands.clear();
self.item_frames.clear();
self.paintings.clear();
self.others.clear();
self.dragon = None;
self.crystals.clear();
self.dragon_fireballs.clear();
self.breath_clouds.clear();
self.tridents.clear();
self.rockets.clear();
self.bolts.clear();
self.particles.clear();
self.pickups.clear();
self.riding = None;
self.persist = Default::default();
}
/// Equipment attribute modifiers (LivingEntity.collectEquipmentChanges).
fn apply_equipment(&mut self) {
let Some(player) = self.player.as_mut() else {
@@ -7673,11 +7604,21 @@ impl Game<'_> {
// Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves:
// LevelExtractor.allChanged when they change.
let (s, st) = (&self.settings, &self.streaming);
let remesh = (s.biome_blend, s.smooth_lighting, s.cutout_leaves)
!= (st.biome_blend, st.smooth_lighting, st.cutout_leaves);
let remesh = (
s.biome_blend,
s.smooth_lighting,
s.cutout_leaves,
s.horizon.cull_leaves,
) != (
st.biome_blend,
st.smooth_lighting,
st.cutout_leaves,
st.cull_leaves,
);
self.streaming.biome_blend = self.settings.biome_blend;
self.streaming.smooth_lighting = self.settings.smooth_lighting;
self.streaming.cutout_leaves = self.settings.cutout_leaves;
self.streaming.cull_leaves = self.settings.horizon.cull_leaves;
if remesh {
self.all_sections_changed();
}
@@ -8416,6 +8357,13 @@ impl Game<'_> {
}
let view = horizon_client::camera::view_matrix(view_yaw, view_pitch);
let at = camera.to_array();
// GameRenderer.renderLevel: the debug crosshair, first person with the HUD shown.
if self.debug_crosshair() && self.camera_type.first_person() && !self.ui.hide_gui {
let mut g = horizon_client::gizmos::Gizmos::default();
let scale = HudBatch::new(size).scale;
g.debug_crosshair(at, view_pitch, view_yaw, scale);
on_top.extend(g.on_top);
}
let debug_lines = horizon_client::gizmos::camera_relative(&lines, at, view);
let debug_lines_on_top = horizon_client::gizmos::camera_relative(&on_top, at, view);
// LevelRenderer.renderHitOutline: the outline shape's edges.
@@ -10054,6 +10002,7 @@ pub fn run() -> Result<()> {
events: Default::default(),
agent: agent::Agent::default(),
view_frustum: None,
entity_culler: None,
pending_uploads: Vec::new(),
frame_graph: Default::default(),
extras: Default::default(),
@@ -10078,10 +10027,10 @@ pub fn run() -> Result<()> {
lan_events: Vec::new(),
lan_block_events: Vec::new(),
lan_entity_events: Vec::new(),
lid_openers: HashMap::new(),
lan_acting: None,
chat_capture: None,
cmds: Default::default(),
cheats: true,
ui: Default::default(),
combat: Default::default(),
mount: Default::default(),
+11 -4
View File
@@ -4,7 +4,7 @@
//! take time run as a task advanced every frame and reply when they finish or
//! time out, so `horizon-ctl break 10 64 3` returns what the block dropped.
use super::{Game, Screen};
use horizon_client::{Result, items::ItemStack, widgets};
use horizon_client::{Result, block_entity_anim::Ticker, items::ItemStack, widgets};
use horizon_core::geometry::Vec3;
use horizon_world::registry::BlockStateId;
use serde_json::{Value, json};
@@ -309,12 +309,19 @@ impl Game<'_> {
}
fn block_json(&self, pos: [i32; 3]) -> Value {
let state = self.world.block(pos[0], pos[1], pos[2]);
json!({
let mut v = json!({
"pos": pos,
"block": &*self.res.facts.get(state).name,
"state": self.state_string(state),
"loaded": self.world.chunks.contains_key(&(pos[0] >> 4, pos[2] >> 4)),
})
});
// How far a chest's or a shulker box's lid is open, 0..1, as drawn.
match self.be_anims.ticker(state.0) {
Some(Ticker::Lid) => v["lid"] = json!(self.chest_lid(pos, 1.0)),
Some(Ticker::Shulker { .. }) => v["lid"] = json!(self.block_anim(pos, 1.0).shulker.0),
_ => {}
}
v
}
pub(super) fn stack_value(&self, s: &ItemStack) -> Value {
let mut v = json!({ "item": &*s.item, "count": s.count });
@@ -1465,7 +1472,7 @@ impl Game<'_> {
self.send_chat(&command);
return ok(json!({ "ok": true }));
}
self.handle_chat_input(&command);
self.as_console(|g| g.handle_chat_input(&command));
ok(json!({ "ok": true, "chat": self.ui.chat.recent_lines(5) }))
}
"respawn" if self.remote.is_none() => {
+17 -10
View File
@@ -7,7 +7,7 @@ use horizon_client::{
entities::ArmorStand,
items::ItemStack,
mesher::Vertex,
mobs::{Part, anim::Poses},
mobs::{Mob, Part, anim::Poses},
};
use horizon_core::{
geometry::{Aabb, Vec3},
@@ -92,21 +92,26 @@ impl Game<'_> {
/// `HumanoidArmorLayer` for the player: (model, texture rect, colour) of
/// each worn piece, head to feet.
pub(super) fn player_armor_layers(&self) -> Vec<(&Part, [f32; 4], u32)> {
self.armor_layers(self.armor.each_ref().map(|s| s.as_ref().map(|s| &*s.item)))
}
/// `HumanoidArmorLayer` for another player's model: the armour it wears
/// (`extra.head` .. `extra.feet`).
pub(super) fn worn_armor_layers(&self, m: &Mob) -> Vec<(&Part, [f32; 4], u32)> {
let e = &m.extra;
self.armor_layers([&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref()))
}
/// The layers of the armour items `worn`, head to feet.
fn armor_layers(&self, worn: [Option<&str>; 4]) -> Vec<(&Part, [f32; 4], u32)> {
let assets = &self.armor_stand_assets;
let mut out = Vec::new();
for (i, layer) in ["helmet", "chestplate", "leggings", "boots"]
for (item, layer) in worn
.into_iter()
.enumerate()
.zip(["helmet", "chestplate", "leggings", "boots"])
{
let Some(stack) = &self.armor[i] else {
let Some(item) = item else {
continue;
};
let Some(asset) = self
.res
.items
.get(&stack.item)
.and_then(|i| i.equip_asset.clone())
else {
let Some(asset) = self.res.items.get(item).and_then(|i| i.equip_asset.clone()) else {
continue;
};
let kind = if layer == "leggings" {
@@ -404,6 +409,7 @@ impl Game<'_> {
return;
};
for a in &self.armor_stands {
let entity_start = out.len();
if a.invisible {
continue;
}
@@ -519,6 +525,7 @@ impl Game<'_> {
out,
);
}
self.cull_entity_vertices(out, entity_start);
}
}
}
@@ -174,6 +174,7 @@ impl Game<'_> {
streaming.biome_blend = self.settings.biome_blend;
streaming.smooth_lighting = self.settings.smooth_lighting;
streaming.cutout_leaves = self.settings.cutout_leaves;
streaming.cull_leaves = self.settings.horizon.cull_leaves;
streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed));
streaming.paused = true;
self.streaming = streaming;
@@ -69,17 +69,19 @@ impl Game<'_> {
/// on both halves of a double chest (`CompoundContainer`).
pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) {
// Spectators never count as openers.
if self.spectator() {
return;
if !self.spectator() {
self.container_openers_changed(key, open);
}
}
/// `container_opener_event` for a player who is not a spectator (a guest).
pub(super) fn container_openers_changed(&mut self, key: (i32, i32, i32), open: bool) {
let pos = [key.0, key.1, key.2];
let state = self.world.block(pos[0], pos[1], pos[2]).0;
match self.be_anims.ticker(state) {
Some(Ticker::Lid) => {
let count = i32::from(open);
self.block_entity_event(pos, 1, count);
self.lid_openers_changed(key, open);
if let Some(other) = self.chest_other_half(key) {
self.block_entity_event([other.0, other.1, other.2], 1, count);
self.lid_openers_changed(other, open);
}
}
Some(Ticker::Shulker { .. }) => {
@@ -90,10 +92,26 @@ impl Game<'_> {
shulker.stop_open()
};
self.block_entity_event(pos, 1, count);
self.lan_block_event(pos, 1, count);
}
_ => {}
}
}
/// `ContainerOpenersCounter.incrementOpeners` / `decrementOpeners` of the
/// chest at `key` (the host and the guests are counted), then
/// `ChestBlockEntity.signalOpenCount`: block event 1 with the count, here
/// and for the guests.
fn lid_openers_changed(&mut self, key: (i32, i32, i32), open: bool) {
let count = self.lid_openers.entry(key).or_default();
*count = (*count + if open { 1 } else { -1 }).max(0);
let count = *count;
if count == 0 {
self.lid_openers.remove(&key);
}
let pos = [key.0, key.1, key.2];
self.block_entity_event(pos, 1, count);
self.lan_block_event(pos, 1, count);
}
/// `BellBlockEntity.updateEntities`: the living entities whose bounding
/// box meets the bell's block box inflated by 48.
fn bell_gather(&self, pos: [i32; 3]) -> Vec<u64> {
@@ -233,7 +251,8 @@ impl Game<'_> {
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
if tick.resonate {
// On a server its own copy does this and sends the sound.
if tick.resonate && self.remote.is_none() {
// The server's copy plays the resonance for everyone.
self.audio
.play("minecraft:block.bell.resonate", Some(centre), 1.0, 1.0);
@@ -249,8 +268,8 @@ impl Game<'_> {
};
self.particles.add(&options, p, [0.0; 3]);
}
// makeRaidersGlow.
for m in self.mobs.iter_mut() {
// makeRaidersGlow (the server's effect).
for m in self.mobs.iter_mut().filter(|_| self.remote.is_none()) {
if glow.contains(&u64::from(m.id)) {
m.add_effect("minecraft:glowing", 60, 0);
}
@@ -292,7 +311,8 @@ impl Game<'_> {
let initial = self.gateway_loaded(pos);
let anims = &mut self.be_anims;
let server = anims.gateway_servers.entry(pos).or_insert(initial);
let triggered = server.portal_tick();
// A server sends its copy's block event instead.
let triggered = self.remote.is_none() && server.portal_tick();
let client = anims.gateways.entry(pos).or_insert(initial);
if triggered {
client.trigger_event(1, 0);
+2
View File
@@ -701,6 +701,7 @@ impl Game<'_> {
pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let a = alpha as f32;
for b in &self.boats {
let entity_start = out.len();
let models = if b.chest {
&self.boat_models.chest_models
} else {
@@ -768,6 +769,7 @@ impl Game<'_> {
0,
out,
);
self.cull_entity_vertices(out, entity_start);
}
}
}
+25 -1
View File
@@ -90,10 +90,28 @@ pub struct UiState {
}
impl Game<'_> {
/// `PlayerList.isOp` for the single-player owner: the world's Allow Commands.
pub(super) fn allow_commands(&self) -> bool {
self.level.allow_commands == Some(true)
}
/// `IntegratedServer.setWorldAllowCommands`, then `updatePermissions`.
pub(super) fn set_allow_commands(&mut self, allow: bool) {
self.level.allow_commands = Some(allow);
self.ui.registries.permission = owner_permission(allow);
}
/// Commands the game issues itself (the server console, harnesses, the
/// control socket) run at the owner's level whatever Allow Commands says.
pub(super) fn as_console<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
let level = std::mem::replace(&mut self.ui.registries.permission, 4);
let out = f(self);
self.ui.registries.permission = level;
out
}
/// Registry contents for argument parsing (built when a world opens).
pub(super) fn build_registries(&mut self) {
let permission = owner_permission(self.allow_commands());
let reg = &mut self.ui.registries;
reg.permission = 4;
reg.permission = permission;
{
let dir = |sub: &str| -> Vec<String> {
let root = self.options.resources.join("data/minecraft").join(sub);
@@ -869,3 +887,9 @@ fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client::
std::fs::write(&path, Compression::Gzip.encode(&out)?)?;
Ok(())
}
/// `IntegratedServer.getProfilePermissions` for the owner: `OWNER` (4) when
/// commands are allowed, else `ALL` (0).
fn owner_permission(allow_commands: bool) -> u8 {
if allow_commands { 4 } else { 0 }
}
@@ -89,7 +89,9 @@ impl Game<'_> {
let command = op["cmd"].as_str().unwrap_or("");
self.chat_capture = Some(Vec::new());
self.cmds.results = Some(Vec::new());
self.run_command(command.strip_prefix('/').unwrap_or(command));
self.as_console(|g| {
g.run_command(command.strip_prefix('/').unwrap_or(command))
});
let messages = self.chat_capture.take().unwrap_or_default();
let results = self.cmds.results.take().unwrap_or_default();
if op["record"].as_bool() != Some(false) {
@@ -713,6 +713,10 @@ impl Game<'_> {
})),
"uptime_seconds": self.started.elapsed().as_secs_f64(),
"server": self.remote_status(),
// The names the name tags show now, seen from the eyes.
"name_tags": self
.eye_position()
.map(|e| self.shown_name_tags(glam::DVec3::from_array(e))),
});
status["physical_keys"] = json!(physical_keys);
status
+14 -1
View File
@@ -2701,6 +2701,7 @@ impl Game<'_> {
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let scale = f64::from(self.settings.entity_distance);
for mob in &self.mobs {
let entity_start = out.len();
let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera;
// Entity.shouldRenderAtSqrDistance: 64 times the bounding box's
// mean edge, scaled by the entity distance option.
@@ -2731,16 +2732,28 @@ impl Game<'_> {
if mob.fire_ticks > 0 || matches!(mob.species(), Species::Blaze | Species::MagmaCube) {
packed = (15 * 16) | ((15 * 16) << 8);
}
horizon_client::mobs::render::render(
// Other players on a server: PlayerRenderer's HumanoidArmorLayer.
let armor = if &*mob.kind.id == "minecraft:player" {
self.worn_armor_layers(mob)
} else {
Vec::new()
};
horizon_client::mobs::render::render_with(
mob,
alpha as f32,
camera,
&lookup,
packed,
&self.res.mob_data,
&armor,
out,
);
self.mob_block_geometry(mob, camera, alpha, packed, out);
// Glowing outlines and a guardian's beam remain visible independently
// of whether the body is hidden behind terrain.
if !mob.glowing && horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none() {
self.cull_entity_vertices(out, entity_start);
}
// GuardianRenderer: the laser to the locked target.
if let Some((time, scale)) = horizon_client::mobs::guardian::beam(mob, alpha as f32)
&& let Some(target) = self.beam_target(mob.ai.target, alpha)
+202 -1
View File
@@ -6,8 +6,11 @@ use horizon_client::{
Result,
command::args::GameMode,
debug_keys::{CrashNotice, DebugAction, DebugHost, KeyAction, OpenScreen},
debug_overlay,
gizmos::Gizmos,
keybinds,
hud::HudBatch,
hud_layout, keybinds,
save::VERSION_NAME,
text::Text,
};
use horizon_core::geometry::Axis;
@@ -253,6 +256,199 @@ impl Game<'_> {
format!("To edit: press {}", key("key.debug.debugOptions")),
]
}
/// `DebugScreenOverlay.extractRenderState` with the default profile's
/// entries, over everything the frame drew (menus too), at the debug GUI
/// scale. F1 hides it unless a screen is open.
pub(super) fn draw_debug_overlay(&self, batch: &mut HudBatch, size: [u32; 2]) {
let screen_open = self.title.is_some() || self.screen != Screen::Playing;
if !self.debug || (self.ui.hide_gui && !screen_open) {
return;
}
let framebuffer = size.map(|v| v as i32);
let (scale, [width, height]) = debug_overlay::scale(
framebuffer,
batch.scale as i32,
self.settings.file.int("debugGuiScale"),
self.settings.force_unicode,
[batch.width as i32, batch.height as i32],
);
let mut d = debug_overlay::Displayer::default();
// fps: DebugEntryFps.
let limit = self.framerate_limit();
let present = self
.renderer
.as_ref()
.map_or("", |r| match r.config.present_mode {
wgpu::PresentMode::Immediate => " (immediate)",
wgpu::PresentMode::Mailbox => " (mailbox)",
wgpu::PresentMode::Fifo => " (fifo)",
wgpu::PresentMode::FifoRelaxed => " (fifo relaxed)",
_ => "",
});
let refresh = self
.window
.as_ref()
.and_then(|w| w.current_monitor())
.and_then(|m| m.refresh_rate_millihertz())
.map_or("0".into(), |mhz| {
debug_overlay::refresh_rate_label(f64::from(mhz) / 1000.0)
});
d.priority(format!(
"{} fps T: {}{present} @{refresh}Hz",
self.fps.round() as i32,
if limit == 260 {
"inf".into()
} else {
limit.to_string()
},
));
// game_version: DebugEntryVersion (the launched version and brand).
d.priority(format!("Minecraft {VERSION_NAME} ({VERSION_NAME}/horizon)"));
// player_position, player_section_position.
if let Some(p) = self.player.as_ref() {
let mut lines = debug_overlay::position(
[p.position.x, p.position.y, p.position.z],
self.yaw,
self.pitch,
self.dim.id(),
self.streaming.forced.len(),
);
let section = lines.pop().unwrap_or_default();
if !self.reduced_debug_info() {
d.group("position", lines);
}
d.group("position", [section]);
}
// simple_performance_impactors.
let s = &self.settings;
d.line(format!(
"{}{}B: {}",
if s.improved_transparency {
"improved-transparency "
} else {
""
},
match s.clouds.as_str() {
"false" => "",
"fast" => "fast-clouds ",
_ => "fancy-clouds ",
},
s.biome_blend
));
d.line("Filtering: None");
d.line(format!(
"Terrain Rendering: {}",
if self.renderer.as_ref().is_some_and(|r| r.multi_draw) {
"multidrawindirect"
} else {
"naive"
}
));
// system_specs (no Java line: Horizon has no JVM).
if let Some(r) = self.renderer.as_ref() {
static CPU: std::sync::OnceLock<String> = std::sync::OnceLock::new();
d.group(
"system",
[format!(
"CPU: {}",
CPU.get_or_init(horizon_client::crash::cpu)
)],
);
let info = &r.info;
d.group(
"system",
[format!(
"Display: {}x{} ({})",
framebuffer[0],
framebuffer[1],
// Metal adapters report no PCI vendor.
if info.vendor == 0 && info.backend == wgpu::Backend::Metal {
"Apple".into()
} else {
debug_overlay::vendor_name(info.vendor)
}
)],
);
if let Some(w) = self.window.as_ref() {
let density = w.scale_factor();
let logical = w.inner_size().to_logical::<f64>(density);
d.group(
"system",
[format!(
"Window: {}x{} ({density:.2}x pixel density)",
logical.width.round() as i32,
logical.height.round() as i32
)],
);
}
let kind = match info.device_type {
wgpu::DeviceType::IntegratedGpu => " (iGPU)",
wgpu::DeviceType::DiscreteGpu => " (dGPU)",
wgpu::DeviceType::VirtualGpu => " (vGPU)",
wgpu::DeviceType::Cpu => " (software)",
wgpu::DeviceType::Other => "",
};
let driver = format!("{} {}", info.driver, info.driver_info);
d.group(
"system",
[
format!("{}{kind}", info.name),
format!(
"{:?} {}",
info.backend,
driver.trim().lines().next().unwrap_or("")
)
.trim_end()
.to_owned(),
],
);
}
// tps: DebugEntryTps for the integrated server (it counts no packets).
if self.player.is_some() && self.remote.is_none() {
let (target, status) = if self.clock.sprinting() {
("-".to_owned(), " (sprinting)")
} else if self.clock.stepping() {
(
format!("{:.1}", 1000.0 / self.clock.rate()),
" (frozen - stepping)",
)
} else if self.clock.frozen() {
(format!("{:.1}", 1000.0 / self.clock.rate()), " (frozen)")
} else {
(format!("{:.1}", 1000.0 / self.clock.rate()), "")
};
d.line(format!(
"Integrated server @ {:.1}/{target} ms{status}, 0 tx, 0 rx",
self.debug_charts.smoothed_tick_ms
));
}
let (left, right) = d.columns(&self.debug_chart_lines());
let atlas = &self.res.atlas;
let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width);
let charts = self.debug_charts.draw(
&atlas.font,
width,
height,
self.settings.max_fps,
1000.0 / self.clock.rate(),
self.remote.is_some(),
);
draws.push(hud_layout::GuiDraw::Push(vec![hud_layout::PoseOp::Scale(
scale, scale,
)]));
draws.extend(charts);
if self.debug_charts.lightmap
&& let Some(r) = &self.renderer
{
draws.extend(horizon_client::debug_chart::lightmap(
&r.lightmap_pixels,
width,
height,
));
}
draws.push(hud_layout::GuiDraw::Pop);
hud_layout::paint(batch, atlas, &draws);
}
/// `KeyMapping.getTranslatedKeyMessage`.
fn key_text(&self, mapping: &str) -> Text {
keybinds::display_name(self.settings.keys.get(mapping))
@@ -283,6 +479,11 @@ impl Game<'_> {
fn reduced_debug_info(&self) -> bool {
self.settings.reduced_debug_info || self.ui.rules.bool("reduced_debug_info")
}
/// The default profile's `3d_crosshair` entry: on while the overlay is
/// open, unless debug info is reduced.
pub(super) fn debug_crosshair(&self) -> bool {
self.debug && !self.reduced_debug_info()
}
/// `Permissions.COMMANDS_GAMEMASTER` (`GameModeCommand.PERMISSION_CHECK`).
pub(super) fn gamemaster(&self) -> bool {
self.ui.registries.permission >= 2
+1 -1
View File
@@ -915,7 +915,7 @@ impl Game<'_> {
_ => {
// The game's dispatcher, captured for the console.
self.chat_capture = Some(Vec::new());
self.run_command(line);
self.as_console(|g| g.run_command(line));
for text in self.chat_capture.take().unwrap_or_default() {
self.console_reply(text);
}
@@ -0,0 +1,51 @@
//! Entity occlusion affects mesh submission, never entity ticking or interaction.
use super::{Game, Vertex};
use horizon_client::chunk::MIN_Y;
use horizon_client::{
blocks::{RenderShape, StateFacts},
entity_culling::Culler,
};
fn opaque(facts: &StateFacts) -> bool {
facts.render_shape == RenderShape::Model
&& facts.can_occlude
&& facts.solid_render
&& facts.full_collision
}
impl Game<'_> {
pub(super) fn prepare_entity_culling(&mut self, camera: glam::DVec3) {
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.
&& self.settings.resource_packs.iter().all(|id| id == "vanilla")
&& self.player.is_some()
&& !self.spectator()
&& !opaque(self.res.facts.get(self.world.block(at[0], at[1], at[2]))))
.then(|| Culler::new(camera.to_array(), 8_192));
}
/// 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(&section)
&& !self.streaming.is_meshing(section)
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
});
}
}
}
+6
View File
@@ -305,6 +305,7 @@ impl Game<'_> {
let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new();
let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new();
for f in &self.item_frames {
let entity_start = out.len();
let map = f.item.as_ref().and_then(super::maps::map_id);
let s = f.step();
// Pose: to the block centre, then X/Y rotation by facing.
@@ -371,6 +372,7 @@ impl Game<'_> {
);
}
}
self.cull_entity_vertices(out, entity_start);
if let Some(id) = map {
// ItemFrameRenderer: the map fills the face, in 90-degree steps.
let depth = if f.invisible { 0.5 } else { 0.4375 };
@@ -400,6 +402,7 @@ impl Game<'_> {
}
// `extractRenderState`: FIXED, seeded by the frame entity.
for (stack, id, m, light) in items {
let entity_start = out.len();
let owner = super::item_draw::owner_at([0.0; 3], 0.0, "minecraft:item_frame");
let state = self.resolve_item(
&stack,
@@ -413,9 +416,12 @@ impl Game<'_> {
horizon_client::block_entity_render::vertex_light(light),
out,
);
self.cull_entity_vertices(out, entity_start);
}
for (id, m, light) in maps {
let entity_start = out.len();
self.map_vertices(id, m, light, out);
self.cull_entity_vertices(out, entity_start);
}
}
}
@@ -330,6 +330,7 @@ impl Game<'_> {
_ => None,
});
for (item, at, partial) in live.chain(taken) {
let entity_start = out.len();
let q = item.position;
let pos = glam::DVec3::from_array(at) - camera;
if pos.length_squared() > 64.0 * 64.0 {
@@ -369,6 +370,7 @@ impl Game<'_> {
) {
self.submit_item_world(&state, copy, vertex_light(packed), out);
}
self.cull_entity_vertices(out, entity_start);
}
}
}
+34 -7
View File
@@ -2,7 +2,7 @@
//! server threads and the play-state hub, feeds it the world's entities each
//! tick and turns what the guests do into gameplay. A world that is not open
//! costs one `Option` check per tick.
use super::{Game, chat::PLAYER_NAME};
use super::Game;
use horizon_client::{
Result,
items::ItemStack,
@@ -43,6 +43,8 @@ pub(super) struct LanHost {
pub settings: LanSettings,
pub host_entity: i32,
pub host_uuid: u128,
/// The host's profile name (the account's, or the offline name).
pub host_name: String,
/// The guests' models in the host's world.
pub models: HashMap<u32, Mob>,
host_mode: i32,
@@ -325,6 +327,7 @@ impl Game<'_> {
Some("status") => Ok(Some(match &self.lan {
Some(h) => json!({
"open": true,
"host": h.host_name,
"port": h.settings.port,
"guests": h.hub.guests.iter().map(|g| json!({
"name": g.name,
@@ -334,6 +337,11 @@ impl Game<'_> {
"game_mode": g.game_mode,
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
// The armour the host draws on this guest, head to feet.
"model_armor": h.models.get(&g.conn).map(|m| {
[&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet]
.map(|s| s.as_deref())
}),
})).collect::<Vec<_>>(),
}),
None => json!({ "open": false }),
@@ -356,9 +364,11 @@ impl Game<'_> {
if self.lan.is_some() || self.remote.is_some() || self.title.is_some() {
return Err("already open".into());
}
let motd = format!("{PLAYER_NAME} - {}", self.level.name);
// IntegratedServer.publishServer: the MOTD names the host's profile.
let name = self.options.player_name();
let motd = format!("{name} - {}", self.level.name);
let host_uuid = self.level.player_uuid.map_or_else(
|| offline_uuid(PLAYER_NAME),
|| offline_uuid(&name),
|u| {
u128::from(u[0] as u32) << 96
| u128::from(u[1] as u32) << 64
@@ -438,6 +448,7 @@ impl Game<'_> {
settings: LanSettings { port, ..settings },
host_entity,
host_uuid,
host_name: self.options.player_name(),
models: HashMap::new(),
host_mode: self.mode_id(),
play: HashMap::new(),
@@ -509,7 +520,7 @@ impl Game<'_> {
equipment[5] = self.armor[0].clone();
Some(HostState {
uuid: host.host_uuid,
name: PLAYER_NAME.to_owned(),
name: host.host_name.clone(),
entity_id: host.host_entity,
position: [p.position.x, p.position.y, p.position.z],
yaw: self.yaw,
@@ -634,7 +645,14 @@ impl Game<'_> {
);
}
}
HostEvent::Left(guest) => {
HostEvent::Left(mut guest) => {
// The container they had open loses an opener.
if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos)
&& !guest.spectator()
{
self.container_openers_changed(pos, false);
}
self.lan_crafting_left(&mut host, &mut guest);
playerdata::save(&guest, &self.world_root);
host.models.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
@@ -839,6 +857,10 @@ impl Game<'_> {
.and_then(|s| s.as_ref())
.map(|s| s.item.clone());
m.extra.off_hand = g.offhand.as_ref().map(|s| s.item.clone());
[m.extra.head, m.extra.chest, m.extra.legs, m.extra.feet] = g
.armor
.each_ref()
.map(|s| s.as_ref().map(|s| s.item.clone()));
m.extra.crouching = g.sneaking;
}
}
@@ -856,6 +878,7 @@ impl Game<'_> {
let atlas = &self.res.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
for m in host.models.values() {
let entity_start = out.len();
let light = self.world.light(
m.position.x.floor() as i32,
(m.position.y + 1.62).floor() as i32,
@@ -869,16 +892,20 @@ impl Game<'_> {
&lookup,
packed,
&self.res.mob_data,
&self.player_armor_layers(),
&self.worn_armor_layers(m),
out,
);
self.held_item_geometry(m, camera, alpha, packed, true, out);
if !m.glowing {
self.cull_entity_vertices(out, entity_start);
}
}
}
/// A chat line the host typed, for the guests.
pub(super) fn lan_host_chat(&mut self, message: &str) {
if let Some(host) = &self.lan {
host.hub.chat(PLAYER_NAME, message);
host.hub.chat(&host.host_name, message);
}
}
}
+106 -11
View File
@@ -12,13 +12,14 @@ use horizon_client::{
entities::Experience,
items::ItemStack,
lan::{guest::SPECTATOR, menu::Rules},
motion::PlayerMotion,
motion::{MotionWorld, PlayerMotion},
};
use horizon_core::geometry::Vec3;
use horizon_protocol::{
packets::play::{self, Clientbound as C, Serverbound as S},
text::literal,
};
use horizon_world::entity_move::EntityMoveWorld;
use winit::keyboard::KeyCode;
/// Per-guest state of the gameplay code that lives outside `Guest`.
@@ -37,6 +38,8 @@ pub(super) struct GuestPlay {
swung: bool,
/// The trading screen the guest has open.
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
/// The inventory menu and the crafting table the guest crafts in.
pub(super) crafting: super::lan_crafting::GuestCrafting,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -126,6 +129,10 @@ impl Game<'_> {
self.keys.remove(&KeyCode::ShiftLeft);
}
let screen = std::mem::replace(&mut self.screen, Screen::Playing);
// The host's crafting grid stays theirs; a crafting table the guest
// opens shows as the 3x3 size.
let craft_size = std::mem::replace(&mut self.craft_size, 2);
let craft_grid = std::mem::replace(&mut self.craft_grid, vec![None; 9]);
let container = self.container.take();
let mining = std::mem::replace(&mut self.mining, play.mining.take());
let destroy_delay = std::mem::replace(&mut self.destroy_delay, play.destroy_delay);
@@ -145,6 +152,8 @@ impl Game<'_> {
// What the action opened: handed to the guest instead of the host.
let opened = self.container.take();
let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3;
self.craft_grid = craft_grid;
let opened_station = std::mem::replace(&mut self.station, host_station);
self.riding = riding;
self.left = left;
@@ -200,12 +209,19 @@ impl Game<'_> {
host.hub.set_game_mode(conn, new_mode);
}
host.play.insert(conn, play);
if let Some(pos) = opened {
self.lan_open_container(host, conn, pos);
if let Some(pos) = opened
&& !self.lan_open_container(host, conn, pos)
&& !host.hub.guests[i].spectator()
{
// Nothing the guest can use opened: its lid closes again.
self.container_openers_changed(pos, false);
}
if let Some(station) = opened_station {
self.lan_station_opened(host, conn, station);
}
if opened_table {
self.lan_open_crafting(host, conn);
}
Some(result)
}
@@ -221,19 +237,20 @@ impl Game<'_> {
self.creative = self.mode == GameMode::Creative;
}
/// Hand a container the guest opened over (ServerPlayer.openMenu).
fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) {
/// Hand a container the guest opened over (ServerPlayer.openMenu);
/// false when it is not one a guest can open.
fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) -> bool {
let Some(entity) = self.world.block_entities.get(&pos) else {
return;
return false;
};
let (menu, title) = match entity {
BlockEntity::Chest(items) => match items.len() {
27 => ("minecraft:generic_9x3", "container.chest"),
9 => ("minecraft:generic_3x3", "container.dispenser"),
5 => ("minecraft:hopper", "container.hopper"),
_ => return,
_ => return false,
},
_ => return,
_ => return false,
};
let name = &self
.res
@@ -247,6 +264,8 @@ impl Game<'_> {
_ => title,
};
let items = entity.slots().to_vec();
// ServerPlayer.openMenu closes the menu that was open.
self.guest_container_closed(host, conn);
host.hub.open_container(
conn,
menu,
@@ -254,6 +273,18 @@ impl Game<'_> {
pos,
items,
);
true
}
/// The guest's open container is closing (`AbstractContainerMenu.removed`):
/// it no longer counts among the openers of the lid.
pub(super) fn guest_container_closed(&mut self, host: &mut LanHost, conn: u32) {
if let Some(g) = host.hub.guest(conn)
&& let Some(pos) = g.menu.as_ref().and_then(|m| m.pos)
&& !g.spectator()
{
self.container_openers_changed(pos, false);
}
}
/// A packet from a guest that the hub does not handle itself.
@@ -392,6 +423,8 @@ impl Game<'_> {
host.hub.guests[gi].set_menu_slot(p.slot as usize, item);
}
S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {}
S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item),
S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => {
let g = &mut host.hub.guests[gi];
@@ -399,12 +432,25 @@ impl Game<'_> {
self.drop_guest_items(host, gi, vec![c]);
}
}
S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => {
let g = &mut host.hub.guests[gi];
if let Some(c) = g.carried.take() {
self.drop_guest_items(host, gi, vec![c]);
}
}
S::ContainerClick(p) => {
let rules = ItemRules(&self.res.items);
let drops = host.hub.container_click(conn, p, &mut self.world, &rules);
let drops = host.hub.container_click(conn, &p, &mut self.world, &rules);
self.drop_guest_items(host, gi, drops);
}
S::ContainerClose(p) => {
if host.hub.guests[gi]
.menu
.as_ref()
.is_some_and(|m| m.window == p.container)
{
self.guest_container_closed(host, conn);
}
host.hub.container_closed(conn, p.container);
let g = &mut host.hub.guests[gi];
if let Some(c) = g.carried.take() {
@@ -553,7 +599,7 @@ impl Game<'_> {
let words: Vec<&str> = command.trim_start_matches('/').split(' ').collect();
if words[0] == "list" && (words.len() == 1 || words[1..] == ["uuids"]) {
let me = (self.options.dedicated.is_none() && self.player.is_some())
.then_some((host.host_uuid, super::chat::PLAYER_NAME));
.then_some((host.host_uuid, host.host_name.as_str()));
let content = host.hub.list_reply(me, words.len() == 2);
host.hub.send_to(
conn,
@@ -564,7 +610,10 @@ impl Game<'_> {
);
return;
}
if !host.settings.guest_commands || !self.cheats {
// A LAN world follows its Allow Commands; a dedicated server leaves
// it to the ops list (the guest's permission level).
let allowed = self.options.dedicated.is_some() || self.allow_commands();
if !host.settings.guest_commands || !allowed {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
@@ -698,6 +747,7 @@ impl Game<'_> {
}
});
}
self.guest_server_tick(host, conn);
self.guest_dig_feedback(host, conn);
self.guest_pickups(host, gi);
let g = &mut host.hub.guests[gi];
@@ -715,6 +765,51 @@ impl Game<'_> {
}
}
/// The guest's body on the server each tick: ServerPlayer.tick's damage
/// clock and Entity.baseTick's fluid phase, then
/// ServerPlayer.doCheckFallDamage for each move the guest made (the fall
/// distance grows while they go down and hurts them where they land, as
/// the host's own landing does; water resets it, lava halves it), then
/// regeneration and the food tick (ServerPlayer.doTick).
fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) {
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
let moves = std::mem::take(&mut g.moves);
if g.spectator() {
return;
}
self.as_guest(host, conn, |game| {
let (rules, health) = (game.world.health_rules, &game.motion.health);
let Some(player) = game.player.as_mut() else {
return;
};
let mut w = MotionWorld {
player,
scene: &mut game.world,
assets: &game.res.assets,
collision_binding: game.collision,
resources: game.motion,
};
w.player.health.advance_clock();
let _ = w.fluid_base_tick();
for (moved, on_ground) in moves {
let movement = Vec3::new(moved[0], moved[1], moved[2]);
let landed = (|| -> horizon_client::Result<()> {
w.set_on_ground_with_movement(on_ground, false, movement)?;
let pos = w.legacy_on_position()?;
let state = w.block_state(pos)?;
w.check_fall_damage(moved[1], on_ground, state, pos)
})();
if landed.is_err() {
break;
}
}
let _ = w.player.peaceful_regeneration(rules);
let _ = w.player.food_tick(health, rules);
});
}
/// The crack animation other players see.
fn guest_dig_feedback(&mut self, host: &mut LanHost, conn: u32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
@@ -0,0 +1,287 @@
//! Crafting for LAN guests: the inventory's 2x2 grid (window 0) and the
//! crafting table (`minecraft:crafting`) run the host's menu engine
//! (`horizon_client::menu`, `Kind::Inventory` / `Kind::Crafting`) over the
//! guest's inventory, with vanilla's packets: OpenScreen, container clicks
//! and their corrections, and the grid back into the inventory when the menu
//! closes (`AbstractContainerMenu.clearContainer`).
use super::{Game, lan::LanHost};
use horizon_client::{
items::ItemStack,
lan::guest::Guest,
menu::{Env, Input, Kind, Menu},
};
use horizon_protocol::packets::play::{self, Clientbound as C};
/// The guest's menus the game runs: kept between clicks, so a drag (quick
/// craft) spans them as in vanilla.
#[derive(Default)]
pub(super) struct GuestCrafting {
/// The inventory menu; its grid lives in the hub's guest.
inventory: Option<Box<Menu>>,
/// The open crafting table: its window, state id and menu.
table: Option<(i32, i32, Box<Menu>)>,
}
/// ServerboundContainerClickPacket's input.
pub(super) fn input(id: i32) -> Input {
match id {
0 => Input::Pickup,
1 => Input::QuickMove,
2 => Input::Swap,
3 => Input::Clone,
4 => Input::Throw,
5 => Input::QuickCraft,
_ => Input::PickupAll,
}
}
/// The armor's player-container slots, head to feet (`Inventory` 39..36).
const ARMOR: [usize; 4] = [39, 38, 37, 36];
const OFFHAND: usize = 40;
/// The guest's inventory, armor, off hand, selection and carried stack into `menu`.
fn load_player(menu: &mut Menu, g: &Guest) {
for i in 0..36 {
menu.set_player_item(i, g.inventory[i].clone());
}
for (k, slot) in ARMOR.into_iter().enumerate() {
menu.set_player_item(slot, g.armor[k].clone());
}
menu.set_player_item(OFFHAND, g.offhand.clone());
menu.selected = g.selected;
menu.creative = g.creative();
menu.carried = g.carried.clone();
}
/// `load_player` back.
fn store_player(menu: &mut Menu, g: &mut Guest) {
for i in 0..36 {
g.inventory[i] = menu.player_item(i).cloned();
}
for (k, slot) in ARMOR.into_iter().enumerate() {
g.armor[k] = menu.player_item(slot).cloned();
}
g.offhand = menu.player_item(OFFHAND).cloned();
g.carried = menu.carried.take();
}
/// Inventory.placeItemBackInInventory for each stack: what doesn't fit is
/// left for Player.drop (creative players keep it too).
fn place_back(menu: &mut Menu, env: &Env, stacks: Vec<ItemStack>) {
menu.creative = false;
for mut stack in stacks {
menu.give(env, &mut stack);
if stack.count > 0 {
menu.dropped.push(stack);
}
}
}
impl Game<'_> {
fn menu_env(&self) -> Env<'_> {
Env {
items: &self.res.items,
recipes: &self.res.recipes,
brewing: &self.res.stations.brewing,
banners: &self.res.stations.banners,
trade: None,
}
}
/// Runs `op` on the guest's menu with their inventory copied in and back.
fn guest_menu_op<R>(
&mut self,
host: &mut LanHost,
gi: usize,
menu: &mut Menu,
op: impl FnOnce(&mut Menu, &Env) -> R,
) -> R {
let env = self.menu_env();
load_player(menu, &host.hub.guests[gi]);
let result = op(menu, &env);
let dropped = std::mem::take(&mut menu.dropped);
menu.drops.clear();
menu.crafted.clear();
store_player(menu, &mut host.hub.guests[gi]);
self.drop_guest_items(host, gi, dropped);
result
}
/// A click on the guest's inventory menu (window 0): `InventoryMenu`,
/// crafting grid included. False for other windows.
pub(super) fn lan_inventory_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
if p.container != 0 {
return false;
}
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return true;
};
if host.hub.guests[gi].spectator() {
return true;
}
let crafting = host.play.entry(conn).or_default();
let mut menu = crafting
.crafting
.inventory
.take()
.unwrap_or_else(|| Box::new(Menu::new(Kind::Inventory)));
let grid = host.hub.guests[gi].craft_grid.clone();
let changed = self.guest_menu_op(host, gi, &mut menu, |menu, env| {
for (k, s) in grid.into_iter().enumerate() {
menu.set_slot(env, 1 + k, s);
}
let before: Vec<_> = (0..menu.slot_count())
.map(|s| menu.slot(s).cloned())
.collect();
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
(0..menu.slot_count())
.filter(|&s| menu.slot(s) != before[s].as_ref())
.collect::<Vec<_>>()
});
let g = &mut host.hub.guests[gi];
for k in 0..4 {
g.craft_grid[k] = menu.slot(1 + k).cloned();
}
g.craft_result = menu.slot(0).cloned();
host.play.entry(conn).or_default().crafting.inventory = Some(menu);
host.hub.inventory_clicked(conn, p, &self.world, &changed);
true
}
/// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`).
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) {
self.lan_crafting_closed(host, conn, None);
// The container it replaces loses its opener.
self.guest_container_closed(host, conn);
let title = horizon_protocol::text::translatable("container.crafting", &[]);
let Some(window) = host.hub.open_window(conn, "minecraft:crafting", title) else {
return;
};
let menu = Box::new(Menu::new(Kind::Crafting));
host.play.entry(conn).or_default().crafting.table = Some((window, 0, menu));
self.lan_send_table_content(host, conn);
}
/// A click on the guest's crafting table window; false for other windows.
pub(super) fn lan_crafting_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
let Some(play) = host.play.get_mut(&conn) else {
return false;
};
let Some((window, state, mut menu)) = play
.crafting
.table
.take_if(|(window, _, _)| *window == p.container)
else {
return false;
};
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& !host.hub.guests[gi].spectator()
{
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
});
}
host.play.entry(conn).or_default().crafting.table = Some((window, state, menu));
self.lan_send_table_content(host, conn);
true
}
/// The whole crafting table menu for the client (`sendAllDataToRemote`).
fn lan_send_table_content(&mut self, host: &mut LanHost, conn: u32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let Some((window, state, menu)) = host
.play
.get_mut(&conn)
.and_then(|p| p.crafting.table.as_mut())
else {
return;
};
*state = (*state + 1) & 0x7FFF;
let (window, state) = (*window, *state);
let mut items: Vec<Option<ItemStack>> = (0..10).map(|s| menu.slot(s).cloned()).collect();
let g = &host.hub.guests[gi];
items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone()));
let carried = g.carried.clone();
let items = items.iter().map(|s| host.hub.stack(s)).collect();
let carried = host.hub.stack(&carried);
host.hub.send_to(
conn,
&C::ContainerSetContent(play::ContainerSetContent {
container: window,
state,
items,
carried,
}),
);
}
/// `AbstractContainerMenu.removed` of a crafting menu: the closed window
/// (`window`; None closes the table whichever it is, and 0 the inventory
/// menu) gives its grid back to the inventory, what doesn't fit is
/// dropped. False when no such window is open.
pub(super) fn lan_crafting_closed(
&mut self,
host: &mut LanHost,
conn: u32,
window: Option<i32>,
) -> bool {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return false;
};
let crafting = &mut host.play.entry(conn).or_default().crafting;
let grid: Vec<ItemStack> = if window == Some(0) {
crafting.inventory = None;
let g = &mut host.hub.guests[gi];
g.craft_result = None;
g.craft_grid.iter_mut().filter_map(Option::take).collect()
} else {
match crafting
.table
.take_if(|(w, _, _)| window.is_none_or(|window| *w == window))
{
Some((_, _, menu)) => (1..10).filter_map(|s| menu.slot(s).cloned()).collect(),
None => return false,
}
};
if grid.is_empty() {
return true;
}
let mut menu = Menu::new(Kind::Inventory);
self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid));
true
}
/// A guest left: what their crafting grids held goes back into their
/// inventory before it is saved (dropped where they stood if full).
pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) {
let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table);
let mut grid: Vec<ItemStack> = g.craft_grid.iter_mut().filter_map(Option::take).collect();
g.craft_result = None;
if let Some((_, _, menu)) = table {
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
}
if grid.is_empty() {
return;
}
let mut menu = Menu::new(Kind::Inventory);
load_player(&mut menu, g);
place_back(&mut menu, &self.menu_env(), grid);
let dropped = std::mem::take(&mut menu.dropped);
store_player(&mut menu, g);
for stack in dropped {
self.spawn_item(stack, g.position, [0.0, 0.1, 0.0], 40);
}
}
}
+5 -3
View File
@@ -170,7 +170,7 @@ impl Game<'_> {
let mut options = WorldOptions {
default_mode: self.level.mode(),
personal_mode: self.mode_id(),
cheats: self.cheats,
cheats: self.allow_commands(),
difficulty: self.ui.difficulty,
lan,
port,
@@ -360,7 +360,7 @@ impl Game<'_> {
fn apply_world_options(&mut self, before: &Snapshot, wanted: &Snapshot) {
if wanted.difficulty != before.difficulty {
let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3];
self.run_command(&format!("difficulty {name}"));
self.as_console(|g| g.run_command(&format!("difficulty {name}")));
}
if wanted.default_mode != before.default_mode {
self.set_default_game_mode(wanted.default_mode);
@@ -368,7 +368,9 @@ impl Game<'_> {
if wanted.personal_mode != before.personal_mode {
self.set_mode_id(wanted.personal_mode);
}
self.cheats = wanted.cheats;
if wanted.cheats != before.cheats {
self.set_allow_commands(wanted.cheats);
}
let settings_changed =
wanted.guest_commands != before.guest_commands || wanted.force != before.force;
if wanted.lan != before.lan || (wanted.lan && wanted.port != before.port) {
@@ -55,6 +55,8 @@ impl Game<'_> {
state.session.update_special_prices();
}
let title = self.merchant_display_name(&state);
// The container the trading screen replaces loses its opener.
self.guest_container_closed(host, conn);
let Some(window) = host.hub.open_merchant_window(conn, title) else {
self.merchant_closed(&mut state);
return;
@@ -1213,6 +1213,7 @@ impl Game<'_> {
pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let a = alpha as f32;
for c in &self.carts {
let entity_start = out.len();
let Some(model) = self.cart_models.models.get(&c.kind) else {
continue;
};
@@ -1309,6 +1310,7 @@ impl Game<'_> {
let m = base * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0));
let poses = Poses::new(model);
horizon_client::mobs::render::draw(model, m, &poses, uv, 0xFFFF_FFFF, packed, 0, out);
self.cull_entity_vertices(out, entity_start);
}
}
/// The chest inside a chest minecart, drawn by the chest block-entity renderer.
+87 -26
View File
@@ -3,9 +3,10 @@
//! on a translucent black background, shown when the name is visible or the
//! mob is under the crosshair within 64 blocks, as its team's name tag
//! visibility allows, in the team's colours, with its score in the
//! objective displayed below names.
//! objective displayed below names. Other players' names (on a LAN host
//! or a server) show whenever `LivingEntityRenderer.shouldShowName` allows.
use super::{Game, view_vector};
use horizon_client::{mesher::Vertex, save::uuid_text, scoreboard as sb, text::Text};
use horizon_client::{mesher::Vertex, mobs::Mob, save::uuid_text, scoreboard as sb, text::Text};
impl Game<'_> {
/// A named name tag names the mob under the crosshair.
@@ -28,13 +29,12 @@ impl Game<'_> {
self.swing_arm();
true
}
/// `Entity.belowNameDisplay`: the mob's score in the objective shown below
/// names, then a space and the objective's name.
fn below_name_text(&self, id: u32) -> Option<Text> {
/// `Entity.belowNameDisplay`: the score holder's score in the objective
/// shown below names, then a space and the objective's name.
fn below_name_text(&self, holder: &str) -> Option<Text> {
let board = &self.score.board;
let objective = board.display_objective(sb::SLOT_BELOW_NAME)?;
let uuid = self.persist.uuids.get(&id)?;
let score = board.score(&uuid_text(*uuid), &objective.name)?;
let score = board.score(holder, &objective.name)?;
// numberFormatOrDefault(StyledFormat.NO_STYLE).
let format = score
.number_format
@@ -47,23 +47,60 @@ impl Game<'_> {
t.push(objective.display_text());
Some(t)
}
pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
/// The other players' models and names: the guests on a LAN host, the
/// players a server sends on a client.
fn other_players(&self) -> Vec<(&Mob, String)> {
let mut out = Vec::new();
if let Some(host) = &self.lan {
for (conn, m) in &host.models {
if let Some(g) = host.hub.guest(*conn) {
out.push((m, g.name.clone()));
}
}
}
for (id, name) in self.remote_player_names() {
if let Some(m) = self.mobs.iter().find(|m| m.id == id) {
out.push((m, name));
}
}
out
}
/// The names the name tags show this frame (the control socket's status).
pub(super) fn shown_name_tags(&self, camera: glam::DVec3) -> Vec<String> {
self.name_tags(camera, 1.0)
.into_iter()
.filter_map(|(_, lines, _)| lines.last().map(|(t, _)| t.plain()))
.collect()
}
/// Each name tag: where it hangs, its lines (text, lift) and its light.
#[allow(clippy::type_complexity)]
fn name_tags(
&self,
camera: glam::DVec3,
alpha: f64,
) -> Vec<(glam::DVec3, Vec<(Text, f64)>, u32)> {
let target = self.mob_hit().map(|(i, _)| self.mobs[i].id);
let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
let up = right.cross(forward).normalize_or_zero();
let white = self.res.atlas.font.white();
let viewer = self.player_team();
for m in &self.mobs {
let Some(name) = m.custom_name.as_deref() else {
continue;
};
let mut tags = Vec::new();
let players = self.other_players();
let named = self
.mobs
.iter()
.filter_map(|m| Some((m, m.custom_name.clone()?, false)));
let players = players.into_iter().map(|(m, name)| (m, name, true));
for (m, name, player) in named.chain(players) {
if !m.alive() {
continue;
}
// EntityAttachment.NAME_TAG: 0.5 above the (crouching) height.
let height = if player && m.extra.crouching {
1.5
} else {
f64::from(m.height())
};
let p = glam::DVec3::new(
m.previous.x + (m.position.x - m.previous.x) * alpha,
m.previous.y + (m.position.y - m.previous.y) * alpha + f64::from(m.height()) + 0.5,
m.previous.y + (m.position.y - m.previous.y) * alpha + height + 0.5,
m.previous.z + (m.position.z - m.previous.z) * alpha,
);
// The name tag distance (64) is measured to the entity.
@@ -72,7 +109,17 @@ impl Game<'_> {
if distance_sqr >= 64.0 * 64.0 {
continue;
}
let team = self.mob_team(m.id);
// A player's scores and team go by name, a mob's by UUID.
let holder = if player {
Some(name.clone())
} else {
self.persist.uuids.get(&m.id).map(|u| uuid_text(*u))
};
let team = if player {
self.score.board.players_team(&name)
} else {
self.mob_team(m.id)
};
// LivingEntityRenderer.shouldShowName (team rules included), then
// MobRenderer: a visible name, or the mob under the crosshair.
let invisible = sb::invisible_to(
@@ -82,27 +129,31 @@ impl Game<'_> {
m.has_effect("minecraft:invisibility"),
);
let view = sb::NameView {
discrete: false,
discrete: player && m.extra.crouching,
distance_sqr,
invisible_to_viewer: invisible,
hud_hidden: self.ui.hide_gui,
is_camera: false,
is_vehicle: self.mobs.iter().any(|o| o.extra.mount == Some(m.id)),
};
if !sb::name_shown(team, viewer, view) || !(m.name_visible || Some(m.id) == target) {
// MobRenderer.shouldShowName: a visible name, or the mob under the
// crosshair; players (LivingEntityRenderer) need neither.
if !sb::name_shown(team, viewer, view)
|| !(player || m.name_visible || Some(m.id) == target)
{
continue;
}
// getDisplayName: the custom name in the team's prefix, suffix and colour.
// getDisplayName: the name in the team's prefix, suffix and colour.
let shown = match team {
Some(t) => t.formatted_name(Text::literal(name)),
None => Text::literal(name),
Some(t) => t.formatted_name(Text::literal(&name)),
None => Text::literal(&name),
};
let mut lines = Vec::new();
// EntityRenderer.extractNameTags: the score shows within the
// below-name distance (10), under the name.
let mut lift = 0.0;
if distance_sqr < 10.0 * 10.0
&& let Some(score) = self.below_name_text(m.id)
&& let Some(score) = holder.and_then(|h| self.below_name_text(&h))
{
lines.push((score, 0.0));
lift = f64::from(9.0f32 * 1.15 * 0.025);
@@ -110,11 +161,21 @@ impl Game<'_> {
lines.push((shown, lift));
let l = self.world.light(
m.position.x.floor() as i32,
(m.position.y + f64::from(m.height())).floor() as i32,
(m.position.y + height).floor() as i32,
m.position.z.floor() as i32,
);
let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8);
let away = forward.as_vec3() * 0.002;
tags.push((p, lines, light));
}
tags
}
pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
let up = right.cross(forward).normalize_or_zero();
let white = self.res.atlas.font.white();
let away = forward.as_vec3() * 0.002;
for (p, lines, light) in self.name_tags(camera, alpha) {
for (text, lift) in lines {
let o = (p + glam::DVec3::new(0.0, lift, 0.0) - camera).as_vec3();
let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025);
@@ -254,6 +254,7 @@ impl Game<'_> {
return;
};
for p in &self.paintings {
let entity_start = out.len();
let Some(v) = self.painting_variants.get(&p.variant) else {
continue;
};
@@ -366,6 +367,7 @@ impl Game<'_> {
strip,
0.6,
);
self.cull_entity_vertices(out, entity_start);
}
}
}
+72
View File
@@ -831,6 +831,21 @@ impl Game<'_> {
}
}
C::BlockChangedAck(_) => {}
// ClientLevel.blockEvent: BlockEntity.triggerEvent (chest lids,
// shulker boxes, bells) when the block is still the one it names.
C::BlockEvent(p) => {
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
let block = &self.res.facts.get(state).name;
let named = self.remote.as_ref().and_then(|r| {
r.builtin
.get("minecraft:block")?
.name(p.block)
.map(str::to_owned)
});
if named.as_deref() == Some(&**block) {
self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1));
}
}
C::LevelEvent(p) if p.kind == 2015 => {
self.dragon_egg_particles(p.pos, p.data);
}
@@ -979,6 +994,29 @@ impl Game<'_> {
}
}
}
// ClientPacketListener.handleSetEquipment: what a mob or another
// player holds and wears (EquipmentSlot ordinals).
C::SetEquipment(p) => {
let items: Vec<(u8, Option<Arc<str>>)> = p
.slots
.iter()
.map(|(slot, stack)| (*slot, stack.as_ref().map(|s| self.item_name(s.item))))
.collect();
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
for (slot, item) in items {
let e = &mut m.extra;
match slot {
0 => e.main_hand = item,
1 => e.off_hand = item,
2 => e.feet = item,
3 => e.legs = item,
4 => e.chest = item,
5 => e.head = item,
_ => {}
}
}
}
}
C::TakeItemEntity(p) => {
if self
.remote
@@ -1694,6 +1732,8 @@ impl Game<'_> {
// ClientLevel.tick: the border's size change.
self.border.tick();
self.tick_remote_entities();
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells.
self.tick_block_entity_anims();
self.tick_hand();
self.tick_particles();
let Some(player) = self.player.as_mut() else {
@@ -1785,6 +1825,8 @@ impl Game<'_> {
// The server owns health and hunger: undo local food/fall changes.
self.apply_remote_health();
self.tick_avatar(before, false);
// The player's own model (third person, the inventory's preview).
self.tick_player_model();
if !dead {
self.remote_mining();
if self.right && self.use_delay == 0 && playing {
@@ -2735,6 +2777,18 @@ impl Game<'_> {
}
}
/// Status for `horizon-ctl status`.
/// The other players' entities in the level and their names (from the
/// player list).
pub(super) fn remote_player_names(&self) -> Vec<(u32, String)> {
let Some(r) = self.remote.as_ref() else {
return Vec::new();
};
r.level_players
.iter()
.filter(|(_, uuid)| **uuid != r.profile)
.filter_map(|(id, uuid)| Some((*id as u32, r.players.get(uuid)?.clone())))
.collect()
}
pub(super) fn remote_status(&self) -> Option<serde_json::Value> {
let r = self.remote.as_ref()?;
Some(serde_json::json!({
@@ -2752,12 +2806,30 @@ impl Game<'_> {
}),
"players": r.players.values().collect::<Vec<_>>(),
// Where the other players' entities are (harnesses check movement).
// What the other players hold and wear, as this client draws them.
"player_equipment": self
.mobs
.iter()
.filter(|m| r.level_players.contains_key(&(m.id as i32)))
.map(|m| {
let e = &m.extra;
let armor = [&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref());
serde_json::json!({
"id": m.id,
"armor": armor,
"main_hand": e.main_hand.as_deref(),
"off_hand": e.off_hand.as_deref(),
})
})
.collect::<Vec<_>>(),
"player_positions": r
.entities
.values()
.filter(|t| t.kind == "minecraft:player")
.map(|t| t.position)
.collect::<Vec<_>>(),
// The player's own model exists (third person and the inventory draw it).
"player_model": self.player_model.is_some(),
"health": r.health.0,
"food": r.health.1,
"decode_errors": r.decode_errors,
+63 -5
View File
@@ -292,7 +292,7 @@ pub struct Renderer {
indirect: wgpu::Buffer,
indirect_capacity: u64,
/// Indirect draws may set `first_instance` (the section origin).
multi_draw: bool,
pub multi_draw: bool,
/// Per-frame scratch, kept to avoid allocating every frame.
visible: Vec<Visible>,
origins: Vec<[f32; 4]>,
@@ -358,10 +358,10 @@ fn mip_chain(
for image in crate::mipmap::generate(
base,
levels - 1,
s.strategy,
s.alpha_cutoff_bias,
has_transparent,
s.item,
crate::mipmap::Settings {
has_transparent,
..s
},
) {
out.extend(image.pixels.iter().flatten());
}
@@ -1590,6 +1590,9 @@ impl Renderer {
pub fn section_count(&self) -> usize {
self.sections.len()
}
pub fn has_section(&self, key: SectionKey) -> bool {
self.sections.contains_key(&key)
}
pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) {
self.occlusion.set(key, mesh.visibility);
if mesh.block_entities.is_empty() {
@@ -3001,6 +3004,61 @@ fn mix_frames(current: &mut [u8], next: &[u8], millis: u32) {
mod sprite_upload_tests {
use super::*;
#[test]
fn real_rail_mips_do_not_change_with_larger_array_layers() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root
.join("assets/minecraft/textures/block/rail.png")
.exists()
{
return;
}
let mut sprites = crate::sprites::Sprites::default();
let layers: Vec<_> = [
"rail",
"powered_rail",
"powered_rail_on",
"detector_rail",
"activator_rail",
]
.map(|name| {
sprites
.insert(&root, &format!("minecraft:block/{name}"))
.unwrap()
})
.into();
sprites.finish();
assert_eq!(sprites.size, 16);
let native: Vec<_> = layers
.iter()
.map(|&layer| {
let start = layer as usize * 16 * 16 * 4;
mip_chain(
&sprites.pixels[start..start + 16 * 16 * 4],
16,
&sprites.mips,
layer,
1,
)
.0
})
.collect();
sprites.insert(&root, "minecraft:block/oak_sign").unwrap();
sprites.finish();
assert_eq!(sprites.size, 32);
for (&layer, expected) in layers.iter().zip(native) {
let start = layer as usize * 32 * 32 * 4;
let (actual, _) = mip_chain(
&sprites.pixels[start..start + 32 * 32 * 4],
32,
&sprites.mips,
layer,
1,
);
assert_eq!(&actual[32 * 32 * 4..], expected, "rail layer {layer}");
}
}
#[test]
fn mipmap_option_keeps_real_16px_reductions() {
for levels in 0..=4 {
assert_eq!(sprite_mipmap_limit(levels, 32, 16, 6), levels + 1);
+59
View File
@@ -37,6 +37,36 @@ pub const DRAGON_PART: u32 = 0xFF3F_FF00;
pub const STROKE_WIDTH: f32 = 2.5;
impl Gizmos {
/// `DebugCrosshairRenderer`: the world axes one block in front of the
/// camera, `0.01 * gui_scale` long, X red, Y green, Z light blue, each a
/// 2 pixel line over a 4 pixel black one. Drawn on top, in that order.
pub fn debug_crosshair(&mut self, camera: [f64; 3], x_rot: f32, y_rot: f32, gui_scale: f32) {
let forward = view_vector(x_rot, y_rot);
let center: [f64; 3] = std::array::from_fn(|i| camera[i] + forward[i]);
let length = f64::from(0.01 * gui_scale);
let axes = [(0, 0xFFFF_0000), (1, 0xFF00_FF00), (2, 0xFF7F_7FFF)];
let end = |axis: usize| {
let mut p = center;
p[axis] += length;
p
};
for (axis, _) in axes {
self.on_top.push(Line {
start: center,
end: end(axis),
color: 0xFF00_0000,
width: 4.0,
});
}
for (axis, color) in axes {
self.on_top.push(Line {
start: center,
end: end(axis),
color,
width: 2.0,
});
}
}
/// `Gizmos.line`.
pub fn line(&mut self, start: [f64; 3], end: [f64; 3], color: u32, width: f32) {
self.lines.push(Line {
@@ -277,6 +307,35 @@ pub fn camera_relative(lines: &[Line], camera: [f64; 3], view: glam::Mat4) -> Ve
mod tests {
use super::*;
#[test]
fn debug_crosshair_is_the_world_axes_ahead_of_the_camera() {
let mut g = Gizmos::default();
// Looking south (yaw 0) at GUI scale 2: one block towards +Z.
g.debug_crosshair([0.5, 64.0, 0.5], 0.0, 0.0, 2.0);
assert!(g.lines.is_empty());
let ends: Vec<([f64; 3], u32, f32)> =
g.on_top.iter().map(|l| (l.end, l.color, l.width)).collect();
assert_eq!(g.on_top[0].start, [0.5, 64.0, 1.5]);
// CROSSHAIR_SCALE * guiScale, in floats as vanilla scales.
let l = f64::from(0.01f32 * 2.0);
let (x, y, z) = (
[0.5 + l, 64.0, 1.5],
[0.5, 64.0 + l, 1.5],
[0.5, 64.0, 1.5 + l],
);
assert_eq!(
ends,
[
(x, 0xFF00_0000, 4.0),
(y, 0xFF00_0000, 4.0),
(z, 0xFF00_0000, 4.0),
(x, 0xFFFF_0000, 2.0),
(y, 0xFF00_FF00, 2.0),
(z, 0xFF7F_7FFF, 2.0),
]
);
}
#[test]
fn chunk_borders_match_the_renderer() {
let mut g = Gizmos::default();
+14 -2
View File
@@ -117,6 +117,10 @@ pub struct Graphics {
pub preset: Preset,
/// Skip sections hidden behind closed ones (vanilla's occlusion graph).
pub cave_culling: bool,
/// Hide shared leaf and mangrove-root faces, reducing foliage density.
pub cull_leaves: bool,
/// Skip drawing entities hidden behind opaque terrain.
pub entity_culling: bool,
/// Meshed sections uploaded per frame; 0 uploads all that are ready.
pub chunk_updates: u32,
/// Section mesh bytes uploaded per frame, in KiB; 0 is unlimited.
@@ -149,6 +153,8 @@ impl Default for Graphics {
Self {
preset: Preset::Custom,
cave_culling: true,
cull_leaves: false,
entity_culling: false,
chunk_updates: 0,
upload_budget_kib: 0,
sky: true,
@@ -192,6 +198,8 @@ impl Graphics {
match key.trim() {
"preset" => g.preset = Preset::parse(value),
"caveCulling" => g.cave_culling = flag(g.cave_culling),
"cullLeaves" => g.cull_leaves = flag(g.cull_leaves),
"entityCulling" => g.entity_culling = flag(g.entity_culling),
"chunkUpdates" => g.chunk_updates = number(g.chunk_updates).min(512),
"uploadBudgetKiB" => g.upload_budget_kib = number(g.upload_budget_kib).min(65536),
"sky" => g.sky = flag(g.sky),
@@ -226,9 +234,11 @@ impl Graphics {
}
pub fn serialize(&self) -> String {
format!(
"preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n",
"preset:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n",
self.preset.name(),
bool_text(self.cave_culling),
bool_text(self.cull_leaves),
bool_text(self.entity_culling),
self.chunk_updates,
self.upload_budget_kib,
bool_text(self.sky),
@@ -321,6 +331,8 @@ mod tests {
let g = Graphics {
preset: Preset::Balanced,
cave_culling: false,
cull_leaves: true,
entity_culling: true,
chunk_updates: 12,
upload_budget_kib: 4096,
sky: false,
@@ -340,7 +352,7 @@ mod tests {
assert_eq!(Graphics::parse(&g.serialize()), g);
assert_eq!(Graphics::parse(""), Graphics::default());
assert_eq!(
Graphics::parse("workers:abc\nsky:maybe\n"),
Graphics::parse("workers:abc\nsky:maybe\ncullLeaves:maybe\nentityCulling:maybe\n"),
Graphics::default()
);
}
+102
View File
@@ -22,6 +22,8 @@ pub enum Level {
pub enum H {
Preset,
CaveCulling,
CullLeaves,
EntityCulling,
ChunkUpdates,
UploadBudget,
Sky,
@@ -117,6 +119,16 @@ pub fn rows(level: Level) -> Vec<Row> {
None,
"Skips terrain hidden behind closed sections. Off costs a lot.",
),
h(
H::CullLeaves,
None,
"Hides shared leaf and mangrove root faces; foliage can look less dense.",
),
h(
H::EntityCulling,
None,
"Hides models behind opaque blocks. Entities update. Off with custom packs.",
),
h(
H::ChunkUpdates,
Low,
@@ -282,6 +294,8 @@ impl H {
match self {
H::Preset => labelled("Preset", g.preset.label()),
H::CaveCulling => labelled("Cave Culling", on_off(g.cave_culling)),
H::CullLeaves => labelled("Cull Leaves", on_off(g.cull_leaves)),
H::EntityCulling => labelled("Entity Culling", on_off(g.entity_culling)),
H::ChunkUpdates => match g.chunk_updates {
0 => labelled("Chunk Updates", "Unlimited"),
n => labelled("Chunk Updates", format!("{n} per frame")),
@@ -352,6 +366,8 @@ impl H {
let g = &mut s.horizon;
match self {
H::CaveCulling => g.cave_culling = !g.cave_culling,
H::CullLeaves => g.cull_leaves = !g.cull_leaves,
H::EntityCulling => g.entity_culling = !g.entity_culling,
H::Sky => g.sky = !g.sky,
H::Fog => g.fog = !g.fog,
H::Weather => g.weather = !g.weather,
@@ -397,6 +413,8 @@ impl Item {
let g = &s.horizon;
Some(match self {
Item::Horizon(H::CaveCulling) => g.cave_culling,
Item::Horizon(H::CullLeaves) => g.cull_leaves,
Item::Horizon(H::EntityCulling) => g.entity_culling,
Item::Horizon(H::Sky) => g.sky,
Item::Horizon(H::Fog) => g.fog,
Item::Horizon(H::Weather) => g.weather,
@@ -896,4 +914,88 @@ mod tests {
H::UploadBudget.set_slider(&mut s, 0.0);
assert_eq!(s.horizon.upload_budget_kib, 0);
}
#[test]
fn cull_leaves_is_opt_in_and_toggles_from_advanced_graphics() {
let mut s = Settings::default();
let item = Item::Horizon(H::CullLeaves);
assert_eq!(item.switch(&s), Some(false));
assert_eq!(item.label(&s).plain(), "Cull Leaves: Off");
for enabled in [false, true] {
s.horizon.cull_leaves = enabled;
for preset in Preset::ALL {
crate::graphics::apply_preset(preset, &mut s);
assert_eq!(s.horizon.cull_leaves, enabled);
}
}
let mut ui = GraphicsUi::default();
let size = (480.0, 4000.0);
let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1);
let switch = widgets
.iter()
.find(|w| matches!(w.target, Target::Item(i) if i == item))
.unwrap();
let point = (switch.x + 1.0, switch.y + 1.0);
for enabled in [false, true] {
s.horizon.preset = Preset::Balanced;
assert_eq!(
ui.click(
Level::Advanced,
&mut s,
point,
size,
[854, 480],
false,
false
),
vec![Action::ButtonClick, Action::Changed]
);
assert_eq!(item.switch(&s), Some(enabled));
assert_eq!(s.horizon.preset, Preset::Custom);
}
assert_eq!(item.label(&s).plain(), "Cull Leaves: On");
}
#[test]
fn entity_culling_is_opt_in_and_toggles_from_advanced_graphics() {
let mut s = Settings::default();
let item = Item::Horizon(H::EntityCulling);
assert_eq!(item.switch(&s), Some(false));
assert_eq!(item.label(&s).plain(), "Entity Culling: Off");
for enabled in [false, true] {
s.horizon.entity_culling = enabled;
for preset in Preset::ALL {
crate::graphics::apply_preset(preset, &mut s);
assert_eq!(s.horizon.entity_culling, enabled);
}
}
let mut ui = GraphicsUi::default();
let size = (480.0, 4000.0);
let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1);
let switch = widgets
.iter()
.find(|w| matches!(w.target, Target::Item(i) if i == item))
.unwrap();
let point = (switch.x + 1.0, switch.y + 1.0);
for enabled in [false, true] {
s.horizon.preset = Preset::Balanced;
assert_eq!(
ui.click(
Level::Advanced,
&mut s,
point,
size,
[854, 480],
false,
false
),
vec![Action::ButtonClick, Action::Changed]
);
assert_eq!(item.switch(&s), Some(enabled));
assert_eq!(s.horizon.preset, Preset::Custom);
}
assert_eq!(item.label(&s).plain(), "Entity Culling: On");
}
}
+36 -4
View File
@@ -180,11 +180,17 @@ impl Hub {
/// Open a trading window for a guest (`Merchant.openTradingScreen`):
/// its id, or None when the menu type is unknown.
pub fn open_merchant_window(&mut self, conn: u32, title: Tag) -> Option<i32> {
self.open_window(conn, "minecraft:merchant", title)
}
/// ServerPlayer.openMenu for a menu the game runs (merchant, crafting
/// table): the open container closes, a new window id opens this menu.
pub fn open_window(&mut self, conn: u32, menu: &str, title: Tag) -> Option<i32> {
let kind = self
.sync
.builtin
.get("minecraft:menu")
.and_then(|m| m.id("minecraft:merchant"))?;
.and_then(|m| m.id(menu))?;
let i = self.guests.iter().position(|g| g.conn == conn)?;
self.close_container_at(i);
let g = &mut self.guests[i];
@@ -277,7 +283,7 @@ impl Hub {
pub fn container_click(
&mut self,
conn: u32,
p: play::ContainerClick,
p: &play::ContainerClick,
world: &mut World,
rules: &dyn Rules,
) -> Vec<ItemStack> {
@@ -326,7 +332,34 @@ impl Hub {
} else {
self.guests[i].drag = drag;
}
// Tell the client about every slot it got wrong, or that it did not claim.
self.answer_click(i, p, world, &changed);
drops
}
/// A click on the inventory menu (window 0) the game applied itself
/// (the crafting grid): the client is corrected like after any click.
pub fn inventory_clicked(
&mut self,
conn: u32,
p: &play::ContainerClick,
world: &World,
changed: &[usize],
) {
if let Some(i) = self.guests.iter().position(|g| g.conn == conn) {
self.answer_click(i, p, world, changed);
}
}
/// After a click: tell the client about every slot it got wrong, or that
/// it did not claim, and the carried stack.
fn answer_click(
&mut self,
i: usize,
p: &play::ContainerClick,
world: &World,
changed: &[usize],
) {
let in_menu = p.container != 0;
let claimed: HashMap<usize, Option<Hashed>> = p
.changed
.iter()
@@ -382,7 +415,6 @@ impl Hub {
} else {
self.guests[i].menu_sent = items;
}
drops
}
/// Slot changes of open containers (AbstractContainerMenu.broadcastChanges).
+14 -1
View File
@@ -80,6 +80,10 @@ pub struct Guest {
pub offhand: Option<ItemStack>,
pub selected: usize,
pub carried: Option<ItemStack>,
/// The inventory menu's crafting grid (2x2) and its result
/// (`InventoryMenu.craftSlots`, `resultSlots`), which the game computes.
pub craft_grid: [Option<ItemStack>; 4],
pub craft_result: Option<ItemStack>,
pub health: f32,
pub food: i32,
pub saturation: f32,
@@ -95,6 +99,9 @@ pub struct Guest {
pub inbox: VecDeque<play::Serverbound>,
pub joined_tick: u64,
pub ticks: u64,
/// The moves accepted since the game last looked (movement, on ground),
/// for ServerPlayer.doCheckFallDamage.
pub moves: Vec<([f64; 3], bool)>,
pub dead: bool,
/// The join packets were sent (PlayerList.placeNewPlayer ran).
pub placed: bool,
@@ -154,6 +161,8 @@ impl Guest {
offhand: None,
selected: 0,
carried: None,
craft_grid: Default::default(),
craft_result: None,
health: 20.0,
food: 20,
saturation: 5.0,
@@ -168,6 +177,7 @@ impl Guest {
inbox: VecDeque::new(),
joined_tick: 0,
ticks: 0,
moves: Vec::new(),
dead: false,
placed: false,
menu: None,
@@ -221,7 +231,8 @@ impl Guest {
/// 45 off hand.
pub fn menu_slot(&self, slot: usize) -> Option<ItemStack> {
match slot {
0..=4 => None,
0 => self.craft_result.clone(),
1..=4 => self.craft_grid[slot - 1].clone(),
5..=8 => self.armor[slot - 5].clone(),
9..=35 => self.inventory.get(slot).cloned().flatten(),
36..=44 => self.inventory.get(slot - 36).cloned().flatten(),
@@ -231,6 +242,8 @@ impl Guest {
}
pub fn set_menu_slot(&mut self, slot: usize, item: Option<ItemStack>) {
match slot {
0 => self.craft_result = item,
1..=4 => self.craft_grid[slot - 1] = item,
5..=8 => self.armor[slot - 5] = item,
9..=35 => self.inventory[slot] = item,
36..=44 => self.inventory[slot - 36] = item,
+5 -3
View File
@@ -1394,9 +1394,7 @@ impl Hub {
S::MovePlayerRot(p) => {
self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags);
}
S::MovePlayerStatus(p) => {
self.guests[i].on_ground = p.flags & 1 != 0;
}
S::MovePlayerStatus(p) => self.move_player(i, None, None, p.flags),
S::PlayerLoaded(_) => self.guests[i].loaded = true,
S::ChunkBatchReceived(p) => {
let g = &mut self.guests[i];
@@ -1460,6 +1458,10 @@ impl Hub {
g.previous_position = g.position;
g.position = p;
}
let moved = pos.map_or([0.0; 3], |_| {
[0, 1, 2].map(|k| g.position[k] - g.previous_position[k])
});
g.moves.push((moved, flags & 1 != 0));
if let Some((yaw, pitch)) = rot
&& yaw.is_finite()
&& pitch.is_finite()
+2
View File
@@ -47,10 +47,12 @@ pub mod data_cmd;
pub mod datapack;
pub mod debug_chart;
pub mod debug_keys;
pub mod debug_overlay;
pub mod effects;
pub mod enchant;
pub mod end_crystal;
pub mod entities;
pub mod entity_culling;
pub mod entity_nbt;
pub mod environment;
pub mod extras;
+22 -13
View File
@@ -167,6 +167,8 @@ fn visibility(pad: &Padded, info: &[Info]) -> u64 {
result
}
#[cfg(test)]
mod leaf_culling_tests;
#[cfg(test)]
mod visibility_tests;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Tint {
@@ -208,6 +210,7 @@ struct Info {
overlay: bool,
/// `LeavesBlock`: with opaque leaves the faces between two leaf blocks are skipped.
leaves: bool,
mangrove_roots: bool,
blocks_flow: bool,
ice: bool,
sturdy: u8,
@@ -368,6 +371,7 @@ impl MeshTables {
legacy_solid: s.legacy_solid,
overlay: s.has_class("HalfTransparentBlock") || s.has_class("LeavesBlock"),
leaves: s.has_class("LeavesBlock"),
mangrove_roots: s.has_class("MangroveRootsBlock"),
blocks_flow: assets.blocks_fluid_flow.contains(&*s.name),
ice: s.has_class("IceBlock"),
sturdy: s.sturdy_full,
@@ -596,6 +600,8 @@ pub struct Mesher<'a> {
pub smooth_lighting: bool,
/// The `cutoutLeaves` option (fancy graphics); off makes leaves opaque.
pub cutout_leaves: bool,
/// Cull shared leaf and mangrove-root faces, including transparent leaves.
pub cull_leaves: bool,
}
impl Mesher<'_> {
/// `region[dz][dx]` are the chunks around the meshed column (centre 1,1).
@@ -673,19 +679,22 @@ impl Mesher<'_> {
for d in Direction::ALL {
let [dx, dy, dz] = d.normal();
let neighbor = pad.blocks[pi(x + dx, y + dy, z + dz)];
visible[d as usize] = self
.visibility
.should_render_face(
BlockStateId(id.into()),
BlockStateId(neighbor.into()),
d,
true,
)
.unwrap_or(true);
// LeavesBlock.skipRendering with opaque leaves.
if !self.cutout_leaves && state.leaves && info[neighbor as usize].leaves {
visible[d as usize] = false;
}
let other = &info[neighbor as usize];
// Adapted from CullLeaves (MIT); see THIRD_PARTY_NOTICES.md.
let shared_foliage = (state.leaves
&& other.leaves
&& (!self.cutout_leaves || self.cull_leaves))
|| (self.cull_leaves && state.mangrove_roots && other.mangrove_roots);
visible[d as usize] = !shared_foliage
&& self
.visibility
.should_render_face(
BlockStateId(id.into()),
BlockStateId(neighbor.into()),
d,
true,
)
.unwrap_or(true);
}
for (_, model) in &models {
for face in &model.faces {
@@ -0,0 +1,124 @@
use super::*;
use horizon_assets::model::Direction as ModelDirection;
#[test]
fn leaf_culling_removes_only_internal_leaf_and_root_faces() {
let root =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("horizon-resources.json").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let facts = BlockFacts::load(&root, assets.registry).unwrap();
let visibility = crate::models::load_visibility(&root, assets.registry).unwrap();
let tables = MeshTables::new(&assets, &facts, visibility.clone()).unwrap();
let biomes = Biomes::load(&root).unwrap();
let state = |name| assets.registry.default_state(name).unwrap().0 as u16;
let oak = state("minecraft:oak_leaves");
let birch = state("minecraft:birch_leaves");
let roots = state("minecraft:mangrove_roots");
let stone = state("minecraft:stone");
let mesh = |blocks: &[([i32; 3], u16)], cull_leaves, cutout_leaves| {
let mut center = Chunk::empty(0, 0);
let mut east = Chunk::empty(1, 0);
for &([x, y, z], state) in blocks {
let chunk = if x < 16 { &mut center } else { &mut east };
chunk.set(x, y, z, state);
}
let mut region = [[None; 3]; 3];
region[1][1] = Some(&center);
region[1][2] = Some(&east);
Mesher {
nether_shading: false,
assets: &assets,
tables: &tables,
biomes: &biomes,
visibility: visibility.clone(),
zoom: BiomeZoom::new(0),
blend_radius: 0,
smooth_lighting: false,
cutout_leaves,
cull_leaves,
}
.mesh(&region, (0 - MIN_Y) / 16)
.solid
};
// Native leaves can contain unculled interior geometry as well as their
// outer faces. Select the touching cull group from the actual baked model,
// preserving every other quad and its full vertex attributes.
let without_face = |at: [i32; 3], id, direction| {
let vertices = mesh(&[(at, id)], false, true);
let models = assets
.model_catalog
.collect(BlockStateId(id.into()), BlockPos::new(at[0], at[1], at[2]))
.unwrap();
let faces: Vec<_> = models.iter().flat_map(|(_, model)| &model.faces).collect();
assert_eq!(vertices.len(), faces.len() * 4);
let retained: Vec<_> = vertices
.as_chunks::<4>()
.0
.iter()
.zip(faces)
.filter(|(_, face)| face.quad.cull != Some(direction))
.flat_map(|(quad, _)| quad.iter().copied())
.collect();
assert!(retained.len() < vertices.len(), "fixture has a cull group");
retained
};
// Same-species leaves, mixed leaves and roots hide only their touching
// model groups. Disabling the option restores the isolated models.
for (a, b) in [(oak, oak), (oak, birch), (roots, roots)] {
let blocks = [([7, 7, 7], a), ([8, 7, 7], b)];
let off = mesh(&blocks, false, true);
let on = mesh(&blocks, true, true);
assert_eq!(
off.len(),
mesh(&[blocks[0]], false, true).len() + mesh(&[blocks[1]], false, true).len()
);
let mut retained = without_face(blocks[0].0, a, ModelDirection::East);
retained.extend(without_face(blocks[1].0, b, ModelDirection::West));
assert_eq!(
bytemuck::cast_slice::<_, u8>(&on),
bytemuck::cast_slice::<_, u8>(&retained)
);
}
// Roots do not join leaves into a single culling group. Ordinary opaque
// neighbors also keep their existing occlusion behavior.
for (a, b) in [(oak, roots), (roots, oak), (oak, stone)] {
let blocks = [([7, 7, 7], a), ([8, 7, 7], b)];
let off = mesh(&blocks, false, true);
let on = mesh(&blocks, true, true);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&on),
bytemuck::cast_slice::<_, u8>(&off)
);
}
// Opaque leaves already hide internal leaf faces independently of this
// option, and a leaf beside air retains its complete baked model.
let pair = [([7, 7, 7], oak), ([8, 7, 7], birch)];
assert_eq!(
mesh(&pair, false, false).len(),
mesh(&pair, true, false).len()
);
let isolated = [([7, 7, 7], oak)];
assert_eq!(
bytemuck::cast_slice::<_, u8>(&mesh(&isolated, false, true)),
bytemuck::cast_slice::<_, u8>(&mesh(&isolated, true, true))
);
// The padding read must also remove the center chunk's internal face
// against a different leaf species in the neighboring chunk.
let boundary = [([15, 7, 7], oak), ([16, 7, 7], birch)];
assert_eq!(
mesh(&boundary, false, true).len(),
mesh(&[boundary[0]], false, true).len()
);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&mesh(&boundary, true, true)),
bytemuck::cast_slice::<_, u8>(&without_face(boundary[0].0, oak, ModelDirection::East))
);
}
@@ -87,6 +87,7 @@ fn info(solid: bool) -> Info {
legacy_solid: false,
overlay: false,
leaves: false,
mangrove_roots: false,
blocks_flow: false,
ice: false,
sturdy: 0,
+43 -11
View File
@@ -31,6 +31,9 @@ impl Strategy {
/// it has a fully transparent pixel and whether it is an `item/` sprite.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Settings {
/// Original square frame edge, before fitting the sprite into the array.
/// Zero means the supplied image is already at its native size.
pub native_size: u32,
pub strategy: Strategy,
pub alpha_cutoff_bias: f32,
pub has_transparent: bool,
@@ -45,6 +48,15 @@ pub struct Image {
pub pixels: Vec<[u8; 4]>,
}
impl Image {
fn resized(&self, size: u32) -> Self {
Self {
width: size,
height: size,
pixels: (0..size * size)
.map(|i| self.get(i % size * self.width / size, i / size * self.height / size))
.collect(),
}
}
fn get(&self, x: u32, y: u32) -> [u8; 4] {
self.pixels[(x + y * self.width) as usize]
}
@@ -263,17 +275,37 @@ fn darkened_alpha_blend(c: [[u8; 4]; 4]) -> [u8; 4] {
}
/// `MipmapGenerator.generateMipLevels` from the base image (`levels` mips
/// below it): `has_transparent` is `Transparency.hasTransparent` (a pixel
/// with zero alpha), `item` whether the sprite is under `item/` (its base
/// is left as is).
pub fn generate(
mut base: Image,
levels: u32,
strategy: Strategy,
alpha_cutoff_bias: f32,
has_transparent: bool,
item: bool,
) -> Vec<Image> {
/// below it). Array-only enlargement must not run extra alpha-coverage steps
/// before the sprite's native mip chain.
pub fn generate(base: Image, levels: u32, settings: Settings) -> Vec<Image> {
let native = settings.native_size;
if native.is_power_of_two()
&& native < base.width
&& base.width == base.height
&& base.width.is_power_of_two()
{
let extra = (base.width / native).ilog2();
let mut mips =
generate_native(base.resized(native), levels.saturating_sub(extra), settings);
let mut out: Vec<_> = (0..extra.min(levels + 1))
.map(|level| mips[0].resized(base.width >> level))
.collect();
if levels >= extra {
out.append(&mut mips);
}
return out;
}
generate_native(base, levels, settings)
}
fn generate_native(mut base: Image, levels: u32, settings: Settings) -> Vec<Image> {
let Settings {
strategy,
alpha_cutoff_bias,
has_transparent,
item,
..
} = settings;
let strategy = match strategy {
Strategy::Auto if has_transparent => Strategy::Cutout,
Strategy::Auto => Strategy::Mean,
+324 -60
View File
@@ -4,7 +4,7 @@
//! ServerStatusPinger to show the MOTD, player count and latency.
use crate::hud::{HudAtlas, HudBatch, rgba};
use crate::lan::discovery::Scanner;
use crate::text::{Text, format_translation};
use crate::text::{DARK_GRAY, GRAY, Text, format_translation};
use crate::title::confirm_top;
use horizon_protocol::servers::{self, ServerEntry};
use std::{
@@ -19,14 +19,36 @@ use std::{
pub enum Ping {
Pinging,
Ok {
motd: String,
players: String,
/// The description component, styled (`sanitizeDescription`).
motd: Text,
/// Online and max players; None when the status has no `players`.
players: Option<(i64, i64)>,
ms: u128,
version: String,
},
Failed(String),
}
impl Ping {
/// ServerStatusPinger.formatPlayerCount: dark grey with grey numbers,
/// or `multiplayer.status.unknown` without a player count.
pub fn player_count(players: Option<(i64, i64)>) -> Text {
match players {
Some((online, max)) => Text::translate(
"multiplayer.status.player_count",
&[
Text::colored(online.to_string(), GRAY),
Text::colored(max.to_string(), GRAY),
],
),
None => Text::translate("multiplayer.status.unknown", &[]),
}
.with_color(DARK_GRAY)
}
}
type Pings = Arc<Mutex<HashMap<String, Ping>>>;
/// Server icons by address as 64x64 RGBA (FaviconTexture), from servers.dat
/// and then from each ping's favicon.
type Icons = Arc<Mutex<HashMap<String, Arc<Vec<u8>>>>>;
#[derive(Clone, Debug)]
pub enum Screen {
@@ -34,6 +56,7 @@ pub enum Screen {
servers: Vec<ServerEntry>,
selected: Option<usize>,
pings: Pings,
icons: Icons,
/// Worlds announced on the local network, listed after the servers.
lan: Scanner,
scroll: crate::ui::Scroll,
@@ -83,24 +106,63 @@ pub fn servers_file(saves: &Path) -> PathBuf {
.parent()
.map_or_else(|| PathBuf::from("servers.dat"), |p| p.join("servers.dat"))
}
fn ping_all(servers: &[ServerEntry], pings: &Pings) {
/// `FaviconTexture.upload`: a PNG of exactly 64x64 pixels, else no icon.
fn icon_pixels(png: &[u8]) -> Option<Arc<Vec<u8>>> {
crate::hud::decode_bytes(png)
.ok()
.filter(|(w, h, _)| *w == 64 && *h == 64)
.map(|(_, _, p)| Arc::new(p))
}
/// `ServerStatus.Favicon.CODEC`: a base64 PNG behind the data URL prefix.
fn favicon_bytes(json: &serde_json::Value) -> Option<Vec<u8>> {
let url = json["favicon"].as_str()?;
let base64 = url
.strip_prefix("data:image/png;base64,")?
.replace('\n', "");
crate::skins::base64_decode(&base64)
}
fn ping_all(servers: &[ServerEntry], pings: &Pings, icons: &Icons, file: &Path) {
for s in servers {
let address = s.ip.clone();
pings.lock().unwrap().insert(address.clone(), Ping::Pinging);
let pings = pings.clone();
let saved = s.icon.clone();
if let Some(pixels) = saved
.as_deref()
.and_then(crate::skins::base64_decode)
.and_then(|png| icon_pixels(&png))
{
icons.lock().unwrap().insert(address.clone(), pixels);
}
let (pings, icons, file) = (pings.clone(), icons.clone(), file.to_owned());
let _ = std::thread::Builder::new()
.name("horizon-ping".into())
.spawn(move || {
let result = match crate::net::ping(&address, Duration::from_secs(5)) {
Ok((json, ms)) => {
let lang = Default::default();
let motd = crate::net::json_text(&json["description"], &lang);
let players = format!(
"{}/{}",
json["players"]["online"].as_i64().unwrap_or(0),
json["players"]["max"].as_i64().unwrap_or(0)
);
let motd = crate::component::to_text(&json["description"], &mut |s| {
Text::literal(s)
});
let players = json["players"].as_object().map(|p| {
(
p.get("online").and_then(|n| n.as_i64()).unwrap_or(0),
p.get("max").and_then(|n| n.as_i64()).unwrap_or(0),
)
});
let version = json["version"]["name"].as_str().unwrap_or("?").to_owned();
// A new favicon replaces the saved one (an invalid one
// clears it) and servers.dat is saved again.
if let Some(png) = favicon_bytes(&json) {
let encoded = crate::lan::base64(&png);
let pixels = icon_pixels(&png);
match &pixels {
Some(p) => icons.lock().unwrap().insert(address.clone(), p.clone()),
None => icons.lock().unwrap().remove(&address),
};
let icon = pixels.map(|_| encoded);
if icon != saved {
save_icon(&file, &address, icon);
}
}
Ping::Ok {
motd,
players,
@@ -114,6 +176,33 @@ fn ping_all(servers: &[ServerEntry], pings: &Pings) {
});
}
}
/// Save the list after a move or delete, keeping the icons pings stored in
/// servers.dat since it was loaded.
fn save_servers(file: &Path, servers: &mut [ServerEntry]) {
let _guard = SAVING.lock();
let saved = servers::load(file);
for entry in servers.iter_mut() {
if let Some(s) = saved.iter().find(|s| s.ip == entry.ip) {
entry.icon = s.icon.clone();
}
}
let _ = servers::save(file, servers);
}
/// Held while servers.dat is read and written back.
static SAVING: Mutex<()> = Mutex::new(());
/// Store `icon` on the entries for `address` (OnlineServerEntry.updateServerList).
fn save_icon(file: &Path, address: &str, icon: Option<String>) {
let _guard = SAVING.lock();
let mut list = servers::load(file);
let mut changed = false;
for entry in list.iter_mut().filter(|e| e.ip == address) {
changed |= entry.icon != icon;
entry.icon = icon.clone();
}
if changed {
let _ = servers::save(file, &list);
}
}
/// The address of list row `index`: the saved servers, then the LAN games.
fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option<String> {
@@ -176,6 +265,41 @@ fn row_at(
}
rows(servers, lan).nth(index as usize)
}
/// SelectableEntry's hover areas over the 32-pixel icon, relative to it.
fn over_right_half(x: f32, y: f32) -> bool {
(16.0..32.0).contains(&x) && (0.0..32.0).contains(&y)
}
fn over_top_left(x: f32, y: f32) -> bool {
(0.0..16.0).contains(&x) && (0.0..16.0).contains(&y)
}
fn over_bottom_left(x: f32, y: f32) -> bool {
(0.0..16.0).contains(&x) && (16.0..32.0).contains(&y)
}
/// The server's favicon in icon slot `slot`, else `misc/unknown_server`.
fn draw_server_icon(
atlas: &HudAtlas,
batch: &mut HudBatch,
pixels: Option<&[u8]>,
slot: usize,
x: f32,
y: f32,
) {
let sprite = format!("horizon/world-icon{}", slot % crate::hud::WORLD_ICON_SLOTS);
if let Some(pixels) = pixels
&& let Some(rect) = atlas.sprites.get(&sprite)
{
batch.patches.push(crate::font::Patch {
x: (rect.u0 * atlas.width as f32).round() as u32,
y: (rect.v0 * atlas.height as f32).round() as u32,
width: 64,
height: 64,
rgba: pixels.to_vec(),
});
batch.sprite_scaled(atlas, &sprite, x, y, 32.0, 32.0, u32::MAX);
} else {
batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX);
}
}
/// `LoadingDotsText.get`.
fn loading_dots(millis: u128) -> &'static str {
["O o o", "o O o", "o o O", "o O o"][(millis / 300 % 4) as usize]
@@ -251,11 +375,13 @@ impl Screen {
pub fn list(saves: &Path) -> Self {
let servers = servers::load(&servers_file(saves));
let pings: Pings = Arc::default();
ping_all(&servers, &pings);
let icons: Icons = Arc::default();
ping_all(&servers, &pings, &icons, &servers_file(saves));
Self::List {
servers,
selected: None,
pings,
icons,
lan: Scanner::start(),
scroll: crate::ui::Scroll::default(),
}
@@ -482,7 +608,7 @@ impl Screen {
true,
);
}
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) {
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool, cursor: (f32, f32)) {
let (w, h) = (batch.width, batch.height);
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| {
@@ -494,6 +620,7 @@ impl Screen {
servers,
selected,
pings,
icons,
lan,
scroll,
} => {
@@ -520,6 +647,9 @@ impl Screen {
crate::ui::list_background(batch, atlas, top, bottom, false);
let first = batch.vertices.len();
let pings = pings.lock().unwrap();
let icons = icons.lock().unwrap();
// The row under the pointer (`isHovered`).
let hovered = row_at(servers.len(), games.len(), cursor, (w, h), scroll.amount);
let millis = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis());
@@ -566,25 +696,18 @@ impl Screen {
match row {
Row::Server(k) => {
let server = &servers[k];
batch.sprite_scaled(
atlas,
"misc/unknown_server",
cx,
cy,
32.0,
32.0,
u32::MAX,
);
batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, false);
let icon = icons.get(&server.ip);
draw_server_icon(atlas, batch, icon.map(|p| p.as_slice()), i, cx, cy);
batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, true);
// OnlineServerEntry: up to two lines of MOTD, the
// player count left of the status icon.
let (motd, status, motd_color, icon) = match pings.get(&server.ip) {
// player count left of the status icon, all with
// GuiGraphics.text's shadow.
let (motd, status, sprite) = match pings.get(&server.ip) {
Some(Ping::Ok {
motd, players, ms, ..
}) => (
motd.clone(),
players.clone(),
gray,
motd.resolve_legacy(),
Ping::player_count(*players),
format!(
"server_list/ping_{}",
match ms {
@@ -597,12 +720,9 @@ impl Screen {
),
),
Some(Ping::Failed(_)) => (
crate::lang::get_or(
"multiplayer.status.cannot_connect",
"Can't connect to server",
),
String::new(),
rgba(255, 0, 0, 255),
Text::translate("multiplayer.status.cannot_connect", &[])
.with_color(0xFF0000),
Text::empty(),
"server_list/unreachable".to_owned(),
),
_ => {
@@ -610,50 +730,71 @@ impl Screen {
let frame = (millis / 100 + i as u128 * 2) & 7;
let frame = if frame > 4 { 8 - frame } else { frame };
(
crate::lang::get_or(
"multiplayer.status.pinging",
"Pinging...",
),
String::new(),
gray,
Text::translate("multiplayer.status.pinging", &[]),
Text::empty(),
format!("server_list/pinging_{}", frame + 1),
)
}
};
for (n, line) in wrap(&motd, ROW_WIDTH - 4.0 - 34.0, atlas)
for (n, line) in atlas
.font
.split(&motd, ROW_WIDTH - 4.0 - 32.0 - 2.0)
.iter()
.take(2)
.enumerate()
{
batch.text(
batch.text_styled(
atlas,
line,
cx + 35.0,
cy + 12.0 + 9.0 * n as f32,
motd_color,
false,
gray,
true,
);
}
let icon_x = cx + ROW_WIDTH - 4.0 - 15.0;
batch.sprite_scaled(
atlas,
&format!("gui/sprites/{icon}"),
&format!("gui/sprites/{sprite}"),
icon_x,
cy,
10.0,
8.0,
u32::MAX,
);
if !status.is_empty() {
let sw = HudBatch::text_width(atlas, &status).ceil();
batch.text(
atlas,
&status,
icon_x - sw - 5.0,
cy + 1.0,
gray,
false,
);
let sw = atlas.font.width_text(&status).ceil();
batch.text_styled(
atlas,
&status,
icon_x - sw - 5.0,
cy + 1.0,
gray,
true,
);
// Hovering the row: the join arrow over the icon
// and the move arrows, each highlighted under
// the pointer.
if hovered == Some(row) {
let (rx, ry) = (cursor.0 - cx, cursor.1 - cy);
batch.fill(atlas, cx, cy, 32.0, 32.0, 0xA0909090);
for (sprite, shown, over) in [
("join", true, over_right_half(rx, ry)),
("move_up", k > 0, over_top_left(rx, ry)),
("move_down", k + 1 < servers.len(), over_bottom_left(rx, ry)),
] {
if shown {
let lit = if over { "_highlighted" } else { "" };
batch.sprite_scaled(
atlas,
&format!("gui/sprites/server_list/{sprite}{lit}"),
cx,
cy,
32.0,
32.0,
u32::MAX,
);
}
}
}
}
Row::LanHeader => {
@@ -916,7 +1057,7 @@ impl Screen {
&& i < servers.len()
{
servers.remove(i);
let _ = servers::save(&servers_file(saves), servers);
save_servers(&servers_file(saves), servers);
}
}
(Self::List { .. }, Some(45)) => *self = Self::list(saves),
@@ -938,9 +1079,34 @@ impl Screen {
if scroll.press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content) {
return Outcome::None;
}
let row = row_at(servers.len(), games, (x, y), (w, h), scroll.amount);
// OnlineServerEntry.mouseClicked: the icon's right half joins,
// its left quarters move the server up or down (and keep it
// selected).
if let Some(Row::Server(k)) = row {
let row_top = top + 2.0 - scroll.amount.trunc() + k as f32 * ROW_HEIGHT;
let (rx, ry) = ((x - left - 2.0).floor(), (y - row_top - 2.0).floor());
if over_right_half(rx, ry) {
*selected = Some(k);
return Outcome::Connect(servers[k].ip.clone());
}
let to = if k > 0 && over_top_left(rx, ry) {
Some(k - 1)
} else if k + 1 < servers.len() && over_bottom_left(rx, ry) {
Some(k + 1)
} else {
None
};
if let Some(to) = to {
servers.swap(k, to);
save_servers(&servers_file(saves), servers);
*selected = Some(to);
return Outcome::None;
}
}
// Clicking a selected row again joins it; the LAN header
// takes the click without anything to join.
let index = match row_at(servers.len(), games, (x, y), (w, h), scroll.amount) {
let index = match row {
Some(Row::Server(k)) => Some(k),
Some(Row::Lan(k)) => Some(servers.len() + k),
Some(Row::LanHeader) => {
@@ -1197,8 +1363,8 @@ mod tests {
pings.insert(
"server0".into(),
Ping::Ok {
motd: String::new(),
players: String::new(),
motd: Text::empty(),
players: None,
ms: 42,
version: String::new(),
},
@@ -1276,6 +1442,104 @@ mod tests {
);
}
#[test]
fn player_count_is_dark_gray_with_gray_numbers() {
assert_eq!(
Ping::player_count(Some((3, 20))).component(),
serde_json::json!({
"translate": "multiplayer.status.player_count",
"with": [{"text": "3", "color": "gray"}, {"text": "20", "color": "gray"}],
"color": "dark_gray",
})
);
assert_eq!(
Ping::player_count(None).component(),
serde_json::json!({"translate": "multiplayer.status.unknown", "color": "dark_gray"})
);
}
fn png(size: u32) -> Vec<u8> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, size, size);
encoder.set_color(png::ColorType::Rgba);
let mut writer = encoder.write_header().unwrap();
writer
.write_image_data(&vec![200; (size * size * 4) as usize])
.unwrap();
writer.finish().unwrap();
out
}
#[test]
fn favicons_are_64_pixel_pngs_behind_the_data_url() {
let icon = png(64);
let encoded = crate::lan::base64(&icon);
let (a, b) = encoded.split_at(10);
let json = serde_json::json!({ "favicon": format!("data:image/png;base64,{a}\n{b}") });
let bytes = favicon_bytes(&json).unwrap();
assert_eq!(bytes, icon);
assert_eq!(icon_pixels(&bytes).unwrap().len(), 64 * 64 * 4);
// FaviconTexture refuses other sizes; other formats are not icons.
assert!(icon_pixels(&png(32)).is_none());
assert!(favicon_bytes(&serde_json::json!({ "favicon": encoded })).is_none());
}
#[test]
fn icon_arrows_join_and_move_servers() {
let dir = std::env::temp_dir().join(format!("horizon-mp-arrows-{}", std::process::id()));
let saves = dir.join("saves");
std::fs::create_dir_all(&saves).unwrap();
let file = servers_file(&saves);
let names = ["a", "b", "c"];
let list: Vec<ServerEntry> = names
.iter()
.map(|n| ServerEntry::new(n, &format!("127.0.0.1:{}", 1 + n.len())))
.collect();
servers::save(&file, &list).unwrap();
let mut screen = Screen::list(&saves);
let size = (427.0, 240.0);
let order = |screen: &Screen| match screen {
Screen::List {
servers, selected, ..
} => (
servers.iter().map(|s| s.name.clone()).collect::<Vec<_>>(),
*selected,
),
_ => unreachable!(),
};
// 427x240: rows start at x 61, the first icon at (63, 37).
let (ix, iy) = (63.0, 37.0);
// The first server has no up arrow: its top-left quarter selects it.
assert!(matches!(
screen.click(None, ix + 4.0, iy + 4.0, size, &saves),
Outcome::None
));
assert_eq!(
order(&screen),
(vec!["a".into(), "b".into(), "c".into()], Some(0))
);
// Bottom-left quarter: down, saved, and still selected.
screen.click(None, ix + 4.0, iy + 20.0, size, &saves);
assert_eq!(
order(&screen),
(vec!["b".into(), "a".into(), "c".into()], Some(1))
);
let saved: Vec<String> = servers::load(&file).into_iter().map(|s| s.name).collect();
assert_eq!(saved, ["b", "a", "c"]);
// Top-left quarter of the second row: back up.
screen.click(None, ix + 4.0, iy + ROW_HEIGHT + 4.0, size, &saves);
assert_eq!(
order(&screen),
(vec!["a".into(), "b".into(), "c".into()], Some(0))
);
// The right half joins at once.
match screen.click(None, ix + 20.0, iy + 2.0 * ROW_HEIGHT + 10.0, size, &saves) {
Outcome::Connect(address) => assert_eq!(address, list[2].ip),
_ => panic!("the join arrow connects"),
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn delete_asks_before_removing_the_server() {
let dir = std::env::temp_dir().join(format!("horizon-mp-delete-{}", std::process::id()));
+2 -7
View File
@@ -14,7 +14,7 @@ use crate::{
graphics_style::Cost,
graphics_ui::{self, Item, Level},
hud::{HudAtlas, HudBatch},
options_ui::{Event, Kind, Opt, OptionsUi, Page, apply_preset},
options_ui::{self, Event, Kind, Opt, OptionsUi, Page, apply_preset},
settings::{SOUND_SOURCES, Settings},
ui_theme::{self as t, CONTROL, Kind as Button, MenuStyle, ROW_LABEL, SIDEBAR, Ui, color, id},
};
@@ -659,12 +659,7 @@ impl OptionsUi {
/// settings go through `graphics_ui`.
fn set_item_slider(item: Item, s: &mut Settings, v: f32) {
match item {
Item::Vanilla(opt) => {
opt.set_slider(s, v);
if opt == Opt::Preset {
apply_preset(s);
}
}
Item::Vanilla(opt) => options_ui::set_slider(opt, s, v),
Item::Horizon(_) => item.set_slider(s, v),
}
}
+91 -16
View File
@@ -622,32 +622,53 @@ const PRESETS: [&str; 4] = ["fast", "fancy", "fabulous", "custom"];
fn preset_index(p: &str) -> usize {
PRESETS.iter().position(|x| *x == p).unwrap_or(1)
}
/// GraphicsPreset.apply: quality options for Fast/Fancy/Fabulous.
/// A slider moved to `v` (OptionInstance.set): the graphics preset applies
/// its options when its value changes (`Options.applyGraphicsPreset`).
pub fn set_slider(opt: Opt, s: &mut Settings, v: f32) {
let preset = preset_index(&s.graphics_preset);
opt.set_slider(s, v);
if opt == Opt::Preset && preset_index(&s.graphics_preset) != preset {
apply_preset(s);
}
}
/// GraphicsPreset.apply: the options Fast, Fancy and Fabulous set (texture
/// filtering and anisotropy have no option here yet).
pub fn apply_preset(s: &mut Settings) {
let fabulous = s.graphics_preset == "fabulous";
match s.graphics_preset.as_str() {
"fast" => {
s.biome_blend = 1;
s.render_distance = 8;
s.prioritize_chunk_updates = 0;
s.simulation_distance = 6;
s.smooth_lighting = false;
s.clouds = "fast".into();
s.particles = 1;
s.mipmap_levels = 2;
s.entity_shadows = false;
s.biome_blend = 1;
s.entity_distance = 0.75;
s.menu_blur = 2;
s.cloud_range = 32;
s.cutout_leaves = false;
s.improved_transparency = false;
s.mipmap_levels = 2;
s.weather_radius = 5;
s.cloud_range = 64;
s.entity_distance = 0.75;
}
"fancy" | "fabulous" => {
s.biome_blend = 2;
s.render_distance = if fabulous { 32 } else { 16 };
s.prioritize_chunk_updates = 1;
s.simulation_distance = 12;
s.smooth_lighting = true;
s.clouds = "true".into();
s.particles = 0;
s.entity_shadows = true;
s.biome_blend = 2;
s.cutout_leaves = true;
s.improved_transparency = s.graphics_preset == "fabulous";
s.mipmap_levels = 4;
s.entity_shadows = true;
s.entity_distance = if fabulous { 1.25 } else { 1.0 };
s.menu_blur = 5;
s.cloud_range = if fabulous { 128 } else { 64 };
s.cutout_leaves = true;
s.improved_transparency = fabulous;
s.weather_radius = 10;
s.cloud_range = 128;
s.entity_distance = 1.0;
}
_ => {}
}
@@ -1778,7 +1799,7 @@ impl OptionsUi {
.iter()
.find(|wd| matches!(&wd.kind, WKind::Slider { opt: o, .. } if *o == opt))
{
opt.set_slider(s, ui::slider_value(wd.x, wd.w, x));
set_slider(opt, s, ui::slider_value(wd.x, wd.w, x));
events.push(Event::Changed);
}
return events;
@@ -1861,10 +1882,7 @@ impl OptionsUi {
}
WKind::Slider { opt, .. } => {
self.dragging = Some(opt);
opt.set_slider(s, ui::slider_value(wd.x, wd.w, x));
if opt == Opt::Preset {
apply_preset(s);
}
set_slider(opt, s, ui::slider_value(wd.x, wd.w, x));
events.push(Event::Changed);
}
WKind::LanguageRow { code, .. } => {
@@ -2148,6 +2166,63 @@ mod tests {
}
}
#[test]
fn classic_graphics_presets_set_the_distances() {
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
ui.show(Page::Video);
let size = (480.0, 480.0);
let (widgets, _, _, _) = ui.layout(&s, size.0, size.1);
let preset = widgets
.iter()
.find(|wd| {
matches!(
wd.kind,
WKind::Slider {
opt: Opt::Preset,
..
}
)
})
.expect("the Graphics preset slider is in classic Video Settings");
// Dragging the slider across its range (GraphicsPreset.apply on each change).
let y = preset.y + 1.0;
let mut seen = Vec::new();
ui.click(
&mut s,
&atlas,
preset.x + 1.0,
y,
size,
[854, 480],
false,
false,
);
for step in 0..=20 {
let x = preset.x + preset.w * step as f32 / 20.0;
ui.click(&mut s, &atlas, x, y, size, [854, 480], true, false);
seen.push((
s.graphics_preset.clone(),
s.render_distance,
s.simulation_distance,
s.cloud_range,
));
}
ui.release();
for expected in [
("fast", 8, 6, 32),
("fancy", 16, 12, 64),
("fabulous", 32, 12, 128),
] {
assert!(
seen.iter()
.any(|(p, r, d, c)| (p.as_str(), *r, *d, *c) == expected),
"{expected:?} in {seen:?}"
);
}
}
#[test]
fn gui_scale_cycle_handles_reverse_and_out_of_range_saved_values() {
for (framebuffer, force_unicode, max) in [
+3 -2
View File
@@ -2107,8 +2107,8 @@ pub struct Level {
pub world_spawn: Option<[i32; 3]>,
pub difficulty: String,
pub hardcore: bool,
/// `allowCommands` chosen on the Create New World screen; unset keeps
/// the saved value (off for a new world).
/// `allowCommands`: read from `level.dat` or chosen on the Create New
/// World screen; unset is written as off.
pub allow_commands: Option<bool>,
/// Game rule values by name without namespace (`keep_inventory`, ...).
pub game_rules: BTreeMap<String, i32>,
@@ -2170,6 +2170,7 @@ impl Level {
level.difficulty = text(d.get("difficulty")).unwrap_or_else(|| "normal".into());
level.hardcore = n(d.get("hardcore")) != 0;
}
level.allow_commands = Some(n(data.get("allowCommands")) != 0);
let mut rules: BTreeMap<String, i32> = GAME_RULES
.iter()
.map(|(k, v)| ((*k).to_owned(), *v))
+1
View File
@@ -252,6 +252,7 @@ impl Sprites {
.and_then(|v| v.get("texture"))
.and_then(|v| serde_json::from_str::<serde_json::Value>(v.get()).ok());
self.mips.push(crate::mipmap::Settings {
native_size: side,
strategy: texture
.as_ref()
.and_then(|t| t["mipmap_strategy"].as_str())
+8
View File
@@ -81,6 +81,7 @@ struct MeshSettings {
blend_radius: i32,
smooth_lighting: bool,
cutout_leaves: bool,
cull_leaves: bool,
}
enum Job {
Generate(i32, i32),
@@ -183,6 +184,7 @@ pub struct Streaming {
/// The `ao` and `cutoutLeaves` options.
pub smooth_lighting: bool,
pub cutout_leaves: bool,
pub cull_leaves: bool,
/// Incremental relighting of block edits on lit chunks (see `light::relight`).
light_tables: Arc<LightTables>,
/// Applied edits by sequence, replayed onto light jobs snapshotted before them.
@@ -401,6 +403,7 @@ impl Streaming {
blend_radius: settings.blend_radius,
smooth_lighting: settings.smooth_lighting,
cutout_leaves: settings.cutout_leaves,
cull_leaves: settings.cull_leaves,
assets: &context.assets,
tables: &context.tables,
biomes: &context.biomes,
@@ -454,6 +457,7 @@ impl Streaming {
biome_blend: 2,
smooth_lighting: true,
cutout_leaves: true,
cull_leaves: false,
light_tables,
light_log: Vec::new(),
light_edit_sequence: 0,
@@ -615,6 +619,9 @@ impl Streaming {
pub fn is_lit(&self, x: i32, z: i32) -> bool {
self.lit.contains(&(x, z))
}
pub fn is_meshing(&self, section: (i32, i32, i32)) -> bool {
self.meshing.contains_key(&section)
}
pub fn pending(&self) -> usize {
self.shared.queue.lock().unwrap().len()
}
@@ -1005,6 +1012,7 @@ impl Streaming {
blend_radius: self.biome_blend,
smooth_lighting: self.smooth_lighting,
cutout_leaves: self.cutout_leaves,
cull_leaves: self.cull_leaves,
},
),
);
+1
View File
@@ -1020,6 +1020,7 @@ impl Title {
atlas,
batch,
(self.started.elapsed().as_millis() / 300).is_multiple_of(2),
cursor,
),
}
for b in self.buttons(w, h) {
@@ -210,6 +210,7 @@ fn relit_columns_keep_every_mesh_current() {
blend_radius: 2,
smooth_lighting: true,
cutout_leaves: true,
cull_leaves: false,
assets: &context.assets,
tables: &context.tables,
biomes: &context.biomes,
+3 -1
View File
@@ -233,4 +233,6 @@ is not under control.
Each PR adds its tests: unit tests next to the code, and scenarios in
`tools/agent_control_e2e.py` (`survival`, `ui`, `options`, `events`; CLI and MCP) and
`tools/launcher_mcp_e2e.py`, which drive the real game offscreen on macOS or on a virtual
screen on Linux.
screen on Linux. `tools/lan_e2e.py` runs two games at once, a host that opens its world to LAN
and a guest that joins it, and checks from both sides what a guest sees and can do (player
list, own model, armour, name tags, chest lids, crafting, fall damage).
+2 -2
View File
@@ -143,7 +143,7 @@ runs the game: GitHub's runners have neither a GPU worth the name nor the game f
`tools/release_train.py notes` writes them from the same pull requests:
- the title, `Horizon 2026.10.15.1: <the first pull request titles>`, features first, newest first;
- the title, `Horizon 2026.10.15.01: <the first pull request titles>` (a day's later releases count .01, .02…, two digits so GitHub's releases page, which sorts them as text, keeps them in order), features first, newest first;
- `### New` (label `feature`) and `### Fixed` (the rest), one line per pull request: its title, its number, the
issues it closes;
- `### Known issues`: the bullets of [docs/known-issues.md](known-issues.md);
@@ -177,7 +177,7 @@ While paused, runs still decide and say why in their summary; `force=true` still
A bad release is withdrawn by turning it back into a draft:
```sh
gh release edit v2026.10.15.1 --draft
gh release edit v2026.10.15.01 --draft
```
Launchers list only published releases: the previous version becomes the newest one again, launchers that
+1
View File
@@ -2673,6 +2673,7 @@ dependencies = [
"self-replace",
"serde",
"serde_json",
"sha1",
"tar",
"ureq",
"winresource",
+2
View File
@@ -12,6 +12,8 @@ gpui = "0.2.2"
ureq = { version = "2", features = ["json", "tls"], default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Checks the client jar and the version file found in other launchers' folders (sources.rs).
sha1 = "0.10"
pulldown-cmark = { version = "0.12", default-features = false }
flate2 = "1"
tar = { version = "0.4", default-features = false }
+6
View File
@@ -422,6 +422,12 @@ fn profile(ep: &Endpoints, token: &str) -> Result<Account, String> {
})
}
/// Whether the signed-in account still owns Minecraft: Java Edition, asked again now: the
/// launcher downloads the game's files only for an owner (sources.rs).
pub fn owns_minecraft(ep: &Endpoints, secrets: &Secrets) -> Result<bool, String> {
owns_game(ep, &secrets.minecraft_token)
}
/// What the keychain keeps for one account.
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Secrets {
+15
View File
@@ -275,6 +275,21 @@ fn refresh_only_when_the_token_runs_out() {
);
}
#[test]
fn ownership_is_asked_again_with_the_saved_token() {
let secrets = |token: &str| Secrets {
refresh_token: "ms-refresh-1".into(),
minecraft_token: token.into(),
minecraft_expires_at: now() + 7200,
xuid: None,
};
let (m, ep) = mock(|_| {});
assert_eq!(owns_minecraft(&ep, &secrets("mc-token")), Ok(true));
assert_eq!(m.lock().unwrap().log.len(), 1);
let (_, ep) = mock(|m| m.owns_game = false);
assert_eq!(owns_minecraft(&ep, &secrets("mc-token")), Ok(false));
}
#[test]
fn refusals_have_messages() {
let tokens = || MsTokens {
+103 -25
View File
@@ -1,6 +1,7 @@
//! Everything that is not UI: GitHub, installs, resource preparation, the game's processes and
//! updates. The GUI, the CLI and the MCP server all go through this module. Functions here
//! block; the GUI runs them on threads and reads their messages.
use crate::{account, mojang, sources};
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
@@ -594,17 +595,14 @@ fn reuse_prepared_in(versions: &Path) -> Vec<(String, String)> {
.collect()
}
/// The official launcher's game directory, where horizon-prepare looks by default.
/// The official launcher's game directory, else the first other launcher's found
/// (sources.rs); preparing looks in all of them anyway.
pub fn default_minecraft_dir() -> Option<PathBuf> {
let home = dirs::home_dir()?;
let dir = if cfg!(target_os = "macos") {
home.join("Library/Application Support/minecraft")
} else if cfg!(windows) {
dirs::config_dir()?.join(".minecraft")
} else {
home.join(".minecraft")
};
dir.is_dir().then_some(dir)
let folders = sources::Folders::current()?;
sources::known_folders(sources::Os::current(), &folders)
.into_iter()
.map(|(_, dir)| dir)
.find(|dir| dir.is_dir())
}
fn found(program: &str, arg: &str) -> bool {
@@ -644,23 +642,102 @@ fn preparer_binary(dir: &Path) -> Option<PathBuf> {
binary.is_file().then_some(binary)
}
/// Downloads the pinned version from Mojang into `dir` when the signed-in account owns
/// Minecraft (asked again now), else says what signing in would do, as the last line of the
/// not-found error.
fn download_for_owner(
pins: &sources::Pins,
dir: &Path,
fetch: sources::Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
let v = &pins.version;
let owner = (|| -> Result<Option<(String, bool)>, String> {
let ep = account::Endpoints::live();
let mut accounts = account::Accounts::load();
let Some((a, secrets)) = account::session_for_launch(&ep, account::store(), &mut accounts)?
else {
return Ok(None);
};
Ok(Some((a.name, account::owns_minecraft(&ep, &secrets)?)))
})();
match owner {
Ok(Some((name, true))) => {
log(format!(
"{name} owns Minecraft: downloading {v} from Mojang"
));
let os = match sources::Os::current() {
sources::Os::Linux => "linux",
sources::Os::MacOs => "osx",
sources::Os::Windows => "windows",
};
mojang::download(pins, dir, os, 8, fetch, log).map_err(|e| {
format!("\n • Horizon tried to download {v} from Mojang for {name}, but: {e}")
})
}
Ok(Some((name, false))) => Err(format!(
"\n • {name}, the signed-in account, doesn't own Minecraft: Java Edition, so Horizon \
can't download it."
)),
Ok(None) => Err(format!(
"\n • Or sign in with the Microsoft account that owns Minecraft: Horizon then \
downloads {v} from Mojang itself."
)),
Err(e) => Err(format!(
"\n • Downloading {v} from Mojang needs your Microsoft account, which could not be \
checked: {e}"
)),
}
}
/// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same
/// steps: the player's own launcher install, the server jar from that version's own json, and
/// Java (and Python, for versions before horizon-prepare).
pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result<Preparer, String> {
/// Java (and Python, for versions before horizon-prepare). Also returns the Minecraft folder
/// to prepare from: `minecraft`, or the files another launcher keeps, linked into the official
/// launcher's layout (sources.rs).
pub fn preparer(
tag: &str,
minecraft: &Path,
log: &dyn Fn(String),
) -> Result<(Preparer, PathBuf), String> {
let version = game_version(tag);
let dir = version_dir(tag);
let reused = horizon_prepare::artifacts::reuse_imported(&dir, &|line| log(line.to_string()))?;
let minecraft = if reused {
minecraft.to_path_buf()
} else {
let pins = read_json(&dir.join("research-lock.json"))
.and_then(|lock| sources::Pins::read(&lock))
.ok_or("The version's research-lock.json doesn't pin the Minecraft files")?;
let own = data_dir().join("minecraft");
let mut known = vec![("Horizon's own download", own.clone())];
known.extend(
sources::Folders::current()
.map(|f| sources::known_folders(sources::Os::current(), &f))
.unwrap_or_default(),
);
let fetch = |url: &str| -> Result<Vec<u8>, String> {
let mut body = Vec::new();
get(url)?
.into_reader()
.read_to_end(&mut body)
.map_err(|e| e.to_string())?;
Ok(body)
};
let linked = data_dir().join("linked-minecraft");
match sources::resolve(minecraft, &pins, &known, &linked, &fetch, log)? {
sources::Resolved::Folder(dir) => dir,
sources::Resolved::NotFound(checked) => {
let not_found = sources::not_found(&version, &checked);
download_for_owner(&pins, &own, &fetch, log).map_err(|e| not_found + &e)?;
own
}
}
};
let manifest = minecraft
.join("versions")
.join(&version)
.join(format!("{version}.json"));
if !reused && !manifest.exists() {
return Err(format!(
"Minecraft {version} is not in {}. Play {version} once from the official launcher, or choose another folder.",
minecraft.display()
));
}
let binary = preparer_binary(&dir);
let python = if binary.is_some() {
// The JDK the version pins, found as horizon-prepare finds it, so a missing one is
@@ -707,20 +784,21 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result<Pre
if horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref()
== Some(horizon_prepare::SOURCES_SHA256)
{
return Ok(Preparer::InProcess(horizon_prepare::Options {
let options = horizon_prepare::Options {
root: dir,
import: !reused,
minecraft_dir: Some(minecraft.to_path_buf()),
minecraft_dir: Some(minecraft.clone()),
server_jar: (!reused).then_some(jar),
}));
};
return Ok((Preparer::InProcess(options), minecraft));
}
let mut cmd = Command::new(binary);
cmd.current_dir(&dir).arg("--root").arg(&dir);
if !reused {
cmd.args(["--prepare", "--server-jar"]).arg(&jar);
}
cmd.arg("--minecraft-dir").arg(minecraft);
return Ok(Preparer::Process(cmd));
cmd.arg("--minecraft-dir").arg(&minecraft);
return Ok((Preparer::Process(cmd), minecraft));
}
let mut cmd = Command::new(python.unwrap());
cmd.current_dir(&dir)
@@ -728,8 +806,8 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result<Pre
if !reused {
cmd.args(["--prepare", "--server-jar"]).arg(&jar);
}
cmd.arg("--minecraft-dir").arg(minecraft);
Ok(Preparer::Process(cmd))
cmd.arg("--minecraft-dir").arg(&minecraft);
Ok((Preparer::Process(cmd), minecraft))
}
/// Copies the pinned version's sounds from the player's own launcher install into the version's
+4 -2
View File
@@ -90,7 +90,8 @@ enum Cmd {
Remove { tag: String },
/// Prepare a version's resources from your own Minecraft install
Prepare {
/// The official launcher's game folder (default: the one the launcher uses)
/// The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App,
/// ATLauncher or GDLauncher (default: the launcher's, then every launcher's default)
#[arg(long)]
minecraft: Option<PathBuf>,
/// The installed version (default: the selected one)
@@ -299,7 +300,8 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
Cmd::Prepare { minecraft, version } => {
let tag = backend::resolve_version(version.as_deref())?;
let minecraft = backend::minecraft_dir(minecraft)?;
let preparer = backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
let (preparer, minecraft) =
backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
backend::sounds(&tag, &minecraft, &|line| println!("{line}"));
match preparer {
backend::Preparer::Process(cmd) => attached(cmd)?,
+2
View File
@@ -2,4 +2,6 @@
pub mod account;
pub mod backend;
pub mod desktop;
pub mod mojang;
pub mod sources;
pub mod telemetry;
+11 -5
View File
@@ -501,9 +501,15 @@ impl Launcher {
if let (None, Some(started)) = (&error, self.prepare_started.take()) {
self.perf.record_since("launcher.prepare_ms", started);
}
// A preparer process's exit status says little, so its last line
// follows; the launcher's own errors are full sentences already.
self.prepare_error = error.map(|e| {
let tail =
self.prepare_log.iter().rev().find(|l| !l.trim().is_empty());
let tail = self
.prepare_log
.iter()
.rev()
.find(|l| !l.trim().is_empty())
.filter(|_| e.starts_with("Exited with"));
tail.map_or(e.clone(), |t| format!("{e}: {t}"))
});
}
@@ -632,8 +638,8 @@ impl Launcher {
let _ = tx.send(Msg::Line(Job::Prepare, line));
};
let result = backend::preparer(&tag, &minecraft, &log)
.inspect(|_| backend::sounds(&tag, &minecraft, &log))
.and_then(|p| match p {
.inspect(|(_, minecraft)| backend::sounds(&tag, minecraft, &log))
.and_then(|(p, _)| match p {
backend::Preparer::Process(cmd) => {
backend::spawn(Job::Prepare, cmd, tx.clone()).map(|_running| false)
}
@@ -1436,7 +1442,7 @@ impl Launcher {
let minecraft = self.settings.minecraft_dir.as_deref().map_or_else(
|| {
div()
.child("Not found. Choose the official launcher's game folder.")
.child("Not found. Choose the folder where your launcher keeps Minecraft.")
.into_any_element()
},
|p| {
+2 -2
View File
@@ -32,7 +32,7 @@ fn tools() -> Value {
{ "name": "remove_version", "description": "Remove an installed Horizon version and its prepared resources.",
"inputSchema": { "type": "object", "properties": { "tag": { "type": "string" } }, "required": ["tag"] } },
{ "name": "prepare_resources", "description": "Prepare a version's resources from the player's own Minecraft install (needs Minecraft 26.3 played once in the official launcher and Java 25; versions before horizon-prepare also need Python 3.10+). Can take several minutes; returns the end of the log.",
"inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The official launcher's game folder. Default: the launcher's setting, else the platform default." } } } },
"inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher. Default: the launcher's setting, then every launcher's default folder." } } } },
{ "name": "launch_client", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world.",
"inputSchema": { "type": "object", "properties": { "version": version,
"world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." },
@@ -120,7 +120,7 @@ impl Session {
let tag = backend::resolve_version(arg_str(args, "version"))?;
let minecraft =
backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?;
let preparer = backend::preparer(&tag, &minecraft, &|_| {})?;
let (preparer, minecraft) = backend::preparer(&tag, &minecraft, &|_| {})?;
let sound = std::cell::RefCell::new(Vec::new());
backend::sounds(&tag, &minecraft, &|line| sound.borrow_mut().push(line));
let (result, tail) = match preparer {
+194
View File
@@ -0,0 +1,194 @@
//! The player's own download of the pinned version from Mojang, for a signed-in account that
//! owns Minecraft: Java Edition (#434), as other launchers get it: the version JSON, the client
//! jar, this system's libraries and the assets (the sounds), each checked against its sha1,
//! in the official launcher's layout in the launcher's data folder. sources.rs then finds them
//! there like any launcher's. Nothing of Mojang's is part of Horizon.
use crate::sources::{fetch_checked, fetch_manifest, sha1_file, write_file, Fetch, Pins};
use serde_json::Value;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use std::sync::Mutex;
use std::time::Duration;
const OBJECTS: &str = "https://resources.download.minecraft.net";
/// One file to download.
struct File {
url: String,
sha1: String,
path: PathBuf,
}
/// Downloads the pinned version into `dir`, `jobs` files at a time; files already there and
/// whole are kept. An asset that fails is a line in the log (the game is then partly silent),
/// anything else an error.
pub fn download(
pins: &Pins,
dir: &Path,
os: &str,
jobs: usize,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
let v = &pins.version;
let versions = dir.join("versions").join(v);
let manifest = versions.join(format!("{v}.json"));
fetch_manifest(pins, &manifest, fetch, log)?;
let manifest = read_json(&manifest)?;
let client = &manifest["downloads"]["client"];
let mut game = vec![File {
url: text(client, "url")?,
sha1: pins.client_sha1.clone(),
path: versions.join(format!("{v}.jar")),
}];
let libraries = manifest["libraries"]
.as_array()
.ok_or("The version file has no libraries")?;
for library in libraries.iter().filter(|l| allowed(l, os)) {
let artifact = &library["downloads"]["artifact"];
if artifact.is_null() {
continue;
}
game.push(File {
url: text(artifact, "url")?,
sha1: text(artifact, "sha1")?,
path: dir
.join("libraries")
.join(relative(&text(artifact, "path")?)?),
});
}
log(format!(
"Downloading Minecraft {v} from Mojang: the game and {} libraries",
game.len() - 1
));
fetch_all(&game, jobs, fetch, log)?;
let index = &manifest["assetIndex"];
let index = File {
url: text(index, "url")?,
sha1: text(index, "sha1")?,
path: dir
.join("assets/indexes")
.join(relative(&format!("{}.json", text(index, "id")?))?),
};
let assets = fetch_all(std::slice::from_ref(&index), 1, fetch, log)
.and_then(|_| objects(&read_json(&index.path)?, dir))
.and_then(|objects| {
log(format!("Downloading the sounds ({} files)", objects.len()));
fetch_all(&objects, jobs, fetch, log)
});
if let Err(e) = assets {
log(format!("The sounds could not all be downloaded: {e}"));
}
Ok(())
}
fn read_json(path: &Path) -> Result<Value, String> {
let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
}
fn text(v: &Value, key: &str) -> Result<String, String> {
v[key]
.as_str()
.map(String::from)
.ok_or_else(|| format!("The version file has no {key} in {v}"))
}
/// A path from the version file, refused if it could leave the folder.
fn relative(path: &str) -> Result<PathBuf, String> {
let safe = !path.contains('\\')
&& Path::new(path)
.components()
.all(|c| matches!(c, Component::Normal(_)));
safe.then(|| PathBuf::from(path))
.ok_or_else(|| format!("Unsafe path {path:?} in the version file"))
}
/// Whether a library's rules let this system (`osx`, `windows`, `linux`) use it: the last
/// rule that matches decides.
fn allowed(library: &Value, os: &str) -> bool {
let Some(rules) = library["rules"].as_array() else {
return true;
};
rules
.iter()
.rfind(|rule| rule["os"]["name"].as_str().is_none_or(|name| name == os))
.is_some_and(|rule| rule["action"] == "allow")
}
/// The asset index's objects, once each.
fn objects(index: &Value, dir: &Path) -> Result<Vec<File>, String> {
let objects = index["objects"]
.as_object()
.ok_or("The asset index has no objects")?;
let mut hashes: Vec<&str> = objects
.values()
.filter_map(|o| o["hash"].as_str())
.collect();
hashes.sort_unstable();
hashes.dedup();
hashes
.into_iter()
.map(|hash| {
if hash.len() != 40 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(format!("Bad asset hash {hash:?} in the asset index"));
}
let path = format!("{}/{hash}", &hash[..2]);
Ok(File {
url: format!("{OBJECTS}/{path}"),
sha1: hash.to_string(),
path: dir.join("assets/objects").join(path),
})
})
.collect()
}
/// Downloads the files not already there, `jobs` at a time, with a line every few seconds;
/// stops at the first error.
fn fetch_all(
files: &[File],
jobs: usize,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
let next = AtomicUsize::new(0);
let done = AtomicUsize::new(0);
let failed = Mutex::new(None);
std::thread::scope(|scope| {
let workers: Vec<_> = (0..jobs.clamp(1, files.len().max(1)))
.map(|_| {
scope.spawn(|| {
while let Some(file) = files.get(next.fetch_add(1, Relaxed)) {
if failed.lock().unwrap().is_some() {
break;
}
if sha1_file(&file.path).as_ref() != Some(&file.sha1) {
let got = fetch_checked(fetch, &file.url, &file.sha1)
.map_err(|e| format!("{} {e}", file.url))
.and_then(|body| write_file(&file.path, &body));
if let Err(e) = got {
failed.lock().unwrap().get_or_insert(e);
}
}
done.fetch_add(1, Relaxed);
}
})
})
.collect();
let mut waited = 0;
while !workers.iter().all(|w| w.is_finished()) {
std::thread::sleep(Duration::from_millis(100));
waited += 1;
if waited % 50 == 0 {
log(format!("{} of {} files", done.load(Relaxed), files.len()));
}
}
});
failed.into_inner().unwrap().map_or(Ok(()), Err)
}
#[cfg(test)]
#[path = "mojang_tests.rs"]
mod tests;
+232
View File
@@ -0,0 +1,232 @@
//! A download from a mock of Mojang's servers serving small fake files (never Mojang's).
use super::*;
use crate::sources::{resolve, sha1_hex, Resolved};
use std::collections::HashMap;
const CLIENT: &[u8] = b"fake client jar";
const COMMON: &[u8] = b"a library every system uses";
const LINUX: &[u8] = b"a linux native";
const SOUND: &[u8] = b"a fake ogg";
const LANG: &[u8] = b"{}";
/// The fake version file, asset index and files, by URL.
fn mojang() -> (Pins, HashMap<String, Vec<u8>>) {
let artifact = |name: &str, data: &[u8]| {
serde_json::json!({
"path": format!("org/fake/{name}/1/{name}-1.jar"),
"sha1": sha1_hex(data),
"url": format!("https://libraries.minecraft.net/org/fake/{name}/1/{name}-1.jar"),
})
};
let index = serde_json::json!({"objects": {
"minecraft/sounds/a.ogg": {"hash": sha1_hex(SOUND), "size": SOUND.len()},
"minecraft/sounds/same.ogg": {"hash": sha1_hex(SOUND), "size": SOUND.len()},
"minecraft/lang/fr_fr.json": {"hash": sha1_hex(LANG), "size": LANG.len()},
}})
.to_string();
let manifest = serde_json::json!({
"id": "26.3",
"assetIndex": {"id": "34", "sha1": sha1_hex(index.as_bytes()),
"url": "https://piston-meta.mojang.com/v1/packages/i/34.json"},
"downloads": {"client": {"sha1": sha1_hex(CLIENT), "url": "https://piston-data.mojang.com/client.jar"}},
"libraries": [
{"name": "org.fake:common:1", "downloads": {"artifact": artifact("common", COMMON)}},
{"name": "org.fake:linux:1", "downloads": {"artifact": artifact("linux", LINUX)},
"rules": [{"action": "allow", "os": {"name": "linux"}}]},
{"name": "org.fake:not-osx:1", "downloads": {"artifact": artifact("not-osx", COMMON)},
"rules": [{"action": "allow"}, {"action": "disallow", "os": {"name": "osx"}}]},
{"name": "org.fake:windows:1", "downloads": {"artifact": artifact("windows", b"w")},
"rules": [{"action": "allow", "os": {"name": "windows"}}]},
],
})
.to_string();
let pins = Pins::read(&serde_json::json!({"minecraft": {
"version": "26.3",
"client_sha1": sha1_hex(CLIENT),
"manifest_sha1": sha1_hex(manifest.as_bytes()),
}}))
.unwrap();
let object = |data: &[u8]| {
let hash = sha1_hex(data);
format!("{OBJECTS}/{}/{hash}", &hash[..2])
};
let lib =
|name: &str| format!("https://libraries.minecraft.net/org/fake/{name}/1/{name}-1.jar");
let files = HashMap::from([
(
format!(
"https://piston-meta.mojang.com/v1/packages/{}/26.3.json",
sha1_hex(manifest.as_bytes())
),
manifest.into_bytes(),
),
(
"https://piston-data.mojang.com/client.jar".into(),
CLIENT.to_vec(),
),
(lib("common"), COMMON.to_vec()),
(lib("linux"), LINUX.to_vec()),
(lib("not-osx"), COMMON.to_vec()),
(lib("windows"), b"w".to_vec()),
(
"https://piston-meta.mojang.com/v1/packages/i/34.json".into(),
index.into_bytes(),
),
(object(SOUND), SOUND.to_vec()),
(object(LANG), LANG.to_vec()),
]);
(pins, files)
}
struct Server {
files: HashMap<String, Vec<u8>>,
asked: Mutex<Vec<String>>,
}
impl Server {
fn fetch(&self, url: &str) -> Result<Vec<u8>, String> {
self.asked.lock().unwrap().push(url.to_string());
self.files
.get(url)
.cloned()
.ok_or_else(|| format!("{url} answered 404"))
}
fn asked(&self) -> Vec<String> {
std::mem::take(&mut *self.asked.lock().unwrap())
}
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("horizon-mojang-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
dir
}
#[test]
fn an_owner_gets_the_official_layout_with_this_systems_libraries() {
let (pins, files) = mojang();
let server = Server {
files,
asked: Mutex::new(Vec::new()),
};
let dir = scratch("layout");
let logged = Mutex::new(Vec::new());
download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|line| {
logged.lock().unwrap().push(line)
})
.unwrap();
assert_eq!(
fs::read(dir.join("versions/26.3/26.3.jar")).unwrap(),
CLIENT
);
let libraries = dir.join("libraries/org/fake");
assert_eq!(
fs::read(libraries.join("common/1/common-1.jar")).unwrap(),
COMMON
);
assert_eq!(
fs::read(libraries.join("linux/1/linux-1.jar")).unwrap(),
LINUX
);
assert!(libraries.join("not-osx/1/not-osx-1.jar").is_file());
assert!(!libraries.join("windows").exists());
let hash = sha1_hex(SOUND);
assert_eq!(
fs::read(dir.join("assets/objects").join(&hash[..2]).join(&hash)).unwrap(),
SOUND
);
assert!(dir.join("assets/indexes/34.json").is_file());
let asked = server.asked();
// The sound two names share is fetched once; nothing is fetched twice.
assert_eq!(asked.len(), 8, "{asked:#?}");
assert!(!asked.iter().any(|u| u.contains("windows")));
assert_eq!(
logged.lock().unwrap()[1],
"Downloading Minecraft 26.3 from Mojang: the game and 3 libraries"
);
// Found like any launcher's folder, as it is; a second download fetches nothing.
let found = resolve(
&dir,
&pins,
&[],
&scratch("unused"),
&|url| server.fetch(url),
&|_| {},
);
assert_eq!(found, Ok(Resolved::Folder(dir.clone())));
download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|_| {}).unwrap();
assert_eq!(server.asked(), Vec::<String>::new());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn macos_skips_what_its_rules_disallow() {
let (pins, files) = mojang();
let server = Server {
files,
asked: Mutex::new(Vec::new()),
};
let dir = scratch("osx");
download(&pins, &dir, "osx", 2, &|url| server.fetch(url), &|_| {}).unwrap();
let libraries = dir.join("libraries/org/fake");
assert!(libraries.join("common/1/common-1.jar").is_file());
assert!(!libraries.join("linux").exists());
assert!(!libraries.join("not-osx").exists());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_file_that_is_not_the_pinned_one_stops_the_download() {
let (pins, mut files) = mojang();
files.insert(
"https://piston-data.mojang.com/client.jar".into(),
b"something else".to_vec(),
);
let server = Server {
files,
asked: Mutex::new(Vec::new()),
};
let dir = scratch("bad-jar");
let error = download(&pins, &dir, "linux", 2, &|url| server.fetch(url), &|_| {}).unwrap_err();
assert!(
error.starts_with("https://piston-data.mojang.com/client.jar is not the one Horizon pins"),
"{error}"
);
assert!(!dir.join("versions/26.3/26.3.jar").exists());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn missing_sounds_are_a_line_in_the_log_not_an_error() {
let (pins, mut files) = mojang();
let hash = sha1_hex(SOUND);
files.remove(&format!("{OBJECTS}/{}/{hash}", &hash[..2]));
let server = Server {
files,
asked: Mutex::new(Vec::new()),
};
let dir = scratch("no-sound");
let logged = Mutex::new(Vec::new());
download(&pins, &dir, "linux", 1, &|url| server.fetch(url), &|line| {
logged.lock().unwrap().push(line)
})
.unwrap();
assert!(dir.join("versions/26.3/26.3.jar").is_file());
let last = logged.lock().unwrap().last().cloned().unwrap();
assert!(
last.starts_with("The sounds could not all be downloaded:")
&& last.ends_with("answered 404"),
"{last}"
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn version_file_paths_stay_in_the_folder() {
assert!(relative("org/fake/a.jar").is_ok());
for bad in ["../a.jar", "/etc/a", "a/../../b", "a\\b"] {
assert!(relative(bad).is_err(), "{bad}");
}
}
+449
View File
@@ -0,0 +1,449 @@
//! Where the player's own Minecraft files are: the folder they chose, the official launcher's,
//! or another launcher's (Prism Launcher, MultiMC, Modrinth App, ATLauncher, GDLauncher), #434.
//! horizon-prepare reads the official launcher's layout and pins the version JSON's own sha1, so
//! files found elsewhere are linked into that layout in the launcher's data folder, with the
//! pinned version JSON from Mojang when the other launcher keeps its own rewrite of it.
use serde_json::Value;
use sha1::{Digest, Sha1};
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
/// What a version's research-lock.json pins about the game files.
pub struct Pins {
pub version: String,
pub client_sha1: String,
/// The version JSON's sha1, then the earlier ones Mojang republished.
pub manifests: Vec<String>,
}
impl Pins {
pub fn read(lock: &Value) -> Option<Pins> {
let game = &lock["minecraft"];
let text = |key: &str| game[key].as_str().map(String::from);
let mut manifests = vec![text("manifest_sha1")?];
if let Some(list) = game["accepted_manifest_sha1"].as_array() {
manifests.extend(list.iter().filter_map(Value::as_str).map(String::from));
}
Some(Pins {
version: text("version")?,
client_sha1: text("client_sha1")?,
manifests,
})
}
fn manifest_accepted(&self, path: &Path) -> bool {
sha1_file(path).is_some_and(|sha1| self.manifests.contains(&sha1))
}
}
/// A launcher's copy of the pinned version.
#[derive(Debug, PartialEq)]
pub struct Found {
/// The folder holding the launcher's `libraries` and `assets`.
pub base: PathBuf,
/// The client jar, checked against the pin.
pub client: PathBuf,
/// The launcher's version JSON when it is one Horizon pins.
pub manifest: Option<PathBuf>,
}
impl Found {
/// Whether `base` is in the official launcher's layout, so horizon-prepare reads it as is.
fn official_layout(&self, version: &str) -> bool {
let dir = self.base.join("versions").join(version);
self.client == dir.join(format!("{version}.jar"))
&& self.manifest == Some(dir.join(format!("{version}.json")))
}
}
pub struct Folders {
pub home: PathBuf,
/// `dirs::data_dir()`: ~/.local/share (XDG_DATA_HOME), ~/Library/Application Support,
/// %APPDATA%.
pub data: PathBuf,
/// `dirs::config_dir()`: ~/.config (XDG_CONFIG_HOME), the same as `data` elsewhere.
pub config: PathBuf,
}
impl Folders {
pub fn current() -> Option<Folders> {
Some(Folders {
home: dirs::home_dir()?,
data: dirs::data_dir()?,
config: dirs::config_dir()?,
})
}
}
#[derive(Clone, Copy, PartialEq)]
pub enum Os {
Linux,
MacOs,
Windows,
}
impl Os {
pub fn current() -> Os {
if cfg!(target_os = "macos") {
Os::MacOs
} else if cfg!(windows) {
Os::Windows
} else {
Os::Linux
}
}
}
const OFFICIAL: &str = "the official launcher";
/// Every launcher's default game folder on `os`, the official launcher's first. MultiMC on
/// macOS and Windows has none (it lives where it was unzipped): it is chosen by hand.
pub fn known_folders(os: Os, f: &Folders) -> Vec<(&'static str, PathBuf)> {
let flatpak = |app: &str, rest: &str| f.home.join(".var/app").join(app).join(rest);
let mut list = match os {
Os::Linux => vec![
(OFFICIAL, f.home.join(".minecraft")),
(OFFICIAL, flatpak("com.mojang.Minecraft", ".minecraft")),
("Prism Launcher", f.data.join("PrismLauncher")),
(
"Prism Launcher",
flatpak("org.prismlauncher.PrismLauncher", "data/PrismLauncher"),
),
("MultiMC", f.data.join("multimc")),
("Modrinth App", f.data.join("ModrinthApp")),
(
"Modrinth App",
flatpak("com.modrinth.ModrinthApp", "data/ModrinthApp"),
),
("ATLauncher", f.data.join("atlauncher")),
(
"ATLauncher",
flatpak("com.atlauncher.ATLauncher", "data/atlauncher"),
),
],
Os::MacOs => vec![
(OFFICIAL, f.data.join("minecraft")),
("Prism Launcher", f.data.join("PrismLauncher")),
("MultiMC", f.data.join("MultiMC")),
("Modrinth App", f.data.join("ModrinthApp")),
("ATLauncher", f.data.join("ATLauncher")),
],
Os::Windows => vec![
(OFFICIAL, f.data.join(".minecraft")),
("Prism Launcher", f.data.join("PrismLauncher")),
("Modrinth App", f.data.join("ModrinthApp")),
("ATLauncher", f.data.join("ATLauncher")),
],
};
// Names every system shares: the Modrinth App before its rename, GDLauncher and its
// previous version (GDLauncher Next).
list.extend([
("Modrinth App", f.data.join("com.modrinth.theseus")),
("GDLauncher", f.data.join("gdlauncher_carbon")),
("GDLauncher", f.config.join("gdlauncher_next")),
]);
list
}
/// The client jar's path in a Maven repository: `com.mojang:minecraft:26.3:client` is
/// `com/mojang/minecraft/26.3/minecraft-26.3-client.jar`.
pub fn maven_path(name: &str) -> Option<String> {
let (name, extension) = name.split_once('@').unwrap_or((name, "jar"));
let parts: Vec<&str> = name.split(':').collect();
let (group, artifact, version) = match parts[..] {
[group, artifact, version] | [group, artifact, version, _] => (group, artifact, version),
_ => return None,
};
let classifier = parts.get(3).map(|c| format!("-{c}")).unwrap_or_default();
let unsafe_part = |p: &str| p.is_empty() || p.contains(['/', '\\']) || p.contains("..");
if parts.iter().any(|p| unsafe_part(p)) || unsafe_part(extension) {
return None;
}
Some(format!(
"{}/{artifact}/{version}/{artifact}-{version}{classifier}.{extension}",
group.replace('.', "/")
))
}
/// The client jar Prism Launcher's and MultiMC's metadata name (`meta/net.minecraft/<v>.json`,
/// their own format, `mainJar` a Maven name in `libraries`).
fn meta_client_jar(base: &Path, version: &str) -> Option<String> {
let meta = fs::read_to_string(base.join(format!("meta/net.minecraft/{version}.json"))).ok()?;
let meta: Value = serde_json::from_str(&meta).ok()?;
maven_path(meta["mainJar"]["name"].as_str()?).map(|path| format!("libraries/{path}"))
}
/// Where launchers keep the client jar, relative to the folder holding their `libraries`.
fn client_jars(base: &Path, version: &str) -> Vec<String> {
let v = version;
let mut jars: Vec<String> = meta_client_jar(base, v).into_iter().collect();
for jar in [
// The official launcher; the Modrinth App, in meta/.
format!("versions/{v}/{v}.jar"),
// Prism Launcher and MultiMC.
format!("libraries/com/mojang/minecraft/{v}/minecraft-{v}-client.jar"),
// ATLauncher and GDLauncher.
format!("libraries/net/minecraft/client/{v}/client-{v}.jar"),
] {
if !jars.contains(&jar) {
jars.push(jar);
}
}
jars
}
pub(crate) fn sha1_file(path: &Path) -> Option<String> {
let mut file = fs::File::open(path).ok()?;
let mut hash = Sha1::new();
let mut buffer = vec![0; 1 << 20];
loop {
match file.read(&mut buffer).ok()? {
0 => break,
n => hash.update(&buffer[..n]),
}
}
Some(hash.finalize().iter().map(|b| format!("{b:02x}")).collect())
}
/// The pinned version in one launcher folder, or what the folder lacks. The folder holding
/// `libraries` is the folder itself or its `meta` (Modrinth App), `data` (GDLauncher) or
/// `datastore` (GDLauncher Next).
pub fn find(dir: &Path, pins: &Pins) -> Result<Found, String> {
if !dir.is_dir() {
return Err("the folder doesn't exist".into());
}
let v = &pins.version;
let mut other = None;
let bases = [dir.to_path_buf()]
.into_iter()
.chain(["meta", "data", "datastore"].map(|sub| dir.join(sub)));
for base in bases {
for jar in client_jars(&base, v) {
let client = base.join(&jar);
if !client.is_file() {
continue;
}
if sha1_file(&client).as_ref() != Some(&pins.client_sha1) {
other.get_or_insert(client);
continue;
}
let manifest = base.join(format!("versions/{v}/{v}.json"));
let manifest = pins.manifest_accepted(&manifest).then_some(manifest);
return Ok(Found {
base,
client,
manifest,
});
}
}
Err(match other {
Some(jar) => format!(
"{} is not the {v} release Horizon was made for",
jar.strip_prefix(dir).unwrap_or(&jar).display()
),
None => format!("no Minecraft {v} client jar"),
})
}
/// The error when no folder has the pinned version: every folder looked in with what it
/// lacks, and what the player can do about it (#419).
pub fn not_found(version: &str, checked: &[(PathBuf, String)]) -> String {
let mut text = format!("Minecraft {version} was not found. Horizon looked in:");
for (dir, missing) in checked {
text += &format!("\n {} ({missing})", dir.display());
}
text += &format!(
"\nTo fix it:\n \
• Play {version} once in the official Minecraft launcher, or in Prism Launcher, MultiMC, \
the Modrinth App, ATLauncher or GDLauncher, then prepare again.\n \
• Or choose the folder where your launcher keeps Minecraft {version} (Minecraft folder › \
Choose… in the launcher, --minecraft on the command line)."
);
text
}
/// Fetches a URL's body (from several threads for a download).
pub type Fetch<'a> = &'a (dyn Fn(&str) -> Result<Vec<u8>, String> + Sync);
/// Where the pinned version is.
#[derive(Debug, PartialEq)]
pub enum Resolved {
/// A folder in the official launcher's layout.
Folder(PathBuf),
/// In none of these folders; each with what it lacks.
NotFound(Vec<(PathBuf, String)>),
}
/// A Minecraft folder in the official launcher's layout holding the pinned version: the
/// chosen folder when it is one, else the files found in the chosen folder (or a folder above
/// it: a launcher's instance folder may be chosen) or any launcher's default folder, linked into
/// `linked`.
pub fn resolve(
chosen: &Path,
pins: &Pins,
known: &[(&'static str, PathBuf)],
linked: &Path,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<Resolved, String> {
let mut checked = Vec::new();
let mut found = None;
for dir in chosen.ancestors().take(4) {
match find(dir, pins) {
Ok(f) => {
found = Some(("the chosen folder", f));
break;
}
Err(missing) if dir == chosen => checked.push((dir.to_path_buf(), missing)),
Err(_) => {}
}
}
let same = |a: &Path, b: &Path| a == b || fs::canonicalize(a).ok() == fs::canonicalize(b).ok();
for (name, dir) in known.iter().filter(|(_, d)| d.is_dir() && !same(d, chosen)) {
if found.is_some() {
break;
}
match find(dir, pins) {
Ok(f) => found = Some((name, f)),
Err(missing) => checked.push((dir.clone(), format!("{name}: {missing}"))),
}
}
let Some((name, found)) = found else {
return Ok(Resolved::NotFound(checked));
};
log(format!(
"Using Minecraft {} from {name} ({})",
pins.version,
found.base.display()
));
if found.official_layout(&pins.version) {
return Ok(Resolved::Folder(found.base));
}
link_official_layout(&found, pins, linked, fetch, log)?;
Ok(Resolved::Folder(linked.to_path_buf()))
}
/// The pinned version JSON at `path`, from piston-meta (by its sha1) unless it is there.
pub(crate) fn fetch_manifest(
pins: &Pins,
path: &Path,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
if pins.manifest_accepted(path) {
return Ok(());
}
let (v, sha1) = (&pins.version, &pins.manifests[0]);
log(format!("Downloading the {v} version file from Mojang"));
let url = format!("https://piston-meta.mojang.com/v1/packages/{sha1}/{v}.json");
let body =
fetch_checked(fetch, &url, sha1).map_err(|e| format!("Mojang's {v} version file {e}"))?;
write_file(path, &body)
}
pub(crate) fn sha1_hex(data: &[u8]) -> String {
Sha1::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
/// A download checked against its sha1; the error says how it differs.
pub(crate) fn fetch_checked(fetch: Fetch, url: &str, sha1: &str) -> Result<Vec<u8>, String> {
let body = fetch(url)?;
match sha1_hex(&body) {
actual if actual == sha1 => Ok(body),
actual => Err(format!("is not the one Horizon pins (sha1 {actual})")),
}
}
/// Writes a file whole: a partial one never takes its place.
pub(crate) fn write_file(path: &Path, data: &[u8]) -> Result<(), String> {
let error = |e: std::io::Error| format!("{}: {e}", path.display());
fs::create_dir_all(path.parent().unwrap()).map_err(error)?;
let partial = path.with_file_name(format!(
"{}.partial",
path.file_name().unwrap().to_string_lossy()
));
fs::write(&partial, data)
.and_then(|_| fs::rename(&partial, path))
.map_err(error)
}
/// Links a launcher's files into the official layout in `linked`: the client jar as
/// `versions/<v>/<v>.jar`, its `libraries` and `assets`, and the pinned version JSON, the
/// launcher's own when it keeps it, else Mojang's.
fn link_official_layout(
found: &Found,
pins: &Pins,
linked: &Path,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
let v = &pins.version;
let versions = linked.join("versions").join(v);
fs::create_dir_all(&versions).map_err(|e| format!("{}: {e}", versions.display()))?;
let manifest = versions.join(format!("{v}.json"));
if let Some(source) = &found.manifest {
fs::copy(source, &manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
} else {
fetch_manifest(pins, &manifest, fetch, log)?;
}
link(&found.client, &versions.join(format!("{v}.jar")))?;
for dir in ["libraries", "assets"] {
let source = found.base.join(dir);
let target = linked.join(dir);
if source.is_dir() {
link(&source, &target)?;
} else {
unlink(&target)?;
}
}
Ok(())
}
/// Removes a link left by an earlier preparation; never a real folder's contents.
fn unlink(path: &Path) -> Result<(), String> {
if fs::symlink_metadata(path).is_err() {
return Ok(());
}
// A Windows junction, or a directory symlink, is removed as a directory.
fs::remove_file(path)
.or_else(|_| fs::remove_dir(path))
.map_err(|e| format!("{}: {e}", path.display()))
}
/// `link` pointing at `target`, replacing an earlier one.
fn link(target: &Path, link: &Path) -> Result<(), String> {
unlink(link)?;
make_link(target, link).map_err(|e| format!("{} → {}: {e}", link.display(), target.display()))
}
#[cfg(unix)]
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(target, link)
}
/// Symlinks need developer mode on Windows: a junction for a folder, a hard link for a file.
#[cfg(windows)]
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
if !target.is_dir() {
return fs::hard_link(target, link).or_else(|_| fs::copy(target, link).map(|_| ()));
}
let status = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(link)
.arg(target)
.stdout(std::process::Stdio::null())
.status()?;
match status.success() {
true => Ok(()),
false => Err(std::io::Error::other("mklink /J failed")),
}
}
#[cfg(test)]
#[path = "sources_tests.rs"]
mod tests;
+406
View File
@@ -0,0 +1,406 @@
//! Each launcher's layout, rebuilt with small fake files (never Mojang's).
use super::*;
use std::cell::RefCell;
use std::sync::Mutex;
const CLIENT: &[u8] = b"fake 26.3 client jar";
const MANIFEST: &[u8] = br#"{"id": "26.3", "fake": true}"#;
fn pins() -> Pins {
Pins::read(&serde_json::json!({ "minecraft": {
"version": "26.3",
"client_sha1": sha1_hex(CLIENT),
"manifest_sha1": sha1_hex(MANIFEST),
"accepted_manifest_sha1": [sha1_hex(b"an earlier one")],
}}))
.unwrap()
}
/// A scratch folder, removed at the end.
struct Scratch(PathBuf);
impl Scratch {
fn new(name: &str) -> Scratch {
let dir =
std::env::temp_dir().join(format!("horizon-sources-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Scratch(dir)
}
fn write(&self, path: &str, data: &[u8]) -> PathBuf {
let path = self.0.join(path);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, data).unwrap();
path
}
/// A launcher folder: the client jar at `jar`, a library and a sound under `base`.
fn launcher(&self, root: &str, base: &str, jar: &str) -> PathBuf {
let base = if base.is_empty() {
root.to_string()
} else {
format!("{root}/{base}")
};
self.write(&format!("{base}/{jar}"), CLIENT);
self.write(&format!("{base}/libraries/org/lib/1/lib-1.jar"), b"lib");
self.write(&format!("{base}/assets/indexes/30.json"), b"{}");
self.0.join(root)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Mojang's piston-meta, serving `body` and counting the requests.
struct Mojang {
body: Vec<u8>,
urls: Mutex<Vec<String>>,
}
impl Mojang {
fn new(body: &[u8]) -> Mojang {
Mojang {
body: body.to_vec(),
urls: Mutex::new(Vec::new()),
}
}
fn fetch(&self, url: &str) -> Result<Vec<u8>, String> {
self.urls.lock().unwrap().push(url.to_string());
Ok(self.body.clone())
}
}
fn resolve_with(
chosen: &Path,
known: &[(&'static str, PathBuf)],
linked: &Path,
mojang: &Mojang,
) -> Result<PathBuf, String> {
match resolve(
chosen,
&pins(),
known,
linked,
&|url| mojang.fetch(url),
&|_| {},
)? {
Resolved::Folder(dir) => Ok(dir),
Resolved::NotFound(checked) => Err(not_found("26.3", &checked)),
}
}
/// The linked folder is the official layout, pointing at the launcher's files.
fn assert_linked(linked: &Path, base: &Path, jar: &str) {
let v = linked.join("versions/26.3");
assert_eq!(fs::read(v.join("26.3.jar")).unwrap(), CLIENT);
assert_eq!(fs::read(v.join("26.3.json")).unwrap(), MANIFEST);
assert_eq!(
fs::canonicalize(v.join("26.3.jar")).unwrap(),
fs::canonicalize(base.join(jar)).unwrap()
);
assert_eq!(
fs::read(linked.join("libraries/org/lib/1/lib-1.jar")).unwrap(),
b"lib"
);
assert!(linked.join("assets/indexes/30.json").is_file());
}
#[test]
fn maven_names_become_repository_paths() {
assert_eq!(
maven_path("com.mojang:minecraft:26.3:client").as_deref(),
Some("com/mojang/minecraft/26.3/minecraft-26.3-client.jar")
);
assert_eq!(
maven_path("org.lwjgl:lwjgl:3.3.3").as_deref(),
Some("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar")
);
assert_eq!(
maven_path("net.example:thing:1.0@zip").as_deref(),
Some("net/example/thing/1.0/thing-1.0.zip")
);
for bad in ["minecraft", "a:b", "a:b:c:d:e", "a:..:1", "a:b/c:1", "a::1"] {
assert_eq!(maven_path(bad), None, "{bad}");
}
}
#[test]
fn the_official_layout_is_used_as_it_is() {
let s = Scratch::new("official");
let dir = s.launcher(".minecraft", "", "versions/26.3/26.3.jar");
s.write(".minecraft/versions/26.3/26.3.json", MANIFEST);
let mojang = Mojang::new(b"");
let got = resolve_with(&dir, &[], &s.0.join("linked"), &mojang).unwrap();
assert_eq!(got, dir);
assert!(mojang.urls.lock().unwrap().is_empty());
assert!(!s.0.join("linked").exists());
}
#[test]
fn an_official_folder_with_an_unknown_version_file_gets_the_pinned_one() {
let s = Scratch::new("republished");
let dir = s.launcher(".minecraft", "", "versions/26.3/26.3.jar");
s.write(".minecraft/versions/26.3/26.3.json", b"{\"id\": \"26.3\"}");
let linked = s.0.join("linked");
let mojang = Mojang::new(MANIFEST);
assert_eq!(resolve_with(&dir, &[], &linked, &mojang).unwrap(), linked);
assert_linked(&linked, &dir, "versions/26.3/26.3.jar");
}
#[test]
fn prism_launcher_and_multimc_are_read_through_their_metadata() {
let s = Scratch::new("prism");
let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let dir = s.launcher("PrismLauncher", "", jar);
// Prism's own version format: no `downloads.server`, the client a Maven name.
s.write(
"PrismLauncher/meta/net.minecraft/26.3.json",
br#"{"formatVersion": 1, "uid": "net.minecraft", "version": "26.3",
"mainJar": {"name": "com.mojang:minecraft:26.3:client",
"downloads": {"artifact": {"sha1": "x", "size": 20}}}}"#,
);
let linked = s.0.join("linked");
let mojang = Mojang::new(MANIFEST);
assert_eq!(resolve_with(&dir, &[], &linked, &mojang).unwrap(), linked);
assert_linked(&linked, &dir, jar);
assert_eq!(
*mojang.urls.lock().unwrap(),
[format!(
"https://piston-meta.mojang.com/v1/packages/{}/26.3.json",
sha1_hex(MANIFEST)
)]
);
// A second preparation keeps the version file it has.
resolve_with(&dir, &[], &linked, &mojang).unwrap();
assert_eq!(mojang.urls.lock().unwrap().len(), 1);
}
#[test]
fn a_main_jar_elsewhere_is_found_from_the_metadata() {
let s = Scratch::new("meta-jar");
let dir = s.launcher(
"multimc",
"",
"libraries/com/mojang/minecraft/26.3/minecraft-26.3-x.jar",
);
s.write(
"multimc/meta/net.minecraft/26.3.json",
br#"{"mainJar": {"name": "com.mojang:minecraft:26.3:x"}}"#,
);
let found = find(&dir, &pins()).unwrap();
assert_eq!(
found.client,
dir.join("libraries/com/mojang/minecraft/26.3/minecraft-26.3-x.jar")
);
}
#[test]
fn the_modrinth_app_atlauncher_and_gdlauncher_are_found() {
for (root, base, jar) in [
("ModrinthApp", "meta", "versions/26.3/26.3.jar"),
(
"atlauncher",
"",
"libraries/net/minecraft/client/26.3/client-26.3.jar",
),
(
"gdlauncher_carbon",
"data",
"libraries/net/minecraft/client/26.3/client-26.3.jar",
),
(
"gdlauncher_next",
"datastore",
"libraries/net/minecraft/client/26.3/client-26.3.jar",
),
] {
let s = Scratch::new(root);
let dir = s.launcher(root, base, jar);
// The Modrinth App rewrites the version file: not the pinned one, so Mojang's is used.
s.write(
&format!("{root}/meta/versions/26.3/26.3.json"),
b"{\"id\":\"26.3\"}",
);
let linked = s.0.join("linked");
let mojang = Mojang::new(MANIFEST);
assert_eq!(
resolve_with(&dir, &[], &linked, &mojang).unwrap(),
linked,
"{root}"
);
assert_linked(&linked, &dir.join(base), jar);
}
}
#[test]
fn an_instance_folder_may_be_chosen() {
let s = Scratch::new("instance");
let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let dir = s.launcher("PrismLauncher", "", jar);
let instance = dir.join("instances/26.3/minecraft");
fs::create_dir_all(&instance).unwrap();
let linked = s.0.join("linked");
let got = resolve_with(&instance, &[], &linked, &Mojang::new(MANIFEST)).unwrap();
assert_eq!(got, linked);
assert_linked(&linked, &dir, jar);
}
#[test]
fn the_known_folders_are_searched_after_the_chosen_one() {
let s = Scratch::new("known");
let empty = s.0.join(".minecraft");
fs::create_dir_all(empty.join("versions")).unwrap();
let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let prism = s.launcher("PrismLauncher", "", jar);
let known = [
(OFFICIAL, empty.clone()),
("Modrinth App", s.0.join("ModrinthApp")),
("Prism Launcher", prism.clone()),
];
let linked = s.0.join("linked");
let logged = RefCell::new(Vec::new());
let mojang = Mojang::new(MANIFEST);
let got = resolve(
&empty,
&pins(),
&known,
&linked,
&|url| mojang.fetch(url),
&|line| logged.borrow_mut().push(line),
);
assert_eq!(got.unwrap(), Resolved::Folder(linked.clone()));
assert_linked(&linked, &prism, jar);
assert_eq!(
logged.borrow()[0],
format!(
"Using Minecraft 26.3 from Prism Launcher ({})",
prism.display()
)
);
}
#[test]
fn relinking_follows_the_launcher_the_files_now_come_from() {
let s = Scratch::new("relink");
let prism_jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let prism = s.launcher("PrismLauncher", "", prism_jar);
let linked = s.0.join("linked");
let mojang = Mojang::new(MANIFEST);
resolve_with(&prism, &[], &linked, &mojang).unwrap();
let modrinth = s.0.join("ModrinthApp");
s.write("ModrinthApp/meta/versions/26.3/26.3.jar", CLIENT);
resolve_with(&modrinth, &[], &linked, &mojang).unwrap();
assert_eq!(
fs::canonicalize(linked.join("versions/26.3/26.3.jar")).unwrap(),
fs::canonicalize(modrinth.join("meta/versions/26.3/26.3.jar")).unwrap()
);
// The Modrinth App folder has no libraries or assets: the old links are gone, and the
// folders they pointed at are untouched.
assert!(fs::symlink_metadata(linked.join("libraries")).is_err());
assert!(prism.join("libraries/org/lib/1/lib-1.jar").is_file());
}
#[test]
fn nothing_found_lists_every_folder_and_what_it_lacks() {
let s = Scratch::new("nothing");
let chosen = s.0.join("chosen");
let wrong = s.0.join("PrismLauncher");
s.write(
"PrismLauncher/libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar",
b"another release",
);
let empty = s.0.join("ModrinthApp");
fs::create_dir_all(&empty).unwrap();
let known = [
("Prism Launcher", wrong.clone()),
("Modrinth App", empty.clone()),
("ATLauncher", s.0.join("atlauncher")),
];
let mojang = Mojang::new(MANIFEST);
let error = resolve_with(&chosen, &known, &s.0.join("linked"), &mojang).unwrap_err();
let expected = format!(
"Minecraft 26.3 was not found. Horizon looked in:\n \
{} (the folder doesn't exist)\n \
{} (Prism Launcher: libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar is \
not the 26.3 release Horizon was made for)\n \
{} (Modrinth App: no Minecraft 26.3 client jar)\nTo fix it:\n",
chosen.display(),
wrong.display(),
empty.display()
);
assert!(error.starts_with(&expected), "{error}");
assert!(error.contains("Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher"));
// A launcher that isn't installed isn't listed.
assert!(!error.contains("atlauncher"));
assert!(mojang.urls.lock().unwrap().is_empty());
}
#[test]
fn a_version_file_that_is_not_the_pinned_one_is_refused() {
let s = Scratch::new("bad-download");
let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let dir = s.launcher("PrismLauncher", "", jar);
let linked = s.0.join("linked");
let error = resolve_with(&dir, &[], &linked, &Mojang::new(b"{}")).unwrap_err();
assert!(error.contains("not the one Horizon pins"), "{error}");
assert!(!linked.join("versions/26.3/26.3.json").exists());
}
#[test]
fn each_system_has_its_launcher_folders() {
let linux = Folders {
home: "/home/r".into(),
data: "/home/r/.local/share".into(),
config: "/home/r/.config".into(),
};
let folders = |os, f: &Folders| -> Vec<String> {
known_folders(os, f)
.into_iter()
.map(|(name, dir)| format!("{name}: {}", dir.display()).replace('\\', "/"))
.collect()
};
let got = folders(Os::Linux, &linux);
for expected in [
"the official launcher: /home/r/.minecraft",
"Prism Launcher: /home/r/.local/share/PrismLauncher",
"Prism Launcher: /home/r/.var/app/org.prismlauncher.PrismLauncher/data/PrismLauncher",
"MultiMC: /home/r/.local/share/multimc",
"Modrinth App: /home/r/.local/share/ModrinthApp",
"Modrinth App: /home/r/.var/app/com.modrinth.ModrinthApp/data/ModrinthApp",
"ATLauncher: /home/r/.local/share/atlauncher",
"GDLauncher: /home/r/.local/share/gdlauncher_carbon",
"GDLauncher: /home/r/.config/gdlauncher_next",
] {
assert!(got.iter().any(|g| g == expected), "{expected} in {got:#?}");
}
assert!(got[0].starts_with("the official launcher"));
let mac = Folders {
home: "/Users/r".into(),
data: "/Users/r/Library/Application Support".into(),
config: "/Users/r/Library/Application Support".into(),
};
let got = folders(Os::MacOs, &mac);
assert_eq!(
got[0],
"the official launcher: /Users/r/Library/Application Support/minecraft"
);
assert!(
got.contains(&"Prism Launcher: /Users/r/Library/Application Support/PrismLauncher".into())
);
let windows = Folders {
home: "C:/Users/r".into(),
data: "C:/Users/r/AppData/Roaming".into(),
config: "C:/Users/r/AppData/Roaming".into(),
};
let got = folders(Os::Windows, &windows);
assert_eq!(
got[0],
"the official launcher: C:/Users/r/AppData/Roaming/.minecraft"
);
assert!(got.contains(&"ATLauncher: C:/Users/r/AppData/Roaming/ATLauncher".into()));
}
+7 -2
View File
@@ -39,8 +39,13 @@ class ReleaseTrainTests(unittest.TestCase):
def test_game_tags_count_up_within_a_day(self):
today = dt.date(2026, 10, 15)
self.assertEqual(train.next_game_tag(["v2026.10.14", "launcher-v0.1.4"], today), "v2026.10.15")
self.assertEqual(train.next_game_tag(["v2026.10.15"], today), "v2026.10.15.1")
self.assertEqual(train.next_game_tag(["v2026.10.15", "v2026.10.15.1", "v2026.10.15.2"], today), "v2026.10.15.3")
self.assertEqual(train.next_game_tag(["v2026.10.15"], today), "v2026.10.15.01")
self.assertEqual(train.next_game_tag(["v2026.10.15", "v2026.10.15.01", "v2026.10.15.02"], today), "v2026.10.15.03")
# Unpadded tags from before the change still count, and the next one sorts after them as text too.
self.assertEqual(train.next_game_tag(["v2026.10.15", "v2026.10.15.9", "v2026.10.15.20"], today), "v2026.10.15.21")
self.assertEqual(train.next_game_tag(["v2026.10.15", "v2026.10.15.08"], today), "v2026.10.15.09")
tags = ["v2026.10.15.09", "v2026.10.15.10", "v2026.10.15"]
self.assertEqual(sorted(tags), sorted(tags, key=train.tag_key))
def test_launcher_tags_bump_the_patch_or_the_minor(self):
tags = ["launcher-v0.1.3", "launcher-v0.1.10", "v2026.10.15", "launcher-v0.1.4"]
+333
View File
@@ -0,0 +1,333 @@
#!/usr/bin/env python3
"""LAN multiplayer end to end: a host opens its world to LAN and a guest joins, both real games.
Two Horizon clients run side by side under horizon-ctl, each in its own scratch folder. The host
creates a survival world and opens it to LAN with commands allowed; the guest connects to it by
address. The script then checks, from both sides, what a guest's game used to get wrong (#366):
- tab: the guest's player list holds the host and the guest, under their own names;
- self: the guest's own model exists (third person, inventory preview);
- armour: each side draws the other player in that player's own armour;
- nametags: each side draws the other player's name above them;
- chest: a chest the guest opens opens on the guest's screen, its lid opens on both sides and
closes on both when the guest closes it;
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table;
- damage: a guest in survival takes fall damage.
Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
both sides go to --out (host-*.png, guest-*.png).
python3 tools/lan_e2e.py # build with the fast profile, run every check
python3 tools/lan_e2e.py --bin-dir target/fast # prebuilt binaries
python3 tools/lan_e2e.py --check chest --check tab
Needs the prepared resources in .local/horizon-client and, on Linux, vscreen (the desktop); on
macOS both games render offscreen. Games started here have no audio (HORIZON_NO_AUDIO=1).
"""
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))
from agent_control_e2e import Cli, Failed, game_env # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
CHECKS = ['tab', 'self', 'armour', 'nametags', 'chest', 'crafting', 'damage']
class Game:
"""One client: its scratch folder, its socket and a CLI driver."""
def __init__(self, name, ctl, resources):
self.name = name
self.work = Path(tempfile.mkdtemp(prefix=f'hzlan-{name}-'))
(self.work / '.local/horizon-client').mkdir(parents=True)
os.symlink(resources, self.work / '.local/horizon-client/26.3')
self.socket = self.work / 'c.sock'
env = game_env(os.environ.get('VSCREEN', 'lan-e2e'))
env['HORIZON_HOME'] = str(self.work / 'home')
self.d = Cli(ctl, self.socket, self.work, env)
self.d.name = name
def __call__(self, tool, **args):
return self.d(tool, **args)
def raw(self, *words):
"""A game command horizon-ctl has no table entry for (lan, connect): the words as typed."""
result = subprocess.run(self.d.base + [str(w) for w in words], cwd=self.work, env=self.d.env,
capture_output=True, text=True, timeout=600)
lines = result.stdout.strip().splitlines()
reply = json.loads(lines[-1]) if lines else {'error': result.stderr.strip()}
print(f'[{self.name}] {list(words)} -> {json.dumps(reply)[:400]}')
if result.returncode or 'error' in reply:
raise Failed(f'{" ".join(map(str, words))}: {reply}')
return reply
def shot(self, out, label):
path = out / f'{self.name}-{label}.png'
self.d('screenshot', path=path)
return path
def wait(self, ticks):
self.d('wait', ticks=ticks)
def close(self):
try:
self.d('quit')
except Exception:
pass
time.sleep(2)
log = self.socket.with_suffix('.log')
return log.read_text(errors='replace') if log.exists() else ''
def remote(guest):
"""The guest's view of the server (`status`'s server part)."""
return guest('status')['server']
def back_to_game(game):
"""Close whatever screen a failed check left open, without opening the pause menu."""
try:
if game('state').get('screen') not in (None, 'playing'):
game.raw('key', 'esc', 'tap')
game.wait(2)
except Failed:
pass
def pos_of(game):
return game('state')['player']['position']
def face_each_other(host, guest):
"""Put the guest 3 blocks east of the host, both looking at the other's head."""
hx, hy, hz = pos_of(host)
guest('command', command=f'tp @s {hx + 3:.2f} {hy:.2f} {hz:.2f}')
guest.wait(30)
host.raw('look-at', f'{hx + 3:.2f}', f'{hy + 1.6:.2f}', f'{hz:.2f}')
guest.raw('look-at', f'{hx:.2f}', f'{hy + 1.6:.2f}', f'{hz:.2f}')
host.wait(10)
def check_tab(host, guest, out):
players = remote(guest)['players']
names = sorted(p['name'] if isinstance(p, dict) else str(p) for p in players)
assert names == sorted([host.player, GUEST_NAME]), f'guest tab list: {players}, host {host.player}'
guest.raw('key', 'tab', 'down')
guest.wait(5)
guest.shot(out, 'tab')
guest.raw('key', 'tab', 'up')
return names
def check_self(host, guest, out):
guest.raw('key', 'f5', 'tap')
guest.wait(10)
guest.shot(out, 'self-third-person')
status = guest('state')
guest.raw('key', 'f5', 'tap')
guest.raw('key', 'f5', 'tap')
guest.raw('key', 'e', 'tap')
guest.raw('wait-for', 'screen', 'inventory')
guest.shot(out, 'self-inventory')
model = remote(guest).get('player_model')
guest.raw('key', 'esc', 'tap')
assert model, f'the guest has no player model: {status.get("camera")}'
return 'model drawn'
def check_armour(host, guest, out):
host('command', command='item replace entity @s armor.head with minecraft:golden_helmet')
host('command', command='item replace entity @s armor.chest with minecraft:golden_chestplate')
guest('command', command='item replace entity @s armor.chest with minecraft:diamond_chestplate')
guest('command', command='item replace entity @s armor.legs with minecraft:diamond_leggings')
face_each_other(host, guest)
host.shot(out, 'armour')
guest.shot(out, 'armour')
seen = host.raw('lan', 'status')['guests'][0].get('model_armor')
assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \
f'the host draws the guest in {seen}'
host_gear = [e for e in remote(guest).get('player_equipment', [])]
assert any('golden_chestplate' in json.dumps(e) for e in host_gear), f'the guest sees the host in {host_gear}'
return 'each in their own'
def check_nametags(host, guest, out):
face_each_other(host, guest)
h = host('status').get('name_tags') or []
g = guest('status').get('name_tags') or []
host.shot(out, 'nametags')
guest.shot(out, 'nametags')
assert GUEST_NAME in h, f'host draws name tags {h}'
assert host.player in g, f'guest draws name tags {g}'
return {'host': h, 'guest': g}
def lid(game, pos):
return game.raw('block', *pos).get('lid', 0.0)
def check_chest(host, guest, out):
x, y, z = (int(v // 1) for v in pos_of(guest))
chest = (x, y, z + 2)
guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest')
guest.wait(10)
guest.raw('interact', *chest)
screen = guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
guest.wait(20)
opened = {'guest': lid(guest, chest), 'host': lid(host, chest)}
host.raw('look-at', chest[0] + 0.5, chest[1] + 0.5, chest[2] + 0.5)
host.wait(2)
host.shot(out, 'chest-open')
guest.shot(out, 'chest-open')
guest.raw('key', 'esc', 'tap')
guest.wait(20)
closed = {'guest': lid(guest, chest), 'host': lid(host, chest)}
host.shot(out, 'chest-closed')
assert screen, 'no container screen on the guest'
assert opened['guest'] > 0.9 and opened['host'] > 0.9, f'lid while open: {opened}'
assert closed['guest'] < 0.1 and closed['host'] < 0.1, f'lid after closing: {closed}'
return {'open': opened, 'closed': closed}
def check_crafting(host, guest, out):
guest('command', command='clear @s')
guest('command', command='give @s minecraft:oak_log 1')
guest.wait(10)
guest.raw('key', 'e', 'tap')
guest.raw('wait-for', 'screen', 'inventory')
inv = guest('inventory')
slot = next(s['slot'] for s in inv['hotbar'] if s and s.get('item') == 'minecraft:oak_log')
# Horizon's slot ids (click-slot): the hotbar is 0-8, the grid 100-108, the result 200.
guest.raw('click-slot', slot)
guest.raw('click-slot', 100)
guest.wait(5)
result = [s for s in guest('screen').get('slots', []) if s.get('slot') == 200]
guest.shot(out, 'crafting-grid')
guest.raw('click-slot', 200, 'shift')
guest.wait(5)
guest.raw('key', 'esc', 'tap')
guest.wait(5)
planks = guest('inventory')['counts'].get('minecraft:oak_planks', 0)
assert planks == 4, f'crafted {planks} planks (result slot: {result})'
x, y, z = (int(v // 1) for v in pos_of(guest))
table = (x, y, z - 2)
guest('command', command=f'setblock {table[0]} {table[1]} {table[2]} minecraft:crafting_table')
guest.wait(10)
guest.raw('interact', *table)
guest.raw('wait-for', 'screen', 'inventory', '--timeout', 10)
size = guest('screen').get('craft_size')
assert size == 3, f'the crafting table opened a {size}x{size} grid'
# Two planks one above the other in the 3x3 grid: four sticks.
slot = next(s['slot'] for s in guest('inventory')['hotbar'] if s and s.get('item') == 'minecraft:oak_planks')
guest.raw('click-slot', slot)
guest.raw('click-slot', 100, 'right')
guest.raw('click-slot', 103, 'right')
guest.raw('click-slot', slot)
guest.wait(5)
guest.shot(out, 'crafting-table')
guest.raw('click-slot', 200, 'shift')
guest.wait(5)
guest.raw('key', 'esc', 'tap')
guest.wait(5)
counts = guest('inventory')['counts']
assert counts.get('minecraft:stick') == 4 and counts.get('minecraft:oak_planks') == 2, f'after the table: {counts}'
return {'planks': planks, 'table': counts}
def check_damage(host, guest, out):
guest('command', command='gamemode survival')
guest.wait(10)
before = remote(guest)['health']
x, y, z = pos_of(guest)
guest('command', command=f'tp @s {x:.2f} {y + 12:.2f} {z:.2f}')
guest.wait(50)
after = remote(guest)['health']
guest.shot(out, 'damage')
assert after < before, f'health {before} -> {after} after a 12-block fall'
# Into water: the fall does no damage.
x, y, z = pos_of(guest)
guest('command', command=f'setblock {int(x // 1)} {int(y // 1)} {int(z // 1)} minecraft:water')
guest('command', command=f'tp @s {x:.2f} {y + 12:.2f} {z:.2f}')
guest.wait(50)
water = remote(guest)['health']
assert water >= after, f'health {after} -> {water} after falling into water'
return {'before': before, 'after': after, 'water': water}
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage}
def run(ctl, out, resources, checks):
host, guest = Game('host', ctl, resources), Game('guest', ctl, resources)
results = {}
try:
host('launch', wait=False, offscreen=sys.platform == 'darwin')
host.raw('open', 'Lan', 5)
host('wait_ready', seconds=400)
host('command', command='time set day')
# An open stone floor around the host, so the players see each other and nothing is in the way.
host('command', command='fill ~-8 ~-1 ~-8 ~8 ~-1 ~8 minecraft:stone')
host('command', command='fill ~-8 ~ ~-8 ~8 ~6 ~8 minecraft:air')
host('command', command='gamerule spawn_mobs false')
port = host.raw('lan', 'open', 0, 'commands')['port']
host.player = host.raw('lan', 'status').get('host', 'Player') # the host's profile name
guest('launch', wait=False, offscreen=sys.platform == 'darwin')
guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME)
guest.raw('wait-for', 'loaded', '--timeout', 300)
guest.wait(40)
face_each_other(host, guest)
host.shot(out, 'joined')
guest.shot(out, 'joined')
for name in checks:
try:
results[name] = {'pass': True, 'detail': CHECK_FNS[name](host, guest, out)}
except (Failed, AssertionError, StopIteration, KeyError) as e:
results[name] = {'pass': False, 'detail': repr(e)}
for g in (host, guest):
back_to_game(g)
print(f'[lan] {name}: {"PASS" if results[name]["pass"] else "FAIL"} {results[name]["detail"]}')
finally:
logs = {g.name: g.close() for g in (guest, host)}
for name, text in logs.items():
(out / f'{name}.log').write_text(text)
for g in (host, guest):
shutil.rmtree(g.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=CHECKS, help='run only these checks (repeatable)')
parser.add_argument('--out', default=str(ROOT / '.local/lan-e2e'), help='screenshots and game 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)
meta = json.loads(subprocess.run(['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=ROOT,
capture_output=True, text=True, check=True).stdout)
bins = Path(meta['target_directory']) / 'fast'
resources = (ROOT / '.local/horizon-client/26.3').resolve()
if not (resources / 'horizon-resources.json').exists():
sys.exit(f'no prepared resources in {resources}')
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
results = run(bins / 'horizon-ctl', out, resources, args.check or 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()
+2
View File
@@ -102,6 +102,8 @@ def main():
archive = args.out / f'{name}.tar.gz'
with tarfile.open(archive, 'w:gz', compresslevel=1) as tar:
tar.add(args.binary, 'horizon/horizon-client')
tar.add(ROOT / 'LICENSE', 'horizon/LICENSE')
tar.add(ROOT / 'THIRD_PARTY_NOTICES.md', 'horizon/THIRD_PARTY_NOTICES.md')
ctl = args.binary.with_name('horizon-ctl') # built with --bins: scripts and agents play through it
if ctl.is_file():
tar.add(ctl, 'horizon/horizon-ctl')
+6 -3
View File
@@ -11,7 +11,7 @@ of merges becomes one release), or the oldest at least MAX_WAIT ago (merges that
of those pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count
towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases.
Game releases are tagged vYYYY.MM.DD, then .1, .2 the same UTC day; launcher releases launcher-vX.Y.Z, the
Game releases are tagged vYYYY.MM.DD, then .01, .02 the same UTC day; launcher releases launcher-vX.Y.Z, the
patch after the last launcher tag, or the next minor when a merged pull request is labelled feature. Notes:
"### New" lists the pull requests labelled feature, "### Fixed" the others, "### Known issues" the bullets of
docs/known-issues.md. See docs/release-flow.md.
@@ -92,12 +92,15 @@ def tag_key(tag):
def next_game_tag(tags, today):
"""vYYYY.MM.DD, or .1, .2... when that day already has a tag (drafts and rolled-back releases included)."""
"""vYYYY.MM.DD, or .01, .02... when that day already has a tag (drafts and rolled-back releases included).
The counter has two digits because GitHub's releases page sorts a day's tags as text: .9 went above .18.
Every reader compares the numbers as integers, so the unpadded tags from before still order correctly."""
day = f"v{today:%Y.%m.%d}"
taken = [tag for tag in tags if tag == day or tag.startswith(day + ".")]
if not taken:
return day
return f"{day}.{max(int(tag.split('.')[3]) if tag.count('.') == 3 else 0 for tag in taken) + 1}"
return f"{day}.{max(int(tag.split('.')[3]) if tag.count('.') == 3 else 0 for tag in taken) + 1:02d}"
def next_launcher_tag(tags, minor):
+1 -1
View File
@@ -346,7 +346,7 @@ def horizon_resave(source, destination, bin_dir):
if launch.returncode:
sys.exit('horizon failed to launch: ' + launch.stdout + launch.stderr)
steps = [['wait-ready', '240']]
steps += [['chat', f'/gamerule {rule} {new}'] for rule, (_, new) in HORIZON_RULES.items()]
steps += [['command', f'gamerule {rule} {new}'] for rule, (_, new) in HORIZON_RULES.items()]
steps += [['save-all'], ['quit']]
for step in steps:
result = subprocess.run(ctl + step, cwd=destination, env=env, capture_output=True, text=True)
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Leaving a world and opening it again keeps its entities as they were (#374).
Vanilla's integrated server unloads every entity with the level when the player saves
and quits (`MinecraftServer.stopServer`), so a world reopened in the same session holds
each entity once. Horizon kept non-mob entities (minecarts, boats, armor stands...) in
memory after Save and Quit to Title; opening the world loaded them again from disk and
the next save wrote both copies, doubling them each time, until the game crawled.
The game runs offscreen (macOS) or on the virtual screen (Linux) with a control socket:
a minecart is summoned beside the player (seed 7 also has mineshaft chest minecarts in
view), then the world is closed through the pause menu and reopened from the title three
times. The minecarts must be the same ones each time, each once.
test_world_reopen_parity.py [--bin-dir DIR] [--keep]
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RESOURCES = ROOT / '.local' / 'horizon-client' / '26.3'
RUN = ROOT / '.local' / 'world-reopen'
CYCLES = 3
def game_env():
"""macOS renders offscreen; Linux uses the virtual screen (as test_save_roundtrip_parity)."""
env = dict(os.environ, HORIZON_NO_AUDIO='1')
if sys.platform == 'darwin':
return env, ['--offscreen']
subprocess.run(['vscreen', 'up'], check=False, capture_output=True)
text = subprocess.run(['vscreen', 'env'], capture_output=True, text=True, check=True).stdout
env.pop('DISPLAY', None)
for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]):
env[match.group(1)] = match.group(2)
return env, []
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 them with the fast profile)')
parser.add_argument('--keep', action='store_true', help='keep the run folder')
args = parser.parse_args()
bin_dir = Path(args.bin_dir).resolve() if args.bin_dir else None
if bin_dir is None:
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'], cwd=ROOT, check=True)
bin_dir = ROOT / os.environ.get('CARGO_TARGET_DIR', 'target') / 'fast'
shutil.rmtree(RUN, ignore_errors=True)
RUN.mkdir(parents=True)
socket = Path(tempfile.mkdtemp(prefix='hzro')) / 'control.sock' # sockets need short paths
env, extra = game_env()
def ctl(*words, check=True):
result = subprocess.run([str(bin_dir / 'horizon-ctl'), '--socket', str(socket), '--timeout', '600', *words],
cwd=RUN, env=env, capture_output=True, text=True)
if check and result.returncode:
sys.exit(f'horizon-ctl {" ".join(words)} failed: {result.stdout}{result.stderr}')
return json.loads(result.stdout) if result.stdout.strip().startswith('{') else result.stdout
def carts():
found = ctl('status')['carts']
return sorted((c['kind'], *(round(v, 1) for v in c['position'])) for c in found)
ctl('launch', '--resources', str(RESOURCES), '--world', 'reopen', '--seed', '7', '--creative',
'--render-distance', '4', *extra)
failures = 0
try:
ctl('wait-ready', '300')
ctl('command', 'summon minecraft:minecart ~2 ~ ~2')
ctl('wait', '20')
expected = carts()
print('minecarts:', len(expected))
if not any(kind == 'minecraft:minecart' for kind, *_ in expected):
sys.exit(f'the summoned minecart is not there: {expected}')
for cycle in range(1, CYCLES + 1):
ctl('pause')
ctl('click-button', 'Save and Quit to Title')
ctl('wait-for', 'screen', 'title', '--timeout', '120')
ctl('open', 'reopen')
ctl('wait-for', 'loaded', '--timeout', '300')
ctl('wait', '20')
got = carts()
ok = got == expected
failures += not ok
print(f'reopen {cycle}: {len(got)} minecarts', 'ok' if ok else f'FAIL (expected {len(expected)})')
finally:
ctl('quit', check=False)
if not args.keep and not failures:
shutil.rmtree(RUN, ignore_errors=True)
print('world reopen:', 'PASS' if not failures else f'{failures} FAILED')
sys.exit(1 if failures else 0)
if __name__ == '__main__':
main()