Merge main into #1265: keep the vehicle checks, take the server-thread default

lan_e2e takes main's version: #1280 kept `boats` (passing with and
without --server-thread) and added `minecarts`, `frames` and `lightning`
next to `ladder`, and main's run() already sets HORIZON_SERVER_THREAD
explicitly as this branch does. The code keeps this branch's change:
single player runs on its server thread by default again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-23 00:42:15 +02:00
52 changed files with 4554 additions and 338 deletions
@@ -1,7 +1,7 @@
//! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the
//! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line;
//! the `#resources` line names the prepared resources for en_us).
use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language};
use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines};
use std::{error::Error, fmt::Write, path::PathBuf};
fn main() -> Result<(), Box<dyn Error>> {
@@ -12,8 +12,9 @@ fn main() -> Result<(), Box<dyn Error>> {
.find_map(|l| l.strip_prefix("#resources "))
.map(PathBuf::from)
.ok_or("no #resources line")?;
let language = Language::load(&[&root], "en_us");
let translate = |key: &str| language.get(key).map(str::to_owned);
// Use the inventory's filtered translations so missing tooltip keys are caught.
let enchantments = Enchantments::load(&root);
let translate = |key: &str| enchantments.translate(key).map(str::to_owned);
let mut output = String::new();
for line in input.lines().filter(|l| !l.starts_with('#')) {
let stack = parse_stack(line)?.ok_or("empty stack")?;
@@ -14,13 +14,22 @@ fn main() {
for count in [0, 1, 4, 64] {
let mut slot = Some(ItemStack::new("minecraft:stone", count));
let mut dropped = 0;
let mut swings = 0;
let mut packets = 0;
for _ in 0..2 {
if let Some(stack) =
take_held_drop(&mut slot, all, mode == GameMode::Spectator)
{
dropped += stack.count;
swings += 1;
}
println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped);
if mode != GameMode::Spectator {
packets += 1;
}
println!(
"{} {dropped} {swings} {packets}",
slot.as_ref().map_or(0, |s| s.count),
);
}
}
}
@@ -3,6 +3,7 @@
//! what the render thread pays for it in `Streaming::update`.
//!
//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F]
//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z]
//!
//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x
//! at that speed for T seconds while frames run at F per second. Each phase reports
@@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn cpu_seconds() -> f64 {
std::fs::read_to_string("/proc/self/stat")
.ok()
.and_then(|stat| {
let fields = stat
.rsplit_once(')')?
.1
.split_whitespace()
.collect::<Vec<_>>();
Some((fields[11].parse::<f64>().ok()? + fields[12].parse::<f64>().ok()?) / 100.0)
})
.unwrap_or(0.0)
}
#[derive(Default)]
struct Phase {
updates: Vec<f64>,
local: (u64, u64),
uploads: usize,
stage_samples: [u64; 7],
cpu_start: f64,
}
impl Phase {
fn update(&mut self, streaming: &mut Streaming, world: &mut World) {
if self.updates.is_empty() {
self.cpu_start = cpu_seconds();
}
let before = LOCAL.with(Cell::get);
let started = Instant::now();
let (uploads, _) = streaming.update(world);
@@ -89,6 +109,9 @@ impl Phase {
self.local.1 += after.1 - before.1;
self.uploads += uploads.len();
drop(uploads);
for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) {
*sum += count as u64;
}
}
fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) {
let mut sorted = self.updates.clone();
@@ -106,6 +129,16 @@ impl Phase {
at(0.99),
sorted.last().copied().unwrap_or(0.0),
);
println!(
"BENCH {}",
serde_json::json!({
"phase": name, "wall_s": wall.as_secs_f64(),
"cpu_s": cpu_seconds() - self.cpu_start,
"chunks": streaming.generated_total - generated, "sections": self.uploads,
"updates": self.updates.len(), "update_ms": total,
"mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64),
})
);
if TRACK {
println!(
" update allocations: {} ({:.1} MiB)",
@@ -142,6 +175,22 @@ fn main() -> Result<()> {
let fly = flag("--fly", 0.0);
let seconds = flag("--seconds", 10.0);
let hz = flag("--hz", 240.0);
let dimension = args
.iter()
.position(|a| a == "--dimension")
.and_then(|i| args.get(i + 1))
.map(|d| {
if d.contains(':') {
d.clone()
} else {
format!("minecraft:{d}")
}
})
.unwrap_or_else(|| "minecraft:overworld".into());
let center = (
flag("--center-x", 0.0) as i32,
flag("--center-z", 0.0) as i32,
);
let assets = Arc::new(Assets::load(&root)?);
let render = Arc::new(assets.reload(&root)?);
@@ -154,11 +203,12 @@ fn main() -> Result<()> {
models::load_visibility(&root, assets.registry)?,
)?);
let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?);
let terrain = Arc::new(VanillaTerrain::new(
let terrain = Arc::new(VanillaTerrain::for_dimension(
&root.join("worldgen"),
assets.registry,
&biomes,
seed,
&dimension,
)?);
let context = Arc::new(WorkerContext {
assets,
@@ -170,8 +220,12 @@ fn main() -> Result<()> {
let mut world = World::new(facts.air, seed);
let mut streaming = Streaming::new(terrain, context, threads);
streaming.radius = radius;
streaming.center = (0, 0);
println!("{threads} workers, radius {radius}, seed {seed}");
streaming.center = center;
streaming.nether_shading = dimension == "minecraft:the_nether";
streaming.sky_light = dimension != "minecraft:the_nether";
println!(
"{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}"
);
let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed));
// Fill: update as often as the game would uncapped, until settled.
@@ -198,12 +252,12 @@ fn main() -> Result<()> {
let mut behind = Vec::new();
while started.elapsed().as_secs_f64() < seconds {
let next = Instant::now() + frame;
let x = (started.elapsed().as_secs_f64() * fly) as i32;
streaming.center = (x, 0);
let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32;
streaming.center = (x, center.1);
phase.update(&mut streaming, &mut world);
// Columns within 2 chunks of the player still missing their meshes.
let near = (-2..=2)
.flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz)))
.flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz)))
.filter(|&(cx, cz)| !streaming.is_lit(cx, cz))
.count();
behind.push(near);
@@ -11,6 +11,7 @@ fn bits(value: f32) -> String {
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let mut output = String::new();
let mut parameters = weather::ParameterCache::default();
for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() {
let p: Vec<&str> = line.split_whitespace().collect();
let int = |i: usize| p[i].parse::<i32>().unwrap();
@@ -38,6 +39,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
bits(column.v_offset),
column.light_coords
)?;
assert_eq!(
parameters
.get(x, z)
.column(kind != 0, ticks, x, bottom, top, z, light, partial),
column,
"cached parameters differ from original random source at case {case}"
);
let max_alpha = if kind == 0 { 1.0 } else { 0.8 };
for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) {
write!(
+2
View File
@@ -193,6 +193,8 @@ impl Enchantments {
|| k.starts_with("item.minecraft.splash_potion")
|| k.starts_with("item.minecraft.lingering_potion")
|| k.starts_with("item.minecraft.tipped_arrow")
|| k.starts_with("item.minecraft.firework_rocket.")
|| k.starts_with("item.minecraft.firework_star.")
|| k.starts_with("trim_")
|| k.starts_with("potion.")
|| k.starts_with("container.")
+140
View File
@@ -43,6 +43,7 @@ struct Out {
@location(8) back_color: vec4<f32>,
// entity.vsh's lightMapColor, multiplied in after the overlay.
@location(9) light_color: vec4<f32>,
@location(10) @interpolate(flat) weather_rect: vec4<f32>,
}
// Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed.
fn entity_light(normal: vec3<f32>, nether: bool) -> f32 {
@@ -109,6 +110,13 @@ fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
return entity_vertex(position, uv, overlay, color, light, normal);
}
// Retained bolt-local geometry, translated using the same f64 camera
// subtraction as the former CPU path before adding each local f32 position.
@vertex fn vs_lightning(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>,
@location(6) offset: vec3<f32>) -> Out {
return entity_vertex(offset + position, uv, overlay, color, light, normal);
}
struct CloudInfo {
offset: vec4<f32>,
colors: array<vec4<f32>, 4>,
@@ -209,3 +217,135 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
@fragment fn fs_water_mask() -> @location(0) vec4<f32> {
return vec4(0.0);
}
// WEATHER_MATH_BEGIN
// Unsigned 64-bit helpers (low word first). Snow adds a random double to a
// float drift before casting to float. Retaining the 53-bit base avoids early
// rounding, including ties, without requiring optional GPU float64 support.
fn weather_shr_jam(v: vec2<u32>, n: u32) -> vec2<u32> {
if n == 0u { return v; }
if n < 32u {
return vec2((v.x >> n) | (v.y << (32u - n)) | select(0u, 1u, (v.x << (32u - n)) != 0u), v.y >> n);
}
if n == 32u { return vec2(v.y | select(0u, 1u, v.x != 0u), 0u); }
if n < 64u {
return vec2((v.y >> (n - 32u)) | select(0u, 1u, v.x != 0u || (v.y << (64u - n)) != 0u), 0u);
}
return vec2(select(0u, 1u, any(v != vec2(0u))), 0u);
}
fn weather_add64(a: vec2<u32>, b: vec2<u32>) -> vec2<u32> {
let lo = a.x + b.x;
return vec2(lo, a.y + b.y + select(0u, 1u, lo < a.x));
}
fn weather_sub64(a: vec2<u32>, b: vec2<u32>) -> vec2<u32> {
return vec2(a.x - b.x, a.y - b.y - select(0u, 1u, a.x < b.x));
}
fn weather_double_plus_float(base: vec2<u32>, delta: f32) -> f32 {
// The random base is nonnegative and either zero or >= 2^-53.
if all(base == vec2(0u)) { return select(delta, 0.0, delta == 0.0); }
let db = bitcast<u32>(delta);
let mag = db & 0x7fffffffu;
let be = i32((base.y >> 20u) & 2047u) - 1023;
var de = i32(mag >> 23u) - 127;
var dm = (mag & 0x7fffffu) | 0x800000u;
if mag < 0x800000u {
dm = mag;
if dm == 0u { de = -200; }
else {
let shift = countLeadingZeros(dm) - 8u;
dm <<= shift;
de = -126 - i32(shift);
}
}
let e = max(be, de);
// Leading significand bit at 61, with room for addition and guard bits.
var a = vec2(base.x << 9u, ((base.y & 0xfffffu) | 0x100000u) << 9u | (base.x >> 23u));
var b = vec2(0u, dm << 6u);
a = weather_shr_jam(a, u32(e - be));
b = weather_shr_jam(b, u32(e - de));
var sign = 0u;
var value: vec2<u32>;
if (db >> 31u) == 0u { value = weather_add64(a, b); }
else if a.y > b.y || (a.y == b.y && a.x >= b.x) { value = weather_sub64(a, b); }
else { value = weather_sub64(b, a); sign = 0x80000000u; }
if all(value == vec2(0u)) { return 0.0; }
let leading = select(31u - countLeadingZeros(value.x), 63u - countLeadingZeros(value.y), value.y != 0u);
var exponent = e + i32(leading) - 61;
// Normalize the leading bit to 62. After jamming, bit 38 is the guard
// bit and bits 0..37 distinguish a tie from a value above the midpoint.
let shift = 62u - leading;
if shift >= 32u { value = vec2(0u, value.x << (shift - 32u)); }
else if shift != 0u { value = vec2(value.x << shift, (value.y << shift) | (value.x >> (32u - shift))); }
// Vanilla first rounds the addition to double, then casts to float.
// Round at bit 10 (53 retained bits) before the 24-bit rounding below;
// otherwise a double-rounding midpoint can select the wrong float.
let double_guard = (value.x & 512u) != 0u;
let double_sticky = (value.x & 511u) != 0u;
let double_odd = (value.x & 1024u) != 0u;
value.x &= 0xfffffc00u;
if double_guard && (double_sticky || double_odd) {
value = weather_add64(value, vec2(1024u, 0u));
}
if (value.y & 0x80000000u) != 0u {
value = weather_shr_jam(value, 1u);
exponent += 1;
}
var mantissa = value.y >> 7u;
let guard = (value.y & 64u) != 0u;
let sticky = (value.y & 63u) != 0u || value.x != 0u;
if guard && (sticky || (mantissa & 1u) != 0u) { mantissa += 1u; }
if mantissa >= 0x1000000u { mantissa >>= 1u; exponent += 1; }
return bitcast<f32>(sign | (u32(exponent + 127) << 23u) | (mantissa & 0x7fffffu));
}
fn weather_phase(animation: vec4<f32>, bases: vec4<u32>, snow: u32, time: vec4<f32>) -> vec2<f32> {
if snow == 0u {
let ticks = time.x + animation.y;
let t = ticks + time.z;
let step = -t / 32.0;
let offset = step * animation.x;
return vec2(0.0, offset % 32.0);
}
let t = time.x + time.z;
let u_time = t * 0.01;
let du = u_time * animation.z;
let v_time = t * animation.w;
let dv = v_time * 0.001;
let u = weather_double_plus_float(bases.xy, du);
let v = weather_double_plus_float(bases.zw, dv);
let fall_time = time.y + time.z;
let fall = -fall_time / 512.0;
return vec2(u, fall + v);
}
// Atlas sampler is nearest with no mipmaps. Clamp the integer texel inside
// the sprite even when a fractional coordinate rounds up at its far edge.
fn weather_texel(uv: vec2<f32>, rect: vec4<f32>, dimensions: vec2<u32>) -> vec2<i32> {
let size = vec2<f32>(dimensions);
let origin = vec2<i32>(round(rect.xy * size));
let extent = max(vec2<i32>(round(rect.zw * size)), vec2(1));
let local = min(vec2<i32>(floor(fract(uv) * vec2<f32>(extent))), extent - vec2(1));
return origin + local;
}
// WEATHER_MATH_END
struct WeatherTime { values: vec4<f32> }
@group(1) @binding(1) var<uniform> weather_time: WeatherTime;
@vertex fn vs_weather(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) rect: vec4<f32>, @location(3) animation: vec4<f32>,
@location(4) bases: vec4<u32>, @location(5) color: vec4<f32>,
@location(6) light: vec4<u32>, @location(7) snow: u32) -> Out {
let phase = weather_phase(animation, bases, snow, weather_time.values);
var out = entity_vertex(position, uv + phase, 0u, color, light, vec4(0.0));
out.weather_rect = rect;
return out;
}
@fragment fn fs_weather(in: Out) -> @location(0) vec4<f32> {
// Repeat within this sprite, never across the atlas. The atlas uses nearest
// filtering and no mipmaps, so fractional UVs have no seam derivatives.
let texel = weather_texel(in.uv, in.weather_rect, textureDimensions(atlas));
var color = textureLoad(atlas, texel, 0) * in.color;
if color.a < 0.1 { discard; }
color *= in.light_color;
let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
}
+103 -74
View File
@@ -76,6 +76,7 @@ mod lan_pvp;
mod lan_screen;
mod lan_stations;
mod lan_trading;
mod lan_vehicles;
mod lan_waypoints;
mod leads;
mod level_particles;
@@ -121,6 +122,7 @@ mod remote;
mod remote_objects;
mod remote_projectiles;
mod remote_stations;
mod remote_vehicles;
mod render_control;
mod render_tick;
mod respawn_anchor;
@@ -1111,6 +1113,7 @@ struct Game<'a> {
/// `FogRenderer`'s evolving state.
fog: horizon_client::fog::FogState,
screen_fx: horizon_client::screen_effects::ScreenEffects,
weather_parameters: horizon_client::weather::ParameterCache,
panorama_rotation: horizon_client::gfx::panorama::Rotation,
world: World,
streaming: Streaming,
@@ -1321,6 +1324,8 @@ struct Game<'a> {
/// `ClientAvatarState`: walked distance and view bob.
avatar: horizon_client::camera::AvatarBob,
flash: u32,
/// Bolts that struck here and sky flashes they made, in total (`status`).
lightning_seen: [u32; 2],
/// The head of the bed while sleeping; the visual timer also survives waking.
sleeping: Option<[i32; 3]>,
sleep_timer: u32,
@@ -4848,6 +4853,9 @@ impl Game<'_> {
self.draw_chat(&mut batch);
self.draw_tab_list(&mut batch);
}
// Screen.extractBlurredBackground blurs the world and HUD, while the
// screen's background, widgets, toasts and debug overlay stay sharp.
batch.blur_at = batch.vertices.len() as u32;
match self.screen {
Screen::Paused if self.pause_menu => self.draw_pause_menu(&mut batch),
// PauseScreen(false): only its title, at the top.
@@ -8952,89 +8960,84 @@ impl Game<'_> {
}
}
/// WeatherEffectRenderer: rain and snow columns within the weather radius.
fn weather_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
fn weather_geometry(
&mut self,
camera: glam::DVec3,
alpha: f64,
) -> Vec<horizon_client::weather::Vertex> {
use horizon_client::weather;
let (intensity, _) = self.world.weather.levels(alpha as f32);
if intensity <= 0.0 {
return;
return Vec::new();
}
let atlas = &self.gui.atlas;
let (Some(rain_tex), Some(snow_tex)) = (
atlas.sprites.get("environment/rain").copied(),
atlas.sprites.get("environment/snow").copied(),
) else {
return;
return Vec::new();
};
let (cx, cy, cz) = (
camera.x.floor() as i32,
camera.y.floor() as i32,
camera.z.floor() as i32,
);
let radius = self.settings.weather_radius;
let ticks = self.world.game_time;
let partial = alpha as f32;
let eye = [camera.x, camera.y, camera.z];
// Vanilla draws every rain column before the snow ones.
let mut columns = (Vec::new(), Vec::new());
for z in cz - radius..=cz + radius {
for x in cx - radius..=cx + radius {
// The 32x32 direction table supports at most a 15-block radius.
let radius = self.settings.weather_radius.clamp(0, 15);
let eye = camera.to_array();
let mut rain = Vec::new();
let mut snow_vertices = Vec::new();
// Saturation keeps extreme camera coordinates from overflowing the loop.
for z in cz.saturating_sub(radius)..=cz.saturating_add(radius) {
for x in cx.saturating_sub(radius)..=cx.saturating_add(radius) {
let top = self.rain_height(x, z);
let y0 = (cy - radius).max(top);
let y1 = (cy + radius).max(top);
let y0 = cy.saturating_sub(radius).max(top);
let y1 = cy.saturating_add(radius).max(top);
if y1 == y0 {
continue;
}
let Some(snow) = self.precipitation(x, cy, z) else {
continue;
};
let mut random = weather::column_random(x, z);
let parameters = self.weather_parameters.get(x, z);
let light = self.world.light(x, top.max(cy), z);
let coords = i32::from(light & 15) << 4 | i32::from(light >> 4) << 20;
if snow {
columns.1.push(weather::snow_column(
&mut random,
ticks,
x,
y0,
y1,
z,
coords,
partial,
));
// Only light brightening is needed here; UV phases stay zero.
let lc = if snow {
let (block, sky) = (coords >> 4 & 15, coords >> 20 & 15);
((block * 3 + 15) / 4) << 4 | ((sky * 3 + 15) / 4) << 20
} else {
columns.0.push(weather::rain_column(
&mut random,
ticks,
x,
y0,
y1,
z,
coords,
partial,
));
coords
};
let column = weather::Column {
x,
z,
bottom_y: y0,
top_y: y1,
u_offset: 0.0,
v_offset: 0.0,
light_coords: lc,
};
let r = if snow { snow_tex } else { rain_tex };
let vertices = weather::vertices(
&column,
parameters,
snow,
eye,
radius,
intensity,
[r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0],
);
if snow {
snow_vertices.extend(vertices);
} else {
rain.extend(vertices);
}
}
}
let rain = columns.0.iter().map(|c| (c, 1.0, rain_tex));
let snow = columns.1.iter().map(|c| (c, 0.8, snow_tex));
for (column, max_alpha, r) in rain.chain(snow) {
let quad = weather::column_quad(column, eye, max_alpha, radius, intensity);
let color = quad[0].color;
let lc = quad[0].light_coords;
let light = ((lc >> 20 & 15) * 16) as u32 | (((lc >> 4 & 15) * 16) as u32) << 8;
weather::tile(&quad, |pos, uvs| {
for (p, [u, v]) in pos.into_iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: p,
uv: [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v],
layer: 0,
color,
light,
});
}
});
}
// Vanilla draws every rain column before the snow ones.
rain.extend(snow_vertices);
rain
}
/// Player.startSleepInBed: night or thunder, no monsters within 8 blocks;
/// the bed becomes the respawn point either way.
@@ -9792,15 +9795,17 @@ impl Game<'_> {
self.entity_geometry(camera, alpha, entities)
});
}
let bolts = if title {
Vec::new()
} else {
self.bolt_instances()
};
let mut additive = Vec::new();
if !title {
self.bolt_geometry(camera, &mut additive);
if self.dim == Dim::End {
let mut dragon = Vec::new();
self.dragon_geometry(camera, alpha, &mut dragon, &mut additive);
self.dragon_fireball_geometry(camera, alpha, &mut dragon);
entities.extend(dragon);
}
if !title && self.dim == Dim::End {
let mut dragon = Vec::new();
self.dragon_geometry(camera, alpha, &mut dragon, &mut additive);
self.dragon_fireball_geometry(camera, alpha, &mut dragon);
entities.extend(dragon);
}
// A Java pack's `clouds` replaces the cloud option (`renderClouds`:
// "false", "fast", "true"), as Iris overrides `getCloudsType`.
@@ -9822,8 +9827,8 @@ impl Game<'_> {
{
// Camera.doesMobEffectBlockSky: no sun, moon or stars.
self.celestial_geometry(&sky)
} else if self.dim == Dim::End {
(self.end_sky_geometry(), None)
} else if self.dim == Dim::End && self.settings.horizon.sky {
(self.end_flash_geometry(), None)
} else {
(Vec::new(), None)
};
@@ -9840,11 +9845,12 @@ impl Game<'_> {
if !title {
self.end_geometry(camera, &mut entities);
}
if (!title || live) && self.dim == Dim::Overworld && self.settings.horizon.weather {
horizon_client::spans::time("weather", || {
self.weather_geometry(camera, alpha, &mut entities)
});
}
let weather =
if (!title || live) && self.dim == Dim::Overworld && self.settings.horizon.weather {
horizon_client::spans::time("weather", || self.weather_geometry(camera, alpha))
} else {
Vec::new()
};
let border = (!title)
.then(|| self.border_draw(camera.to_array(), alpha as f32))
.flatten();
@@ -9855,6 +9861,8 @@ impl Game<'_> {
self.gather_dynamic_lights(camera, alpha);
}
let frame = Frame {
weather: &weather,
weather_time: horizon_client::weather::Time::new(self.world.game_time, alpha as f32),
shader: self.shader_inputs(camera, alpha as f32),
nether_lighting: self.dim == Dim::Nether,
camera,
@@ -9870,6 +9878,12 @@ impl Game<'_> {
title: title && !live,
skybox: self.dim == Dim::Overworld && self.settings.horizon.sky,
end_sky: self.dim == Dim::End && self.settings.horizon.sky,
end_sky_sprite: self
.gui
.atlas
.sprites
.get("environment/end_sky")
.map(|r| [r.u0, r.v0, r.u1, r.v1]),
environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)),
cave_culling,
water_fog,
@@ -9912,6 +9926,13 @@ impl Game<'_> {
}),
entities: &entities,
dynamic_lights: &self.dynamic_lights,
lightning: horizon_client::gfx::lightning::Input {
bolts: &bolts,
uv: [
self.gui.atlas.font.white().u0,
self.gui.atlas.font.white().v0,
],
},
additive: &additive,
see_through: &see_through,
celestial: if self.settings.horizon.sky || title {
@@ -10017,9 +10038,8 @@ impl Game<'_> {
};
level_loading::draw(batch, atlas, Some(&status), Some(self.loading_progress));
}
/// `Screen.extractBlurredBackground` over the panorama: every classic
/// screen of the title menus but the title itself (`TitleScreen`
/// doesn't blur), when `menuBackgroundBlurriness` is at least 1.
/// `Screen.extractBlurredBackground` over the panorama or the world and
/// HUD, when `menuBackgroundBlurriness` is at least 1.
fn menu_blur(&self) -> Option<f32> {
let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
let blurred = !horizon_client::ui_theme::horizon()
@@ -10027,7 +10047,10 @@ impl Game<'_> {
|| self.title.as_ref().is_some_and(|t| {
self.screen == Screen::Options
|| !matches!(t.mode, horizon_client::title::Mode::Main)
}));
})
|| (self.title.is_none()
&& self.player.is_some()
&& self.screen.blurs_background(self.pause_menu)));
let radius = self.settings.menu_blur as f32;
(blurred && radius >= 1.0).then_some(radius)
}
@@ -11448,6 +11471,7 @@ impl<'a> Game<'a> {
gui,
fog: Default::default(),
screen_fx: Default::default(),
weather_parameters: Default::default(),
panorama_rotation: Default::default(),
world,
streaming,
@@ -11592,6 +11616,7 @@ impl<'a> Game<'a> {
dragging: false,
avatar: Default::default(),
flash: 0,
lightning_seen: [0; 2],
sleeping: None,
sleep_timer: 0,
dim: Dim::Overworld,
@@ -12360,6 +12385,8 @@ fn loading_renderer(
/// A title-shaped frame: black clear and panorama, only the HUD is drawn.
fn loading_frame(hud: &HudBatch) -> Frame<'_> {
Frame {
weather: &[],
weather_time: horizon_client::weather::Time::new(0, 0.0),
camera: glam::DVec3::new(0.5, 100.0, 0.5),
yaw: 0.0,
pitch: 10.0,
@@ -12374,6 +12401,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
title: true,
skybox: false,
end_sky: false,
end_sky_sprite: None,
environment_fog: None,
water_fog: [0.0; 3],
fog: None,
@@ -12388,6 +12416,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
entities: &[],
dynamic_lights: &[],
clouds: None,
lightning: Default::default(),
additive: &[],
see_through: &[],
celestial: &[],
+10 -3
View File
@@ -57,7 +57,7 @@ pub(super) const CHEST_SLOTS: usize = 27;
const WIDTH: f64 = 1.375;
const HEIGHT: f64 = 0.5625;
/// Player.DEFAULT_VEHICLE_ATTACHMENT minus the boat's passenger attachment.
const SEAT: f64 = 0.1875 - 0.6;
pub(super) const SEAT: f64 = 0.1875 - 0.6;
impl Boat {
pub fn new(id: u32, wood: Arc<str>, position: Vec3, yaw: f32) -> Self {
Self {
@@ -295,7 +295,7 @@ impl Game<'_> {
}
}
/// `AbstractBoat.tick` for one boat (`controlled` when the player rides it).
fn tick_boat(&mut self, mut b: Boat, controlled: bool) -> Boat {
pub(super) fn tick_boat(&mut self, mut b: Boat, controlled: bool) -> Boat {
b.previous = b.position;
b.previous_yaw = b.yaw;
b.old_status = b.status;
@@ -448,9 +448,12 @@ impl Game<'_> {
pub(super) fn tick_boats(&mut self) {
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
// A server player's boat is driven by its client (lan_vehicles.rs).
let driven = self.guest_vehicles();
for i in 0..self.boats.len() {
let p = self.boats[i].position;
if Some(self.boats[i].id) == self.riding
|| driven.contains(&self.boats[i].id)
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
{
continue;
@@ -659,7 +662,11 @@ impl Game<'_> {
self.right = false;
return true;
}
if sneaking || self.boats[i].out_of_control >= 60.0 || self.riding.is_some() {
if sneaking
|| self.boats[i].out_of_control >= 60.0
|| self.riding.is_some()
|| self.ridden_by_guest(self.boats[i].id)
{
return false;
}
self.riding = Some(self.boats[i].id);
@@ -926,6 +926,8 @@ impl Game<'_> {
status["heard"] = json!(self.audio.heard);
// Boats, minecarts, armor stands, item frames and paintings.
status["objects"] = json!(self.objects_status());
status["lightning"] = json!({"bolts": self.bolts.len(), "struck": self.lightning_seen[0],
"flashes": self.lightning_seen[1], "flash": self.flash});
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
status["projectiles"] = json!(self.projectiles_status());
status
+5 -40
View File
@@ -138,47 +138,12 @@ impl Game<'_> {
}
}
/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times,
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
pub(super) fn end_sky_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::with_capacity(6 * 256 * 4);
let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else {
/// SkyRenderer.renderEndFlash, drawn after the renderer's resident sky mesh.
pub(super) fn end_flash_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::new();
// The old combined sky/flash draw also skipped the flash without a sky sprite.
if !self.gui.atlas.sprites.contains_key("environment/end_sky") {
return out;
};
use std::f32::consts::FRAC_PI_2;
let faces = [
glam::Mat4::IDENTITY,
glam::Mat4::from_rotation_x(FRAC_PI_2),
glam::Mat4::from_rotation_x(-FRAC_PI_2),
glam::Mat4::from_rotation_x(std::f32::consts::PI),
glam::Mat4::from_rotation_z(FRAC_PI_2),
glam::Mat4::from_rotation_z(-FRAC_PI_2),
];
let step = 200.0 / 16.0;
for pose in faces {
for a in 0..16 {
for b in 0..16 {
let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32);
let (x1, z1) = (x0 + step, z0 + step);
let corners = [
(x0, z0, [r.u0, r.v0]),
(x0, z1, [r.u0, r.v1]),
(x1, z1, [r.u1, r.v1]),
(x1, z0, [r.u1, r.v0]),
];
for (x, z, uv) in corners {
let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z));
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 2,
color: 0xFF28_2828,
light: 0,
});
}
}
}
}
// SkyRenderer.renderEndFlash: the end_flash sprite at height 100, scale 60.
let intensity = self.end.flash.intensity(self.clock.fraction() as f32);
+16 -8
View File
@@ -52,10 +52,12 @@ impl Game<'_> {
if self.friends.is_some() {
return Ok(());
}
if self.remote.is_some() || self.title.is_some() {
// Single player on its server thread shares that server, as Open to
// LAN publishes it; another server can't be shared.
if self.title.is_some() || (self.remote.is_some() && self.integrated.is_none()) {
return Err("open a singleplayer world first".into());
}
let opened_lan = self.lan.is_none();
let opened_lan = self.lan_port().is_none();
if opened_lan {
// ShareToLanScreen's defaults, as the world options screen offers them.
self.lan_open(LanSettings {
@@ -171,14 +173,20 @@ impl Game<'_> {
/// What the pause menu shows.
pub(super) fn friends_view(&self) -> FriendsView {
let guests = self
.lan
.as_ref()
.map(|h| h.hub.guests.iter().map(|g| g.name.clone()).collect())
.unwrap_or_default();
let guests = match &self.lan {
Some(h) => h.hub.guests.iter().map(|g| g.name.clone()).collect(),
// On the server thread: the other players the server lists.
None if self.integrated.is_some() => {
let me = self.options.player_name();
let mut names = self.remote_online_names().unwrap_or_default();
names.retain(|n| *n != me);
names
}
None => Vec::new(),
};
let Some(s) = &self.friends else {
return FriendsView {
shown: self.remote.is_none(),
shown: self.remote.is_none() || self.integrated.is_some(),
..FriendsView::default()
};
};
+7 -1
View File
@@ -807,7 +807,13 @@ impl Game<'_> {
if has_guests {
let host_entity = state.as_ref().map(|s| s.entity_id);
self.lan_assign_ids();
self.lan_riding(host_entity, &mut host.hub.riding);
let guests: Vec<(u32, i32)> = host
.hub
.guests
.iter()
.filter_map(|g| Some((g.vehicle?, g.entity_id)))
.collect();
self.lan_riding(host_entity, &guests, &mut host.hub.riding);
self.lan_entities(host_entity, &mut host.hub, &mut states);
} else {
states.clear();
+57 -7
View File
@@ -292,7 +292,8 @@ impl Game<'_> {
let (left, right) = (self.left, self.right);
self.left = play.digging.is_some();
self.right = play.using.is_some() || self.using.is_some();
let riding = self.riding.take();
// The guest's vehicle (Entity.vehicle) for its turn.
let riding = std::mem::replace(&mut self.riding, g.vehicle);
let host_station = self.station.take();
// The guest's bed, sleep counter and respawn point; the host's
// respawn point, anchor and action bar stay theirs.
@@ -467,7 +468,7 @@ impl Game<'_> {
(self.respawn_config, self.level.spawn) = respawn;
// ServerPlayer.displayClientMessage(_, true): the guest's action bar.
let guest_message = std::mem::replace(&mut self.message, message);
self.riding = riding;
let guest_vehicle = std::mem::replace(&mut self.riding, riding);
self.left = left;
self.right = right;
play.mining = std::mem::replace(&mut self.mining, mining);
@@ -491,6 +492,11 @@ impl Game<'_> {
self.mount_menu = host_mount_menu;
self.keys = host_keys;
let g = &mut host.hub.guests[i];
let left_vehicle = g.vehicle.filter(|_| guest_vehicle.is_none());
if guest_vehicle.is_none() {
g.vehicle_good = None;
}
g.vehicle = guest_vehicle;
let fell_asleep = bed.is_some() && g.bed.is_none();
(g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn);
g.sleeping = g.bed.is_some();
@@ -549,7 +555,24 @@ impl Game<'_> {
let teleported = std::mem::take(&mut m.teleported);
let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum();
g.motion = Some(Box::new(m));
if moved > 0.0001 || turned || teleported {
// Entity.teleportTo takes a rider out of its vehicle.
let left_vehicle = match g.vehicle.filter(|_| teleported) {
Some(v) => {
(g.vehicle, g.vehicle_good) = (None, None);
Some(v)
}
None => left_vehicle,
};
// ServerPlayer.dismountTo: the client hears it is out of the
// vehicle before the teleport beside it. A rider sits where its
// vehicle puts it (lan_vehicles.rs), with no teleport.
if let Some(vehicle) = left_vehicle {
g.send(&C::SetPassengers(play::SetPassengers {
vehicle: vehicle as i32,
passengers: Vec::new(),
}));
}
if g.vehicle.is_none() && (moved > 0.0001 || turned || teleported) {
host.hub.teleport(i, Some(at));
}
}
@@ -900,16 +923,22 @@ impl Game<'_> {
}
S::Attack(p) => self.guest_attack(host, conn, p.id),
S::Interact(p) => {
if let Some((position, eye)) = self.look_at_entity(host, gi, p.id) {
let _ = (position, eye);
let before = host.hub.guests[gi].vehicle;
if self
.look_at_entity(host, gi, p.id, Some(p.location))
.is_some()
{
let swung = self.as_guest(host, conn, |g| {
let swings = g.swings_started;
let _ = g.use_item();
g.swings_started != swings
});
self.lan_swing_back(host, conn, swung);
self.guest_boarded(host, conn, before);
}
}
S::MoveVehicle(p) => self.guest_move_vehicle(host, conn, &p),
S::PaddleBoat(p) => self.guest_paddle_boat(host, conn, [p.left, p.right]),
S::SetCreativeModeSlot(p) => {
let g = &mut host.hub.guests[gi];
if !g.creative() || !(0..46).contains(&p.slot) {
@@ -1147,19 +1176,39 @@ impl Game<'_> {
}
}
/// Aim the swapped-in player at an entity; returns its centre and the eye.
/// Aim the swapped-in player at an entity; returns where it aims and the
/// eye. A boat, minecart, armor stand, item frame or painting is aimed at
/// the point the client hit (the interact packet's location) when that
/// is on it, else at its centre.
fn look_at_entity(
&mut self,
host: &mut LanHost,
gi: usize,
id: i32,
location: Option<[f64; 3]>,
) -> Option<([f64; 3], [f64; 3])> {
let object = || {
let (lo, hi, origin) = self.object_target(id)?;
let middle = [0, 1, 2].map(|k| (lo[k] + hi[k]) / 2.0);
let Some(l) = location else {
return Some(middle);
};
let point = [0, 1, 2].map(|k| origin[k] + l[k]);
// A little inside the box, so the ray from the eye meets it.
let inside = [0, 1, 2].map(|k| {
let margin = ((hi[k] - lo[k]) / 2.0).min(0.01);
point[k].clamp(lo[k] + margin, hi[k] - margin)
});
let on = (0..3).all(|k| (point[k] - inside[k]).abs() < 0.1);
Some(if on { inside } else { middle })
};
let centre = match self.mobs.iter().find(|m| m.id as i32 == id) {
Some(m) => [
m.position.x,
m.position.y + m.kind.height * 0.5,
m.position.z,
],
None if self.object_target(id).is_some() => object()?,
// A dragon part or an end crystal (game/dragon.rs).
None => {
let b = self.tracked_special_box(id)?;
@@ -1210,7 +1259,7 @@ impl Game<'_> {
return;
}
let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch);
if self.look_at_entity(host, gi, id).is_none() {
if self.look_at_entity(host, gi, id, None).is_none() {
return;
}
self.as_guest(host, conn, |g| {
@@ -1676,6 +1725,7 @@ impl Game<'_> {
/// regeneration and the food tick (ServerPlayer.doTick). Their hurt
/// sounds are heard at the guest.
fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) {
self.guest_vehicle_tick(host, conn);
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
+15 -1
View File
@@ -89,8 +89,17 @@ fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> {
impl Game<'_> {
/// Who rides what (`Entity.getPassengers`): mobs on mobs, and the
/// host in its boat or minecart.
pub(super) fn lan_riding(&self, host_entity: Option<i32>, riding: &mut Riding) {
pub(super) fn lan_riding(
&self,
host_entity: Option<i32>,
guests: &[(u32, i32)],
riding: &mut Riding,
) {
riding.clear();
// The server's players in their boats and minecarts.
for &(vehicle, guest) in guests {
riding.add(vehicle as i32, guest);
}
for m in self.mobs.iter().filter(|m| !m.removed) {
if let Some(vehicle) = m.extra.mount {
riding.add(vehicle as i32, m.id as i32);
@@ -264,6 +273,7 @@ impl Game<'_> {
self.tridents.iter_mut().for_each(|t| give(&mut t.id));
self.rockets.iter_mut().for_each(|r| give(&mut r.id));
self.crystals.iter_mut().for_each(|c| give(&mut c.id));
self.bolts.iter_mut().for_each(|b| give(&mut b.id));
}
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
@@ -275,6 +285,10 @@ impl Game<'_> {
None => 0,
};
let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z];
// LightningBolt: each client draws and flashes its own.
for b in self.bolts.iter().filter(|b| b.id != 0) {
out.push(state(b.id, "minecraft:lightning_bolt", b.at, 0.0, false));
}
for t in self.tnts.iter().filter(|t| t.id != 0) {
let mut e = state(t.id, "minecraft:tnt", at(t.position), 0.0, t.on_ground);
e.velocity = at(t.velocity);
@@ -0,0 +1,288 @@
//! Boats and minecarts for a server's players: LAN guests, players on a
//! dedicated server, and single player's window on its server thread.
//!
//! A player aims at a vehicle, item frame, armor stand or painting as at a
//! mob (`ServerGamePacketListenerImpl.handleInteract`), and the game's own
//! code for it runs as that player (`AbstractBoat.interact` seats it,
//! `VehicleEntity.hurtServer` breaks the vehicle). A boat is driven by its
//! rider's client (`handleMoveVehicle`, `handlePaddleBoat`); a minecart moves
//! here with the rider's input (`ServerPlayer.getLastClientMoveIntent`).
//! Sneaking gets out (`Player.rideTick`: `wantsToStopRiding`), and the client
//! is teleported where the player lands (`ServerPlayer.dismountTo`).
use super::{Game, Keys, boats::SEAT, lan::LanHost};
use horizon_client::collisions::SceneCollisions;
use horizon_core::geometry::{Aabb, Vec3};
use horizon_protocol::{
packets::play::{self, Clientbound as C},
text::translatable,
};
/// `PlayerInput` flags, as the server player's client last sent them.
pub(super) fn input_keys(flags: u8) -> Keys {
Keys {
forward: flags & 1 != 0,
backward: flags & 2 != 0,
left: flags & 4 != 0,
right: flags & 8 != 0,
jump: flags & 16 != 0,
shift: flags & 32 != 0,
..Keys::default()
}
}
fn corners(b: Aabb) -> ([f64; 3], [f64; 3]) {
let (lo, hi) = (b.min_position(), b.max_position());
([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z])
}
impl Game<'_> {
/// The box of a boat, minecart, armor stand, item frame or painting, and
/// the point an interact packet's location is measured from (the
/// client's `remote_object_hit` uses the same points).
pub(super) fn object_target(&self, id: i32) -> Option<([f64; 3], [f64; 3], [f64; 3])> {
let id = u32::try_from(id).ok()?;
let at = |v: Vec3| [v.x, v.y, v.z];
let centre = |p: [i32; 3]| p.map(|v| f64::from(v) + 0.5);
if let Some(b) = self.boats.iter().find(|b| b.id == id) {
let (lo, hi) = corners(b.bounds());
return Some((lo, hi, at(b.position)));
}
if let Some(c) = self.carts.iter().find(|c| c.id == id) {
let (lo, hi) = corners(c.bounds());
return Some((lo, hi, at(c.position)));
}
if let Some(a) = self.armor_stands.iter().find(|a| a.id == id) {
let (lo, hi) = corners(a.bounds());
return Some((lo, hi, at(a.position)));
}
if let Some(f) = self.item_frames.iter().find(|f| f.id == id) {
let (lo, hi) = f.bounds();
return Some((lo, hi, centre(f.pos)));
}
let p = self.paintings.iter().find(|p| p.id == id)?;
let (lo, hi) = p.bounds();
Some((lo, hi, centre(p.pos)))
}
/// The vehicles the server's players ride: they move with their riders,
/// not in `tick_boats` and `tick_carts`.
pub(super) fn guest_vehicles(&self) -> Vec<u32> {
self.lan.as_ref().map_or_else(Vec::new, |h| {
h.hub.guests.iter().filter_map(|g| g.vehicle).collect()
})
}
/// Whether a server player other than the one acting rides `vehicle`
/// (`Entity.canAddPassenger`: a boat or minecart seats one player here).
pub(super) fn ridden_by_guest(&self, vehicle: u32) -> bool {
self.lan.as_ref().is_some_and(|h| {
h.hub
.guests
.iter()
.any(|g| Some(g.conn) != self.lan_acting && g.vehicle == Some(vehicle))
})
}
/// `Player.rideTick` for a server player, before its moves this tick:
/// it stays in its seat, steers its minecart, or gets out.
pub(super) fn guest_vehicle_tick(&mut self, host: &mut LanHost, conn: u32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let g = &host.hub.guests[gi];
let Some(vehicle) = g.vehicle else {
return;
};
let (keys, dead) = (input_keys(g.input), g.dead || g.health <= 0.0);
let boat = self.boats.iter().position(|b| b.id == vehicle);
let cart = self.carts.iter().any(|c| c.id == vehicle);
// The vehicle is gone (broken, in another level) or the rider died:
// its client drops it with the entity or the death screen.
if dead || (boat.is_none() && !cart) {
let g = &mut host.hub.guests[gi];
(g.vehicle, g.vehicle_good) = (None, None);
return;
}
if let Some(i) = boat {
// AbstractBoat.tick on the server for a boat its rider drives:
// only the hurt animation and the damage wear off here.
let b = &mut self.boats[i];
b.hurt_time = (b.hurt_time - 1).max(0);
b.damage = (b.damage - 1.0).max(0.0);
}
// Getting out goes through leave_guest, which tells the client and
// teleports it (ServerPlayer.dismountTo).
let seat = self.as_guest(host, conn, |game| {
if let Some(i) = game.boats.iter().position(|b| Some(b.id) == game.riding) {
if keys.shift {
game.dismount(i);
return None;
}
let p = game.boats[i].position;
return Some([p.x, p.y + SEAT, p.z]);
}
// The minecart moves with the rider's input, and lets it out when
// it sneaks or the cart breaks.
game.tick_cart_riding(keys);
game.riding?;
let p = game.player.as_ref()?.position;
Some([p.x, p.y, p.z])
});
if let Some(Some(at)) = seat {
let g = &mut host.hub.guests[gi];
g.previous_position = g.position;
g.position = at;
}
}
/// After an interaction: a player that got into a vehicle sits in it,
/// and its last good vehicle position is where the vehicle is.
pub(super) fn guest_boarded(&mut self, host: &mut LanHost, conn: u32, before: Option<u32>) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let Some(vehicle) = host.hub.guests[gi].vehicle else {
return;
};
if before == Some(vehicle) {
return;
}
// The host in the window rides it already.
if self.riding == Some(vehicle) {
host.hub.guests[gi].vehicle = before;
return;
}
let at = self
.boats
.iter()
.find(|b| b.id == vehicle)
.map(|b| b.position)
.or_else(|| {
self.carts
.iter()
.find(|c| c.id == vehicle)
.map(|c| c.position)
});
let g = &mut host.hub.guests[gi];
if let Some(p) = at {
g.vehicle_good = Some([p.x, p.y, p.z]);
g.previous_position = g.position;
g.position = [p.x, p.y + SEAT, p.z];
g.on_ground = false;
}
}
/// `ServerGamePacketListenerImpl.handleMoveVehicle`: the boat its rider
/// drives goes where the client says, unless it moved too quickly or
/// wrongly; then it stays, and the client is told where it is.
pub(super) fn guest_move_vehicle(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::MoveVehicleRequest,
) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let [x, y, z] = p.position;
if !(x.is_finite() && y.is_finite() && z.is_finite())
|| !p.yaw.is_finite()
|| !p.pitch.is_finite()
{
host.hub.kick(
conn,
translatable("multiplayer.disconnect.invalid_vehicle_movement", &[]),
);
return;
}
let g = &host.hub.guests[gi];
if g.awaiting_teleport.is_some() || !g.loaded {
return;
}
let owner = host.hub.singleplayer_owner == Some(g.uuid);
let (vehicle, good) = (g.vehicle, g.vehicle_good);
let back = |host: &mut LanHost, position: Vec3, yaw: f32| {
let packet = play::MoveVehicle {
position: [position.x, position.y, position.z],
yaw,
pitch: 0.0,
};
host.hub.send_to(conn, &C::MoveVehicle(packet));
};
// Only a boat is driven by its rider (getControllingPassenger); a
// minecart that is elsewhere on the client is put back.
let Some(i) = vehicle.and_then(|v| self.boats.iter().position(|b| b.id == v)) else {
if let Some(c) = vehicle.and_then(|v| self.carts.iter().find(|c| c.id == v))
&& c.position.distance_squared(Vec3::new(x, y, z)) > 1.0
{
back(host, c.position, c.yaw);
}
return;
};
let b = &self.boats[i];
let old = b.position;
let good = good.map_or(old, |g| Vec3::new(g[0], g[1], g[2]));
let target = Vec3::new(
x.clamp(-3.0E7, 3.0E7),
y.clamp(-2.0E7, 2.0E7),
z.clamp(-3.0E7, 3.0E7),
);
// Moved too quickly: more than 10 blocks past its own motion.
let moved = target.distance_squared(old) - b.velocity.length_squared();
if moved > 100.0 && !owner {
log::warn!("boat {} moved too quickly! {moved}", b.id);
back(host, old, b.yaw);
return;
}
// vehicle.move(PLAYER, target - lastGood) with the boat's collisions:
// where it can't follow the client (a quarter block off, the height
// aside), it moved wrongly.
let bounds = b.bounds();
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
let wanted = target.subtract(good);
let resolved = scene
.resolve(bounds, wanted, 0.0, b.on_ground)
.unwrap_or(wanted);
let reached = old.add_vector(resolved);
let wrongly = (target.x - reached.x).powi(2) + (target.z - reached.z).powi(2) > 0.0625;
let free_before = scene.unobstructed(bounds).unwrap_or(true);
// isEntityCollidingWithAnythingNew: a box that was free is not there.
let moved_box = bounds.move_by(target.subtract(old));
let free_after = scene
.unobstructed(moved_box.deflate(Vec3::new(1.0E-5, 1.0E-5, 1.0E-5)))
.unwrap_or(true);
if free_before && (wrongly || !free_after) {
log::warn!("boat {} moved wrongly", b.id);
back(host, old, b.yaw);
return;
}
let b = &mut self.boats[i];
b.previous = old;
b.velocity = target.subtract(old);
b.position = target;
b.previous_yaw = b.yaw;
b.yaw = p.yaw;
b.on_ground = p.on_ground;
let g = &mut host.hub.guests[gi];
g.vehicle_good = Some([target.x, target.y, target.z]);
g.previous_position = g.position;
g.position = [target.x, target.y + SEAT, target.z];
}
/// `handlePaddleBoat`: the paddles of the boat the player drives.
pub(super) fn guest_paddle_boat(&mut self, host: &LanHost, conn: u32, paddles: [bool; 2]) {
let vehicle = host
.hub
.guests
.iter()
.find(|g| g.conn == conn)
.and_then(|g| g.vehicle);
if let Some(b) = self.boats.iter_mut().find(|b| Some(b.id) == vehicle) {
b.paddling = paddles;
}
}
}
+37 -75
View File
@@ -5,17 +5,13 @@
//! witches, mooshroom colours, turtles, burnt items), lightning rods, the sky
//! flash, the sounds and the branching additive bolt.
use super::Game;
use horizon_client::{
mesher::Vertex,
mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species},
};
use horizon_core::{
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_client::mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species};
use horizon_core::{position::BlockPos, random::RandomSource};
pub(super) struct Bolt {
at: [f64; 3],
/// The entity id a server's players know it by (0 until it has one).
pub id: u32,
pub at: [f64; 3],
life: i32,
flashes: i32,
seed: i64,
@@ -137,7 +133,9 @@ impl Game<'_> {
let r = &mut self.world.random;
let seed = r.next_long();
let flashes = r.next_int_bound(3).unwrap_or(0) + 1;
self.lightning_seen[0] += 1;
self.bolts.push(Bolt {
id: 0,
at,
life: 2,
flashes,
@@ -146,6 +144,24 @@ impl Game<'_> {
converted: Vec::new(),
});
}
/// `ClientLevel.addEntity` for a server's lightning bolt: on a client it
/// only flashes, sounds and draws (`LightningBolt.tick` off the server).
pub(super) fn spawn_remote_bolt(&mut self, id: u32, at: [f64; 3]) {
self.bolts.retain(|b| b.id != id);
let r = &mut self.world.random;
let seed = r.next_long();
let flashes = r.next_int_bound(3).unwrap_or(0) + 1;
self.lightning_seen[0] += 1;
self.bolts.push(Bolt {
id,
at,
life: 2,
flashes,
seed,
visual_only: true,
converted: Vec::new(),
});
}
/// `spawnFire`: fire at the strike point and `extra` random neighbours.
fn bolt_fire(&mut self, at: [f64; 3], extra: i32) {
if self.ui.difficulty < 2 {
@@ -222,6 +238,9 @@ impl Game<'_> {
}
}
if b.life >= 0 {
if self.flash == 0 {
self.lightning_seen[1] += 1;
}
self.flash = 2;
if !b.visual_only {
self.thunder_hit(b);
@@ -349,71 +368,14 @@ impl Game<'_> {
|| e.stack.item.contains("netherite")
});
}
/// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8
/// segments of 16 blocks, from the bolt's seed.
pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let white = self.gui.atlas.font.white();
let uv = [white.u0, white.v0];
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
for b in &self.bolts {
let o = (glam::DVec3::from_array(b.at) - camera).as_vec3();
let mut random = LegacyRandom::new(b.seed);
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
let (mut x_off, mut z_off) = (0f32, 0f32);
for i in (0..8).rev() {
xs[i] = x_off;
zs[i] = z_off;
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
}
for layer in 0..4 {
let mut random = LegacyRandom::new(b.seed);
for branch in 0..3 {
let trunk = branch == 0;
let start = 7 - branch;
let end = if trunk { 0 } else { start - 3 + 1 };
let mut sx = xs[start] - x_off;
let mut sz = zs[start] - z_off;
for segment in (end..=start).rev() {
let (ex, ez) = (sx, sz);
let spread = if trunk { 11 } else { 31 };
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
let mut top = 0.1 + layer as f32 * 0.2;
let mut bottom = top;
if trunk {
top *= segment as f32 * 0.1 + 1.0;
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
}
for (rx, rz, lx, lz) in [
(false, false, true, false),
(true, false, true, true),
(true, true, false, true),
(false, true, false, false),
] {
let s = |p: bool, r: f32| if p { r } else { -r };
let y0 = segment as f32 * 16.0;
let corners = [
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
];
for c in corners {
out.push(Vertex {
normal: [0; 4],
pos: (o + glam::Vec3::from_array(c)).to_array(),
uv,
layer: 2,
color,
light: 240 | 240 << 8,
});
}
}
}
}
}
}
/// Simulation-order render inputs; seeded geometry lives in the renderer.
pub(super) fn bolt_instances(&self) -> Vec<horizon_client::gfx::lightning::Bolt> {
self.bolts
.iter()
.map(|b| horizon_client::gfx::lightning::Bolt {
at: b.at,
seed: b.seed,
})
.collect()
}
}
+4 -1
View File
@@ -775,10 +775,13 @@ impl Game<'_> {
self.push_carts();
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
// A server player's minecart moves with its rider (lan_vehicles.rs).
let ridden = self.guest_vehicles();
let mut i = 0;
while i < self.carts.len() {
let p = self.carts[i].position;
if Some(self.carts[i].id) == self.riding
|| ridden.contains(&self.carts[i].id)
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
{
i += 1;
@@ -986,7 +989,7 @@ impl Game<'_> {
let held = self.held().cloned();
match self.carts[i].kind {
CartKind::Rideable => {
if sneaking || self.riding.is_some() {
if sneaking || self.riding.is_some() || self.ridden_by_guest(self.carts[i].id) {
return false;
}
self.riding = Some(self.carts[i].id);
+273 -45
View File
@@ -7,7 +7,7 @@
//! client predicts its own movement; the server stays authoritative for
//! everything else.
use super::{Dim, Game, Mining, Screen};
use horizon_client::first_person::Hand;
use horizon_client::first_person::{Hand, SwingAnimation};
use horizon_client::{
Result,
chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy},
@@ -93,7 +93,7 @@ pub(super) struct Remote {
pub(super) registries: Arc<Dynamic>,
joined: bool,
status: String,
entity_id: i32,
pub(super) entity_id: i32,
dimension: DimensionType,
biome_map: Vec<u16>,
biome_bits: u8,
@@ -332,6 +332,11 @@ impl Game<'_> {
progress: 0.0,
total: 0,
};
// The connected client never opens a server world (single player also
// joins here), so load the registries its argument parsers and local
// suggestions need before receiving the server's command tree.
self.ui.registries = Default::default();
self.build_registries();
self.ui.registries.permission = 0;
self.ui.chat.clear();
self.screen = Screen::Playing;
@@ -1362,6 +1367,10 @@ impl Game<'_> {
self.turn_remote_projectile(id, rotation);
}
fn remove_entity(&mut self, id: i32) {
// The vehicle the player rode is gone (Entity.removeVehicle).
if self.riding == Some(id as u32) {
self.riding = None;
}
self.mobs.retain(|m| m.id != id as u32);
self.orbs.retain(|o| o.id != id as u32);
self.dropped.retain(|d| d.id != id as u32);
@@ -1748,6 +1757,8 @@ impl Game<'_> {
];
self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground);
}
C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers),
C::MoveVehicle(p) => self.remote_move_vehicle(p.position, p.yaw),
// ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3).
C::RotateHead(p) => {
if let Some(r) = self.remote.as_mut() {
@@ -2927,9 +2938,9 @@ impl Game<'_> {
self.capture_loaded_world();
}
let stick = self.pad_move();
let Some(player) = self.player.as_mut() else {
if self.player.is_none() {
return Ok(());
};
}
let playing = self.screen == Screen::Playing;
let held = |k| playing && self.keys.contains(&k);
let keys = Keys {
@@ -2950,7 +2961,14 @@ impl Game<'_> {
| u8::from(keys.jump) << 4
| u8::from(keys.shift) << 5
| u8::from(keys.sprint) << 6;
self.previous_position = player.position;
// A passenger moves with its vehicle (Entity.rideTick), not by itself.
let riding = self.screen != Screen::Dead && self.remote_ride(keys);
let Some(player) = self.player.as_mut() else {
return Ok(());
};
if !riding {
self.previous_position = player.position;
}
let before = (
player.ground.on_ground,
[player.velocity.x, player.velocity.y, player.velocity.z],
@@ -2967,7 +2985,7 @@ impl Game<'_> {
f64::from(head[2]) + 0.5,
);
player.velocity = Vec3::ZERO;
} else if !dead {
} else if !dead && !riding {
player.velocity = player.velocity.add_vector(pushed);
MotionWorld {
entities: &ghast_collisions,
@@ -3253,6 +3271,9 @@ impl Game<'_> {
};
self.tick_remote_objects(&mut step);
self.tick_remote_projectiles(&mut step);
// LightningBolt.tick on a client, and the sky flash fading.
self.flash = self.flash.saturating_sub(1);
self.tick_bolts();
}
lerps.retain(|_, l| l.steps > 0);
if let Some(r) = self.remote.as_mut() {
@@ -3314,6 +3335,8 @@ impl Game<'_> {
p.sprinting,
);
let (yaw, pitch, selected) = (self.yaw, self.pitch, self.selected);
let riding = self.riding.is_some();
let vehicle = self.remote_vehicle_packets();
let Some(r) = self.remote.as_mut() else {
return;
};
@@ -3336,9 +3359,18 @@ impl Game<'_> {
data: 0,
}));
}
if let Some(packet) = r
.position_sender
.update(pos, (yaw, pitch), on_ground, collision)
if riding {
// LocalPlayer.tick: a passenger sends its look, then the vehicle
// it controls.
out.push(S::MovePlayerRot(play::MovePlayerRot {
yaw,
pitch,
flags: u8::from(on_ground) | u8::from(collision) << 1,
}));
out.extend(vehicle);
} else if let Some(packet) =
r.position_sender
.update(pos, (yaw, pitch), on_ground, collision)
{
out.push(packet);
}
@@ -3458,10 +3490,8 @@ impl Game<'_> {
sequence: seq,
}));
if progress >= 1.0 {
// startDestroyBlock: instant survival breaks have no destroy delay.
self.predict_break(hit.pos, state, seq);
if let Some(r) = self.remote.as_mut() {
r.destroy_delay = 5;
}
return;
}
if let Some(r) = self.remote.as_mut() {
@@ -3571,6 +3601,21 @@ impl Game<'_> {
fn remote_use_entity(&mut self) -> bool {
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
// A boat, minecart, item frame, armor stand or painting nearer than
// any mob: the server uses it (AbstractBoat.interact boards it).
if let Some(hit) = self.remote_object_hit()
&& self.mob_hit().is_none_or(|(_, d)| hit.distance < d)
&& self.before_block(hit.distance)
{
self.send(S::Interact(play::Interact {
id: hit.id,
hand: 0,
location: hit.location,
secondary: sneaking,
}));
self.swing_arm();
return true;
}
if let Some((i, distance)) = self.mob_hit()
&& self.before_block(distance)
{
@@ -3638,7 +3683,15 @@ impl Game<'_> {
self.predict_use(&changes, seq);
}
if held_block {
self.with_hand(hand, Game::swing_arm);
if reacts
|| held
.as_ref()
.is_some_and(|stack| self.remote_can_place(&hit, stack))
{
self.with_hand(hand, Game::swing_arm);
}
// BlockItem.place returns FAIL when placement is rejected:
// stop this click without trying the item or the other hand.
return true;
}
return reacts;
@@ -3696,7 +3749,11 @@ impl Game<'_> {
/// container, and the blocks it changed. Vanilla's client runs it on its
/// own level first; this runs it on a copy, and `predict_use` keeps the
/// changes it predicts.
fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) {
fn remote_block_reacts(
&mut self,
hit: &super::Hit,
held: Option<&ItemStack>,
) -> (bool, DryUse) {
// Player.isSecondaryUseActive with something in either hand.
let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some();
if self.keys.contains(&KeyCode::ShiftLeft) && hands_full {
@@ -3711,26 +3768,53 @@ impl Game<'_> {
[-1, 0, 0] => Direction::West,
_ => Direction::East,
};
let mut level = DryLevel {
world: &self.world,
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
sounds: Vec::new(),
let player = self.use_context();
self.with_level(|b, level, _| {
let mut level = DryLevel::new(level);
let reacts = b
.use_item_on(
&mut level,
&mut horizon_world::level::Ticks::default(),
horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
player,
held.map(|s| &*s.item),
)
.consumes_action();
(reacts, (level.changed.into_iter().collect(), level.sounds))
})
}
/// Run BlockItem.place on a disposable level before predicting its swing.
/// The real level supplies collision shapes and building-blocking entities;
/// block writes, random draws, scheduled ticks and events stay in the preview.
fn remote_can_place(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool {
if !self.may_build() {
return false;
}
let ctx = horizon_world::level::PlaceContext {
clicked_pos: horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face: horizon_core::geometry::Direction::ALL[face_direction(hit.face) as usize],
hit: Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
inside: hit.face == [0; 3],
yaw: self.yaw,
pitch: self.pitch,
sneaking: self.keys.contains(&KeyCode::ShiftLeft),
item: stack.item.to_string(),
can_use_game_master_blocks: self.can_use_game_master_blocks(),
};
let reacts = self
.res
.behaviours()
.use_item_on(
&mut level,
&mut horizon_world::level::Ticks::default(),
horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
self.use_context(),
held.map(|s| &*s.item),
self.with_level(|b, level, _| {
let mut level = DryLevel::new(level);
matches!(
b.place_block(
&mut level,
&mut horizon_world::level::Ticks::default(),
&ctx
),
horizon_world::level::PlaceOutcome::Placed { .. }
)
.consumes_action();
(reacts, (level.changed.into_iter().collect(), level.sounds))
})
}
/// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether
@@ -3911,6 +3995,14 @@ impl Game<'_> {
id: self.creatures.projectiles[i].id as i32,
}));
self.reset_attack_strength();
} else if let Some(hit) = self.remote_object_hit()
&& self.mob_hit().is_none_or(|(_, d)| hit.distance < d)
&& self.before_block(hit.distance)
{
// VehicleEntity.hurtServer, ItemFrame and ArmorStand hurtServer,
// a painting broken: the server decides.
self.send(S::Attack(play::Attack { id: hit.id }));
self.reset_attack_strength();
} else if let Some((i, distance)) = self.mob_hit()
&& self.before_block(distance)
{
@@ -3985,23 +4077,26 @@ impl Game<'_> {
Ok(true)
}
KeyCode::KeyQ => {
if self.spectator() {
return Ok(true);
}
let all = self.keys.contains(&KeyCode::ControlLeft);
// MultiPlayerGameMode.dropItem: predict removal before sending
// the action, then swing only if a nonempty stack was removed.
let dropped = horizon_client::items::take_held_drop(
&mut self.inventory[self.selected],
all,
false,
);
self.send(S::PlayerAction(play::PlayerAction {
action: if all { 4 } else { 5 },
pos: [0; 3],
direction: 0,
sequence: 0,
}));
// Inventory.removeFromSelected (prediction).
let slot = &mut self.inventory[self.selected];
if let Some(s) = slot {
if all || s.count <= 1 {
*slot = None;
} else {
s.count -= 1;
}
if dropped.is_some() {
self.swing_hand(Hand::Main, SwingAnimation::DEFAULT);
}
self.swing_arm();
Ok(true)
}
KeyCode::KeyE => {
@@ -4678,7 +4773,7 @@ pub(super) fn input_ordinal(input: Input) -> i32 {
/// The client's world for a guess at what a click does: reads go to the
/// world, writes stay here and are dropped.
struct DryLevel<'w> {
world: &'w horizon_client::world::World,
base: &'w dyn horizon_world::level::LevelAccess,
changed: HashMap<horizon_core::position::BlockPos, BlockStateId>,
random: horizon_core::random::LegacyRandom,
/// The sounds the use plays (a door's creak).
@@ -4708,6 +4803,17 @@ pub(super) fn hand_operated(name: &str) -> bool {
|| name == "lever"
}
impl<'w> DryLevel<'w> {
fn new(base: &'w dyn horizon_world::level::LevelAccess) -> Self {
Self {
base,
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
sounds: Vec::new(),
}
}
}
impl horizon_world::level::LevelAccess for DryLevel<'_> {
fn emit(&mut self, event: horizon_world::level::LevelEvent) {
if let horizon_world::level::LevelEvent::Sound {
@@ -4724,7 +4830,7 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> {
self.changed
.get(&pos)
.copied()
.unwrap_or_else(|| self.world.block(pos.x, pos.y, pos.z))
.unwrap_or_else(|| self.base.block_state(pos))
}
fn set_raw(
&mut self,
@@ -4736,13 +4842,31 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> {
Some(previous)
}
fn is_loaded(&self, pos: horizon_core::position::BlockPos) -> bool {
self.world.loaded(pos.x, pos.z)
self.base.is_loaded(pos)
}
fn min_y(&self) -> i32 {
self.base.min_y()
}
fn max_y(&self) -> i32 {
self.base.max_y()
}
fn block_light(&self, pos: horizon_core::position::BlockPos) -> i32 {
self.base.block_light(pos)
}
fn sky_light(&self, pos: horizon_core::position::BlockPos) -> i32 {
self.base.sky_light(pos)
}
fn sky_darken(&self) -> i32 {
self.base.sky_darken()
}
fn is_unobstructed(&self, pos: horizon_core::position::BlockPos, state: BlockStateId) -> bool {
self.base.is_unobstructed(pos, state)
}
fn random(&mut self) -> &mut horizon_core::random::LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
self.world.game_time
self.base.game_time()
}
}
@@ -4858,6 +4982,110 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_
mod tests {
use super::Game;
#[test]
fn placement_preview_checks_obstruction_without_changing_the_level() {
use super::DryLevel;
use horizon_core::{position::BlockPos, random::LegacyRandom};
use horizon_world::{
level::{
Behaviours, LevelAccess, PlaceContext, PlaceOutcome, Ticks, data::load_registry,
},
registry::BlockStateId,
};
struct Level {
air: BlockStateId,
stone: BlockStateId,
obstructed: bool,
loaded: bool,
ceiling: i32,
}
impl LevelAccess for Level {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
if pos == BlockPos::new(0, 0, 0) {
self.stone
} else {
self.air
}
}
fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option<BlockStateId> {
panic!("preview must not write to the live level");
}
fn is_loaded(&self, _: BlockPos) -> bool {
self.loaded
}
fn max_y(&self) -> i32 {
self.ceiling
}
fn is_unobstructed(&self, pos: BlockPos, _: BlockStateId) -> bool {
assert_eq!(pos, BlockPos::new(0, 1, 0));
!self.obstructed
}
fn random(&mut self) -> &mut LegacyRandom {
panic!("preview must not advance the live level's random source");
}
fn game_time(&self) -> i64 {
0
}
}
// As with the LAN tests, prepared game resources are optional locally.
let resources = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
if !resources.join("block-behaviours.json").exists() {
return;
}
let registry = load_registry(&resources).unwrap();
let behaviours = Behaviours::load(&registry, &resources).unwrap();
let mut base = Level {
air: registry.default_state("minecraft:air").unwrap(),
stone: registry.default_state("minecraft:stone").unwrap(),
obstructed: false,
loaded: true,
ceiling: 320,
};
for item in [
"minecraft:stone",
"minecraft:oak_slab",
"minecraft:oak_door",
// GrowingPlantHeadBlock.getStateForPlacement draws a random age.
"minecraft:twisting_vines",
] {
let ctx = PlaceContext {
clicked_pos: BlockPos::new(0, 0, 0),
face: horizon_core::geometry::Direction::Up,
hit: horizon_core::geometry::Vec3::new(0.5, 1.0, 0.5),
inside: false,
yaw: 0.0,
pitch: 45.0,
sneaking: false,
item: item.into(),
can_use_game_master_blocks: false,
};
for (obstructed, loaded, ceiling) in [
(false, true, 320),
(true, true, 320),
(false, false, 320),
(false, true, 1),
] {
base.obstructed = obstructed;
base.loaded = loaded;
base.ceiling = ceiling;
let valid = !obstructed && loaded && ceiling > 1;
let mut preview = DryLevel::new(&base);
let outcome = behaviours.place_block(&mut preview, &mut Ticks::default(), &ctx);
assert_eq!(
matches!(outcome, PlaceOutcome::Placed { .. }),
valid,
"{item}, obstructed={obstructed}, loaded={loaded}, ceiling={ceiling}"
);
assert_eq!(preview.changed.is_empty(), !valid);
assert_eq!(base.block_state(BlockPos::new(0, 1, 0)), base.air);
}
}
}
#[test]
fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() {
// InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand.
@@ -52,6 +52,8 @@ impl Game<'_> {
invisible: false,
check_interval: 0,
});
} else if kind == "minecraft:lightning_bolt" {
self.spawn_remote_bolt(id, position);
} else if kind == "minecraft:painting" {
// The variant comes with the entity data; until then the
// registry's first one (VariantUtils.getAny).
@@ -188,7 +190,12 @@ impl Game<'_> {
/// A move's rotation and ground state for an object.
pub(super) fn turn_remote_object(&mut self, id: i32, yaw: Option<f32>, on_ground: bool) {
let id = id as u32;
// The boat the player drives turns here (isLocalInstanceAuthoritative).
let driven = self.riding;
if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
if Some(id) == driven {
return;
}
if let Some(yaw) = yaw {
b.yaw = yaw;
}
@@ -213,7 +220,12 @@ impl Game<'_> {
c.previous_yaw = c.yaw;
c.position = step(c.id, c.position);
}
// The boat the player drives moves here, not where the server says.
let driven = self.riding;
for b in &mut self.boats {
if Some(b.id) == driven {
continue;
}
b.previous = b.position;
b.previous_yaw = b.yaw;
b.position = step(b.id, b.position);
@@ -274,5 +286,6 @@ impl Game<'_> {
self.armor_stands.retain(|a| a.id != id);
self.item_frames.retain(|f| f.id != id);
self.paintings.retain(|p| p.id != id);
self.bolts.retain(|b| b.id != id);
}
}
@@ -0,0 +1,181 @@
//! Boats, minecarts, item frames, armor stands and paintings for a server's
//! client: single player on its server thread, a LAN guest, a player on a
//! dedicated server.
//!
//! The client aims at them like at mobs (`Minecraft.hitResult`, then
//! `ServerboundInteractPacket`), and rides the vehicle the server seats it in
//! (`ClientPacketListener.handleSetEntityPassengersPacket`). A boat is
//! controlled by its rider's client: it ticks here and its moves go to the
//! server (`LocalPlayer.tick`: `ServerboundMoveVehiclePacket`,
//! `AbstractBoat.tick`: `ServerboundPaddleBoatPacket`). A minecart moves on
//! the server with the rider's input, and the rider sits in it.
use super::{Game, Keys, view_vector};
use horizon_core::geometry::Vec3;
use horizon_protocol::packets::play::{self, Serverbound as S};
/// An object under the crosshair: its entity id, how far along the view it
/// was hit, and where (`EntityHitResult.getLocation` minus the entity's
/// position, the interact packet's location).
pub(super) struct ObjectHit {
pub id: i32,
pub distance: f64,
pub location: [f64; 3],
}
impl Game<'_> {
/// The nearest boat, minecart, item frame, armor stand or painting the
/// view hits within reach.
pub(super) fn remote_object_hit(&self) -> Option<ObjectHit> {
let eye = self.eye_position()?;
let dir = view_vector(self.yaw, self.pitch);
let at = |d: f64| {
[
eye[0] + dir[0] * d,
eye[1] + dir[1] * d,
eye[2] + dir[2] * d,
]
};
let block_centre = |p: [i32; 3]| {
[
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
]
};
let mut hits: Vec<(i32, f64, [f64; 3])> = Vec::new();
if let Some((i, d)) = self.painting_hit() {
let p = &self.paintings[i];
hits.push((p.id as i32, d, block_centre(p.pos)));
}
if let Some((i, d)) = self.frame_hit() {
let f = &self.item_frames[i];
hits.push((f.id as i32, d, block_centre(f.pos)));
}
if let Some((i, d, _)) = self.armor_stand_hit() {
let a = &self.armor_stands[i];
let p = a.position;
hits.push((a.id as i32, d, [p.x, p.y, p.z]));
}
if let Some((i, d)) = self.boat_hit() {
let p = self.boats[i].position;
hits.push((self.boats[i].id as i32, d, [p.x, p.y, p.z]));
}
if let Some((i, d)) = self.cart_hit() {
let p = self.carts[i].position;
hits.push((self.carts[i].id as i32, d, [p.x, p.y, p.z]));
}
let (id, distance, origin) = hits.into_iter().min_by(|a, b| a.1.total_cmp(&b.1))?;
let point = at(distance);
Some(ObjectHit {
id,
distance,
location: [
point[0] - origin[0],
point[1] - origin[1],
point[2] - origin[2],
],
})
}
/// `ClientPacketListener.handleSetEntityPassengersPacket`: who rides
/// `vehicle` now. The local player gets in or out; mobs and other
/// players sit where the server keeps them.
pub(super) fn remote_set_passengers(&mut self, vehicle: i32, passengers: &[i32]) {
let Some(me) = self.remote.as_ref().map(|r| r.entity_id) else {
return;
};
let vehicle_id = vehicle as u32;
for m in &mut self.mobs {
if m.extra.mount == Some(vehicle_id) && !passengers.contains(&(m.id as i32)) {
m.extra.mount = None;
} else if passengers.contains(&(m.id as i32)) {
m.extra.mount = Some(vehicle_id);
}
}
if passengers.contains(&me) {
if self.riding != Some(vehicle_id) {
self.riding = Some(vehicle_id);
if let Some(p) = self.player.as_mut() {
p.velocity = Vec3::ZERO;
p.fall_distance = 0.0;
}
}
} else if self.riding == Some(vehicle_id) {
// The server takes the player out, then teleports it.
self.riding = None;
}
}
/// The local player's tick in its vehicle, in place of its own movement:
/// false when it rides nothing.
pub(super) fn remote_ride(&mut self, keys: Keys) -> bool {
let Some(id) = self.riding else {
return false;
};
let seat = if let Some(i) = self.boats.iter().position(|b| b.id == id) {
// AbstractBoat.tick on the controlling client: steer and move.
let mut b = self.boats[i].clone();
b.input = [keys.left, keys.right, keys.forward, keys.backward];
let b = self.tick_boat(b, true);
// positionRider: the seat turns with the boat; clampRotation.
self.yaw += b.delta_rotation;
let delta = (self.yaw - b.yaw + 180.0).rem_euclid(360.0) - 180.0;
self.yaw += delta.clamp(-105.0, 105.0) - delta;
let seat = b.position;
self.boats[i] = b;
Some(seat)
} else {
// A minecart: the server moves it, the rider sits in it.
self.carts.iter().find(|c| c.id == id).map(|c| c.position)
};
if let Some(p) = self.player.as_mut() {
self.previous_position = p.position;
if let Some(v) = seat {
p.position = Vec3::new(v.x, v.y + super::boats::SEAT, v.z);
}
p.velocity = Vec3::ZERO;
p.fall_distance = 0.0;
}
true
}
/// `LocalPlayer.tick` for a passenger: the boat it controls goes to the
/// server every tick with its paddles (the rider's own position does not).
pub(super) fn remote_vehicle_packets(&self) -> Vec<S> {
let Some(b) = self
.riding
.and_then(|id| self.boats.iter().find(|b| b.id == id))
else {
return Vec::new();
};
vec![
S::MoveVehicle(play::MoveVehicleRequest {
position: [b.position.x, b.position.y, b.position.z],
yaw: b.yaw,
pitch: 0.0,
on_ground: b.on_ground,
}),
S::PaddleBoat(play::PaddleBoat {
left: b.paddling[0],
right: b.paddling[1],
}),
]
}
/// `ClientPacketListener.handleMoveVehicle`: the server put the boat the
/// player drives back.
pub(super) fn remote_move_vehicle(&mut self, position: [f64; 3], yaw: f32) {
let Some(b) = self
.riding
.and_then(|id| self.boats.iter_mut().find(|b| b.id == id))
else {
return;
};
let at = Vec3::new(position[0], position[1], position[2]);
b.previous = at;
b.position = at;
b.yaw = yaw;
b.previous_yaw = yaw;
b.velocity = Vec3::ZERO;
}
}
+46 -1
View File
@@ -7,6 +7,24 @@ use horizon_client::{
ui,
};
impl Screen {
/// Screen.extractBackground for non-isInGameUi screens, and
/// PauseScreen.extractBackground only when showPauseMenu is true.
pub(super) fn blurs_background(self, pause_menu: bool) -> bool {
match self {
Self::Paused => pause_menu,
Self::Options | Self::Stats | Self::Advancements | Self::WorldOptions => true,
Self::Playing
| Self::GameModeSwitcher
| Self::Chat
| Self::Creative
| Self::Inventory
| Self::Dead
| Self::CommandBlock => false,
}
}
}
/// PauseScreen buttons: (x, y, width, label key, action id, active).
/// https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/PauseScreen
fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static str, u8, bool)> {
@@ -334,7 +352,34 @@ impl Game<'_> {
#[cfg(test)]
mod tests {
use super::pause_buttons;
use super::{Screen, pause_buttons};
#[test]
fn menu_blur_matches_vanilla_screen_backgrounds() {
for screen in [
Screen::Options,
Screen::Stats,
Screen::Advancements,
Screen::WorldOptions,
] {
assert!(screen.blurs_background(false));
assert!(screen.blurs_background(true));
}
assert!(Screen::Paused.blurs_background(true));
assert!(!Screen::Paused.blurs_background(false));
for screen in [
Screen::Playing,
Screen::GameModeSwitcher,
Screen::Chat,
Screen::Creative,
Screen::Inventory,
Screen::Dead,
Screen::CommandBlock,
] {
assert!(!screen.blurs_background(true));
assert!(!screen.blurs_background(false));
}
}
#[test]
fn pause_menu_uses_disconnect_for_servers_and_keeps_world_options() {
+104 -14
View File
@@ -33,6 +33,7 @@ fn entity_shader() -> String {
}
mod entity_batch;
mod weather;
use entity_batch::EntityBatch;
pub use entity_batch::WATER_MASK_OVERLAY;
@@ -61,8 +62,10 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6]
mod arena;
mod cull;
mod end_sky;
mod flat;
mod java_stages;
pub mod lightning;
mod lod;
mod occlusion;
mod pack_stages;
@@ -163,8 +166,10 @@ pub struct Frame<'a> {
pub title: bool,
/// Dimensions without a skybox (the Nether) clear to the fog colour.
pub skybox: bool,
/// The End: clear to black and draw `celestial` (the End sky box) behind the world.
/// The End: clear to black and draw the resident sky box behind the world.
pub end_sky: bool,
/// End sky atlas bounds (u0, v0, u1, v1); absent when the sprite is missing.
pub end_sky_sprite: Option<[f32; 4]>,
/// Environmental fog start/end (Nether 10..96), if any.
pub environment_fog: Option<(f32, f32)>,
pub water_fog: [f32; 3],
@@ -189,16 +194,20 @@ pub struct Frame<'a> {
pub nether_lighting: bool,
/// Camera-relative entity geometry textured from the shared atlas.
pub entities: &'a [Vertex],
pub weather: &'a [crate::weather::Vertex],
pub weather_time: crate::weather::Time,
/// Horizon Extras' dynamic lights, nearest first (`dynamic_light::select`); empty when off.
pub dynamic_lights: &'a [[f32; 4]],
/// Cloud mesh inputs; geometry and GPU storage are retained by the renderer.
pub clouds: Option<crate::clouds::Input<'a>>,
/// Additive translucent geometry after the entities (lightning, dragon rays).
/// Retained lightning bolts, drawn before the other additive entities.
pub lightning: lightning::Input<'a>,
/// Additive translucent geometry after lightning (dragon rays).
pub additive: &'a [Vertex],
/// Name tags over everything, without depth (`TEXT_SEE_THROUGH`).
pub see_through: &'a [Vertex],
/// Camera-relative sun and moon, or the End sky box (drawn behind
/// everything, additive).
/// Camera-relative sun and moon, or the animated End flash (additive,
/// behind everything and after the resident End sky box).
pub celestial: &'a [Vertex],
/// The stars, drawn from their static buffer after the sun and moon:
/// the sky's rotation (camera-relative world from star space) and the
@@ -324,6 +333,7 @@ pub struct Renderer {
crosshair_group: wgpu::BindGroup,
crosshair_globals: wgpu::Buffer,
entity_pipeline: wgpu::RenderPipeline,
weather: weather::Weather,
crumbling_pipeline: wgpu::RenderPipeline,
/// `RenderPipelines.WATER_MASK`: depth writes only, no colour.
water_mask_pipeline: wgpu::RenderPipeline,
@@ -334,9 +344,12 @@ pub struct Renderer {
cloud_uniform: wgpu::Buffer,
cloud_group: wgpu::BindGroup,
additive_pipeline: wgpu::RenderPipeline,
lightning_pipeline: wgpu::RenderPipeline,
lightning: lightning::Renderer,
see_through_pipeline: wgpu::RenderPipeline,
celestial_pipeline: wgpu::RenderPipeline,
celestial_buffer: wgpu::Buffer,
end_sky: end_sky::EndSky,
stars: stars::Stars,
panorama: panorama::Panorama,
/// `RenderPipelines.WORLD_BORDER` and its buffers.
@@ -1445,6 +1458,12 @@ impl Renderer {
),
],
});
let weather = weather::Weather::new(
&device,
config.format.remove_srgb_suffix(),
&entity_bindings,
&entity_shader,
);
let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Atlas"),
..Default::default()
@@ -1664,8 +1683,17 @@ impl Renderer {
alpha_blend,
false,
);
let lightning_attributes = wgpu::vertex_attr_array![6=>Float32x3];
let lightning_vertex = [
entity_vertex[0].clone(),
Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<[f32; 3]>() as u64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &lightning_attributes,
}),
];
// BlendFunction.LIGHTNING: src alpha, one; no depth writes.
let additive_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
let additive_descriptor = wgpu::RenderPipelineDescriptor {
label: Some("Additive entities"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
@@ -1709,6 +1737,16 @@ impl Renderer {
}),
multiview_mask: None,
cache: None,
};
let additive_pipeline = device.create_render_pipeline(&additive_descriptor);
let lightning_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Lightning"),
vertex: wgpu::VertexState {
entry_point: Some("vs_lightning"),
buffers: &lightning_vertex,
..additive_descriptor.vertex.clone()
},
..additive_descriptor
});
let celestial_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Celestial bodies"),
@@ -2101,6 +2139,7 @@ impl Renderer {
crosshair_group,
crosshair_globals,
entity_pipeline,
weather,
crumbling_pipeline,
water_mask_pipeline,
cloud_pipeline,
@@ -2110,9 +2149,12 @@ impl Renderer {
cloud_uniform,
cloud_group,
additive_pipeline,
lightning_pipeline,
lightning: lightning::Renderer::new(),
see_through_pipeline,
celestial_pipeline,
celestial_buffer,
end_sky: end_sky::EndSky::default(),
stars,
panorama,
border_pipeline,
@@ -3229,6 +3271,13 @@ impl Renderer {
bytemuck::cast_slice(&all),
);
}
self.weather.prepare(
&self.device,
&mut encoder,
&mut self.uploads,
frame.weather,
frame.weather_time,
);
let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize);
if outline_edges > 0 {
let lines = outline_vertices(&frame.outline[..outline_edges], camera);
@@ -3246,6 +3295,7 @@ impl Renderer {
frame.hand,
frame.see_through,
);
let weather_quads = frame.weather.len() as u32 / 4;
let world_quads =
entity_quads + crumbling_quads + translucent_crumbling_quads + water_mask_quads;
let cloud_quads = if let Some(input) = &frame.clouds {
@@ -3279,6 +3329,13 @@ impl Renderer {
} else {
0
};
self.lightning.prepare(
&self.device,
&mut self.uploads,
&mut encoder,
&frame.lightning,
camera,
);
let all_entities = &self.entity_batch.combined;
let hand_quads = (frame.hand.len() / 4) as u32;
let additive_quads = (frame.additive.len() / 4) as u32;
@@ -3310,6 +3367,9 @@ impl Renderer {
);
}
let celestial_vertices = frame.celestial.len().min(2048 * 4);
if frame.end_sky && !frame.title {
self.end_sky.prepare(&self.device, frame.end_sky_sprite);
}
if celestial_vertices > 0 {
self.uploads.buffer(
&mut encoder,
@@ -3318,8 +3378,14 @@ impl Renderer {
bytemuck::cast_slice(&frame.celestial[..celestial_vertices]),
);
}
let max_quads =
(world_quads + additive_quads + hand_quads + see_through_quads).max(cloud_quads);
let max_quads = (world_quads + additive_quads + hand_quads + see_through_quads)
.max(cloud_quads)
.max(if frame.lightning.bolts.is_empty() {
0
} else {
lightning::QUADS
})
.max(weather_quads);
if max_quads > self.index_quads {
self.index_quads = max_quads.next_power_of_two();
self.indices = Self::quad_indices(&self.device, self.index_quads);
@@ -3510,12 +3576,17 @@ impl Renderer {
if frame.title {
self.panorama.draw(&mut pass);
pass.set_bind_group(0, &self.group, &[]);
} else if celestial_vertices > 0 {
} else if celestial_vertices > 0 || frame.end_sky {
pass.set_pipeline(&self.celestial_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.celestial_buffer.slice(..));
pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1);
if frame.end_sky {
self.end_sky.draw(&mut pass);
}
if celestial_vertices > 0 {
pass.set_vertex_buffer(0, self.celestial_buffer.slice(..));
pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1);
}
pass.set_bind_group(0, &self.group, &[]);
}
if !frame.title && frame.stars.is_some() {
@@ -3602,6 +3673,8 @@ impl Renderer {
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
self.weather.draw(&mut pass, &self.entity_group);
pass.set_bind_group(0, &self.group, &[]);
if crumbling_quads > 0 {
pass.set_pipeline(&self.crumbling_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
@@ -3622,6 +3695,12 @@ impl Renderer {
);
pass.set_bind_group(0, &self.group, &[]);
}
if !frame.lightning.bolts.is_empty() {
pass.set_pipeline(&self.lightning_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
self.lightning.draw(&mut pass, &frame.lightning);
pass.set_bind_group(0, &self.group, &[]);
}
if additive_quads > 0 {
pass.set_pipeline(&self.additive_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
@@ -3841,9 +3920,19 @@ impl Renderer {
let first = debug_depth + debug_top;
pass.draw(0..4, first..first + crosshair);
}
if let Some(radius) = frame.menu_blur
&& self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
{
let menu_blur = frame
.menu_blur
.filter(|_| self.config.usage.contains(wgpu::TextureUsages::COPY_SRC));
let blur_at = menu_blur.map_or(0, |_| frame.hud.blur_at);
self.hud.draw_range(
&mut encoder,
&view_target,
&self.depth,
frame.hud,
[self.config.width, self.config.height],
0..blur_at,
);
if let Some(radius) = menu_blur {
let format = self.config.format;
let device = &self.device;
self.menu_blur
@@ -3875,12 +3964,13 @@ impl Renderer {
grade,
);
}
self.hud.draw(
self.hud.draw_range(
&mut encoder,
&view_target,
&self.depth,
frame.hud,
[self.config.width, self.config.height],
blur_at..frame.hud.vertices.len() as u32,
);
if culling && let Some(cull) = &mut self.cull {
cull.end(&self.device, &mut encoder);
+84
View File
@@ -0,0 +1,84 @@
//! The End sky's six tiled faces, retained for the lifetime of the renderer's atlas.
use crate::mesher::Vertex;
use wgpu::util::DeviceExt;
const VERTICES: u32 = 6 * 16 * 16 * 4;
#[derive(Default)]
pub(super) struct EndSky {
mesh: Option<([f32; 4], wgpu::Buffer)>,
}
impl EndSky {
/// Called only when the End sky is enabled. Rebuild on atlas UV changes;
/// resource reload and device recreation also replace the owning renderer.
pub(super) fn prepare(&mut self, device: &wgpu::Device, uv: Option<[f32; 4]>) {
let Some(uv) = uv else {
self.mesh = None;
return;
};
if self.mesh.as_ref().is_some_and(|(old, _)| *old == uv) {
return;
}
let vertices = vertices(uv);
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("End sky vertices"),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
self.mesh = Some((uv, buffer));
}
/// The celestial pipeline, atlas bind group and quad indices are already bound.
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {
if let Some((_, buffer)) = &self.mesh {
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw_indexed(0..VERTICES / 4 * 6, 0, 0..1);
}
}
}
/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times,
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
fn vertices(uv: [f32; 4]) -> Vec<Vertex> {
let mut out = Vec::with_capacity(VERTICES as usize);
use std::f32::consts::FRAC_PI_2;
let faces = [
glam::Mat4::IDENTITY,
glam::Mat4::from_rotation_x(FRAC_PI_2),
glam::Mat4::from_rotation_x(-FRAC_PI_2),
glam::Mat4::from_rotation_x(std::f32::consts::PI),
glam::Mat4::from_rotation_z(FRAC_PI_2),
glam::Mat4::from_rotation_z(-FRAC_PI_2),
];
let step = 200.0 / 16.0;
for pose in faces {
for a in 0..16 {
for b in 0..16 {
let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32);
let (x1, z1) = (x0 + step, z0 + step);
let corners = [
(x0, z0, [uv[0], uv[1]]),
(x0, z1, [uv[0], uv[3]]),
(x1, z1, [uv[2], uv[3]]),
(x1, z0, [uv[2], uv[1]]),
];
for (x, z, uv) in corners {
let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z));
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 2,
color: 0xFF28_2828,
light: 0,
});
}
}
}
}
out
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,330 @@
use super::*;
use crate::gfx::{Globals, Renderer};
use bytemuck::Zeroable;
use glam::Mat4;
#[test]
fn geometry_matches_pre_residency_vertex_snapshots() {
use sha2::{Digest, Sha256};
// Captured from game/end.rs at 34c3c1cf for full, tiled and non-binary UVs.
// Quantize positions only, avoiding platform sin/cos rounding differences;
// quad order, UVs, tint, material and light retain their exact byte values.
for (uv, expected) in [
(
[0.0, 0.0, 1.0, 1.0],
"f7ee23457fc557b33ecf09c9afaf858f3d8907e108abf06055f627523f733536",
),
(
[0.125, 0.25, 0.375, 0.5],
"f74c4b8d23ec2b7c11b5752821d0733851bf11358f1b26f9448226ff62a6a318",
),
(
[0.13, 0.27, 0.41, 0.59],
"f0aaa39c5b22168bdc7c6c329acb4d3598a2feb61ff7b6f2850b644682749b39",
),
] {
let mut mesh = vertices(uv);
assert_eq!(mesh.len(), VERTICES as usize);
for vertex in &mut mesh {
vertex.pos = vertex.pos.map(|x| {
let n = (x * 1024.0).round() / 1024.0;
if n == 0.0 { 0.0 } else { n }
});
}
assert_eq!(
format!("{:x}", Sha256::digest(bytemuck::cast_slice(&mesh))),
expected
);
}
}
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
eprintln!("End sky test adapter: {:?}", adapter.get_info());
pollster::block_on(adapter.request_device(&Default::default())).ok()
}
#[test]
fn resident_buffer_survives_frames_and_refreshes_with_the_atlas() {
let Some((device, _)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
let mut sky = EndSky::default();
let uv = [0.125, 0.25, 0.375, 0.5];
sky.prepare(&device, Some(uv));
let first = sky.mesh.as_ref().unwrap().1.clone();
assert_eq!(
first.size(),
u64::from(VERTICES) * size_of::<Vertex>() as u64
);
// Immutable: steady-state frames cannot upload into this buffer.
assert_eq!(first.usage(), wgpu::BufferUsages::VERTEX);
for _ in 0..600 {
sky.prepare(&device, Some(uv));
assert_eq!(sky.mesh.as_ref().unwrap().1, first);
}
let moved = [0.5, 0.5, 0.75, 0.75];
sky.prepare(&device, Some(moved));
assert_ne!(sky.mesh.as_ref().unwrap().1, first);
assert_eq!(sky.mesh.as_ref().unwrap().0, moved);
sky.prepare(&device, None);
assert!(sky.mesh.is_none());
sky.prepare(&device, Some(uv));
assert_ne!(sky.mesh.as_ref().unwrap().1, first);
// A resource reload/device recreation starts a new renderer-owned cache,
// even if the replacement atlas happens to use exactly the same UVs.
let mut replacement = EndSky::default();
replacement.prepare(&device, Some(uv));
assert_ne!(
replacement.mesh.as_ref().unwrap().1,
sky.mesh.as_ref().unwrap().1
);
}
/// The actual entity shader and celestial blend, comparing the old combined
/// vertex stream with a resident sky draw followed by a separate flash draw.
#[test]
fn separate_draws_match_combined_celestial_pixels() {
let Some((device, queue)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("End sky differential shader"),
source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()),
});
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("End sky differential pipeline"),
layout: None,
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_entity"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_celestial"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba8Unorm,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::OVER,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let texture = |pixels: &[u8], width, height| {
device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
pixels,
)
};
// Asymmetric, translucent texels expose UV/winding and blend-order errors.
let pixels: Vec<u8> = (0..16 * 16)
.flat_map(|i| {
[
(i * 17) as u8,
(i * 31) as u8,
(i * 7) as u8,
(80 + i % 176) as u8,
]
})
.collect();
let atlas = texture(&pixels, 16, 16).create_view(&Default::default());
let lightmap = texture(&[255; 4], 1, 1).create_view(&Default::default());
let sampler = device.create_sampler(&Default::default());
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let indices = Renderer::quad_indices(&device, VERTICES / 4 + 1);
let mut resident = EndSky::default();
let uv = [0.125, 0.25, 0.375, 0.5];
resident.prepare(&device, Some(uv));
let first = resident.mesh.as_ref().unwrap().1.clone();
let render = |sky: &EndSky, flash: &[Vertex], combined: bool| {
let target = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 64,
height: 64,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&Default::default());
let mut vertices = if combined { vertices(uv) } else { Vec::new() };
vertices.extend_from_slice(flash);
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 64 * 64 * 4,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &group, &[]);
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
if !combined {
sky.draw(&mut pass);
}
if !vertices.is_empty() {
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw_indexed(0..vertices.len() as u32 / 4 * 6, 0, 0..1);
}
}
encoder.copy_texture_to_buffer(
target.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(256),
rows_per_image: Some(64),
},
},
target.size(),
);
queue.submit([encoder.finish()]);
readback
.slice(..)
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
readback.slice(..).get_mapped_range().unwrap().to_vec()
};
let mut cases = 0;
let mut visible_flash_cases = 0;
for yaw in [0.0_f32, 45.0, 90.0, 180.0, 270.0] {
for pitch in [-85.0_f32, -30.0, 0.0, 45.0, 85.0] {
let mut globals = Globals::zeroed();
globals.view_proj = (Mat4::perspective_rh(90_f32.to_radians(), 1.0, 0.05, 1024.0)
* Mat4::from_rotation_x(pitch.to_radians())
* Mat4::from_rotation_y(yaw.to_radians()))
.to_cols_array_2d();
queue.write_buffer(&uniform, 0, bytemuck::bytes_of(&globals));
let no_flash = render(&resident, &[], true);
for level in [0_u32, 1, 127, 255] {
let flash: Vec<_> = if level == 0 {
Vec::new()
} else {
// Same flash size/height, with an arbitrary EndFlashState pose.
let pose = Mat4::from_rotation_y(1.3) * Mat4::from_rotation_x(-1.6);
[(-60.0, -60.0), (60.0, -60.0), (60.0, 60.0), (-60.0, 60.0)]
.map(|(x, z)| Vertex {
pos: pose.transform_point3(glam::vec3(x, 100.0, z)).to_array(),
uv: [0.75 + x / 480.0, 0.75 + z / 480.0],
layer: 2,
color: level * 0x01010101,
light: 0,
normal: [0; 4],
})
.to_vec()
};
resident.prepare(&device, Some(uv));
let expected = render(&resident, &flash, true);
let actual = render(&resident, &flash, false);
visible_flash_cases += usize::from(expected != no_flash);
assert_eq!(actual, expected, "yaw={yaw} pitch={pitch} flash={level}");
assert!(
actual.as_chunks::<4>().0.iter().any(|p| p[..3] != [0; 3]),
"empty frame"
);
assert_eq!(resident.mesh.as_ref().unwrap().1, first);
cases += 1;
}
}
}
assert!(
visible_flash_cases > 0,
"the flash must affect the comparison"
);
eprintln!("{cases} combined/resident framebuffer cases matched exactly");
}
+211
View File
@@ -0,0 +1,211 @@
//! Seeded, bolt-local lightning meshes retained until their last active bolt disappears.
use crate::{gfx::upload::Uploads, mesher::Vertex};
use glam::DVec3;
use horizon_core::random::{LegacyRandom, RandomSource};
use std::collections::HashMap;
use wgpu::util::DeviceExt;
/// A bolt's render state. Simulation lifetime and flashes stay in the game.
#[derive(Clone, Copy)]
pub struct Bolt {
pub at: [f64; 3],
pub seed: i64,
}
#[derive(Default)]
pub struct Input<'a> {
pub bolts: &'a [Bolt],
/// Current atlas white texel; a changed rect invalidates retained vertices.
pub uv: [f32; 2],
}
// Four layers, fourteen segments (eight trunk, two branches of three), four quads.
pub(super) const QUADS: u32 = 4 * 14 * 4;
/// `LightningBoltRenderer.submit`: keep random draws, layers and quad order unchanged.
fn geometry(seed: i64, uv: [f32; 2]) -> Vec<Vertex> {
let mut out = Vec::with_capacity(QUADS as usize * 4);
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
let mut random = LegacyRandom::new(seed);
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
let (mut x_off, mut z_off) = (0f32, 0f32);
for i in (0..8).rev() {
xs[i] = x_off;
zs[i] = z_off;
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
}
for layer in 0..4 {
let mut random = LegacyRandom::new(seed);
for branch in 0..3 {
let trunk = branch == 0;
let start = 7 - branch;
let end = if trunk { 0 } else { start - 3 + 1 };
let mut sx = xs[start] - x_off;
let mut sz = zs[start] - z_off;
for segment in (end..=start).rev() {
let (ex, ez) = (sx, sz);
let spread = if trunk { 11 } else { 31 };
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
let mut top = 0.1 + layer as f32 * 0.2;
let mut bottom = top;
if trunk {
top *= segment as f32 * 0.1 + 1.0;
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
}
for (rx, rz, lx, lz) in [
(false, false, true, false),
(true, false, true, true),
(true, true, false, true),
(false, true, false, false),
] {
let s = |p: bool, r: f32| if p { r } else { -r };
let y0 = segment as f32 * 16.0;
let corners = [
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
];
for c in corners {
out.push(Vertex {
normal: [0; 4],
pos: c,
uv,
layer: 2,
color,
light: 240 | 240 << 8,
});
}
}
}
}
}
out
}
struct Cached<T> {
mesh: T,
used: bool,
}
/// Shared seeds use the same mesh; storage is bounded by active unique seeds,
/// including after seed changes, removals, dimension switches and disconnects.
struct Cache<T> {
uv: Option<[f32; 2]>,
meshes: HashMap<i64, Cached<T>>,
}
impl<T> Cache<T> {
fn new() -> Self {
Self {
uv: None,
meshes: HashMap::new(),
}
}
fn prepare(&mut self, input: &Input<'_>, mut build: impl FnMut(i64, [f32; 2]) -> T) {
if self.uv != Some(input.uv) {
self.meshes.clear();
self.uv = Some(input.uv);
}
for cached in self.meshes.values_mut() {
cached.used = false;
}
for bolt in input.bolts {
self.meshes
.entry(bolt.seed)
.or_insert_with(|| Cached {
mesh: build(bolt.seed, input.uv),
used: true,
})
.used = true;
}
self.meshes.retain(|_, cached| cached.used);
// HashMap::retain keeps its allocation. Release historical peak capacity
// as well as meshes once the storm (or connection) is gone.
if self.meshes.is_empty() {
self.meshes = HashMap::new();
} else if self.meshes.capacity() > self.meshes.len() * 4 {
self.meshes.shrink_to_fit();
}
}
}
fn offset(bolt: &Bolt, camera: DVec3) -> [f32; 3] {
(DVec3::from_array(bolt.at) - camera).as_vec3().to_array()
}
pub(super) struct Renderer {
cache: Cache<wgpu::Buffer>,
instances: Option<wgpu::Buffer>,
capacity: usize,
}
impl Renderer {
pub(super) fn new() -> Self {
Self {
cache: Cache::new(),
instances: None,
capacity: 0,
}
}
pub(super) fn prepare(
&mut self,
device: &wgpu::Device,
uploads: &mut Uploads,
encoder: &mut wgpu::CommandEncoder,
input: &Input<'_>,
camera: DVec3,
) {
self.cache.prepare(input, |seed, uv| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Lightning vertices"),
contents: bytemuck::cast_slice(&geometry(seed, uv)),
usage: wgpu::BufferUsages::VERTEX,
})
});
if input.bolts.is_empty() {
self.instances = None;
self.capacity = 0;
return;
}
if input.bolts.len() > self.capacity || input.bolts.len() < self.capacity / 4 {
self.capacity = input.bolts.len().next_power_of_two();
self.instances = Some(device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Lightning offsets"),
size: (self.capacity * std::mem::size_of::<[f32; 3]>()) as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}));
}
let offsets: Vec<_> = input
.bolts
.iter()
.map(|bolt| offset(bolt, camera))
.collect();
uploads.buffer(
encoder,
self.instances.as_ref().unwrap(),
0,
bytemuck::cast_slice(&offsets),
);
}
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, input: &Input<'_>) {
let Some(instances) = &self.instances else {
return;
};
pass.set_vertex_buffer(1, instances.slice(..));
// Follow simulation order, including repeated seeds; HashMap order must
// never change additive accumulation or the order before dragon rays.
for (i, bolt) in input.bolts.iter().enumerate() {
pass.set_vertex_buffer(0, self.cache.meshes[&bolt.seed].mesh.slice(..));
pass.draw_indexed(0..QUADS * 6, 0, i as u32..i as u32 + 1);
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,495 @@
use super::*;
use std::cell::Cell;
// Frozen pre-cache generator: compare every Vertex byte, including primitive
// order and the original camera-relative rounding, without game resources.
fn reference(seed: i64, at: [f64; 3], camera: DVec3, uv: [f32; 2]) -> Vec<Vertex> {
let mut out = Vec::new();
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
let b = Bolt { seed, at };
{
let o = (glam::DVec3::from_array(b.at) - camera).as_vec3();
let mut random = LegacyRandom::new(b.seed);
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
let (mut x_off, mut z_off) = (0f32, 0f32);
for i in (0..8).rev() {
xs[i] = x_off;
zs[i] = z_off;
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
}
for layer in 0..4 {
let mut random = LegacyRandom::new(b.seed);
for branch in 0..3 {
let trunk = branch == 0;
let start = 7 - branch;
let end = if trunk { 0 } else { start - 3 + 1 };
let mut sx = xs[start] - x_off;
let mut sz = zs[start] - z_off;
for segment in (end..=start).rev() {
let (ex, ez) = (sx, sz);
let spread = if trunk { 11 } else { 31 };
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
let mut top = 0.1 + layer as f32 * 0.2;
let mut bottom = top;
if trunk {
top *= segment as f32 * 0.1 + 1.0;
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
}
for (rx, rz, lx, lz) in [
(false, false, true, false),
(true, false, true, true),
(true, true, false, true),
(false, true, false, false),
] {
let s = |p: bool, r: f32| if p { r } else { -r };
let y0 = segment as f32 * 16.0;
let corners = [
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
];
for c in corners {
out.push(Vertex {
normal: [0; 4],
pos: (o + glam::Vec3::from_array(c)).to_array(),
uv,
layer: 2,
color,
light: 240 | 240 << 8,
});
}
}
}
}
}
}
out
}
fn seeds() -> Vec<i64> {
let mut seeds = vec![0, 1, -1, i64::MIN, i64::MAX, 0x123456789abcdef];
let mut random = LegacyRandom::new(42);
seeds.extend((0..256).map(|_| random.next_long()));
seeds
}
/// Pinned 26.3 LightningBoltRenderer.lambda$submit$0, captured with an
/// identity PoseStack and a VertexConsumer recording big-endian xyz floats.
#[test]
fn geometry_matches_pinned_vanilla_vertex_digest() {
use sha2::{Digest, Sha256};
let mut digest = Sha256::new();
for seed in seeds() {
for vertex in geometry(seed, [0.0; 2]) {
for value in vertex.pos {
digest.update(value.to_be_bytes());
}
}
}
assert_eq!(
format!("{:x}", digest.finalize()),
"a9ed25caa50b9aa340faa4bb417b3d533b061f0dce66514e4bb212931444dee6"
);
}
#[test]
fn retained_geometry_matches_original_generator() {
let uv = [0.8125, 0.03125];
for seed in seeds() {
let local = geometry(seed, uv);
assert_eq!(local.len(), QUADS as usize * 4);
for (at, camera) in [
([0.0; 3], DVec3::ZERO),
([12.5, 64.0, -12.5], DVec3::new(-4.25, 71.125, 32.5)),
(
[29_999_999.5, -64.0, -29_999_999.5],
DVec3::new(29_999_987.125, 67.75, -29_999_983.875),
),
] {
let offset = offset(&Bolt { seed, at }, camera);
let translated: Vec<_> = local
.iter()
.map(|v| Vertex {
pos: (glam::Vec3::from_array(offset) + glam::Vec3::from_array(v.pos))
.to_array(),
..*v
})
.collect();
let expected = reference(seed, at, camera, uv);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&translated),
bytemuck::cast_slice::<_, u8>(&expected),
"seed {seed}"
);
}
}
}
#[test]
fn cache_tracks_seed_lifecycle_movement_and_atlas_reload() {
let mut cache = Cache::new();
let builds = Cell::new(0);
let build = |seed, uv| {
builds.set(builds.get() + 1);
geometry(seed, uv)
};
let mut bolts = [
Bolt {
seed: 123,
at: [0.0; 3],
},
Bolt {
seed: 456,
at: [1.0; 3],
},
];
fn input(bolts: &[Bolt]) -> Input<'_> {
Input {
bolts,
uv: [0.25, 0.5],
}
}
cache.prepare(&input(&bolts), build);
assert_eq!(builds.get(), 2);
assert_eq!(cache.meshes.len(), 2);
// Any number of rendered frames or multiplayer position updates reuse meshes.
for i in 0..100 {
bolts[0].at = [i as f64; 3];
cache.prepare(&input(&bolts), build);
}
assert_eq!(builds.get(), 2);
// A flash changes the seed; retire its previous mesh immediately.
bolts[0].seed = 789;
cache.prepare(&input(&bolts), build);
assert_eq!(builds.get(), 3);
assert!(!cache.meshes.contains_key(&123));
// Removal retains other bolts, and repeated seeds still share geometry.
bolts[0].seed = 456;
cache.prepare(&input(&bolts), build);
assert_eq!(builds.get(), 3);
assert_eq!(cache.meshes.len(), 1);
// Atlas replacement must update white texel UVs without changing the seed.
cache.prepare(
&Input {
bolts: &bolts,
uv: [0.75, 0.25],
},
build,
);
assert_eq!(builds.get(), 4);
assert_eq!(cache.meshes[&456].mesh[0].uv, [0.75, 0.25]);
// Disconnect/dimension switch/expiry drops every retained resource.
cache.prepare(&Input::default(), build);
assert!(cache.meshes.is_empty());
assert_eq!(cache.meshes.capacity(), 0);
cache.prepare(&input(&bolts), build);
assert_eq!(builds.get(), 5);
}
#[test]
fn long_flash_sequence_keeps_only_active_seeds() {
let mut cache = Cache::new();
for seed in 0..10_000 {
cache.prepare(
&Input {
bolts: &[Bolt { seed, at: [0.0; 3] }],
uv: [0.0; 2],
},
|seed, _| seed,
);
assert_eq!(cache.meshes.len(), 1);
assert_eq!(cache.meshes[&seed].mesh, seed);
assert!(cache.meshes.capacity() < 16);
}
}
/// Exercise the actual entity shader and retained draw path offscreen. Run
/// explicitly, separately from other headless device tests (some GPU drivers
/// fail during concurrent device teardown). Machines without an adapter skip it.
#[test]
#[ignore = "requires GPU; run separately with --ignored --exact"]
fn retained_gpu_draw_matches_transient_additive_draw() {
use bytemuck::Zeroable;
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
eprintln!("no GPU adapter: skipped");
return;
};
eprintln!("lightning differential GPU: {}", adapter.get_info().name);
let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).unwrap();
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Lightning differential shader"),
source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()),
});
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4];
let offsets = wgpu::vertex_attr_array![6=>Float32x3];
let vertices = [Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})];
let retained_vertices = [
vertices[0].clone(),
Some(wgpu::VertexBufferLayout {
array_stride: 12,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &offsets,
}),
];
let pipelines: Vec<_> = [false, true]
.into_iter()
.map(|retained| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Lightning differential pipeline"),
layout: None,
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(if retained {
"vs_lightning"
} else {
"vs_entity"
}),
compilation_options: Default::default(),
buffers: if retained {
&retained_vertices
} else {
&vertices
},
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(false),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_celestial"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba8Unorm,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
})
.collect();
let globals = crate::gfx::Globals {
view_proj: (glam::Mat4::orthographic_rh(-100.0, 100.0, -10.0, 150.0, 0.1, 400.0)
* glam::Mat4::look_at_rh(
glam::Vec3::new(80.0, 30.0, 160.0),
glam::Vec3::new(0.0, 60.0, 0.0),
glam::Vec3::Y,
))
.to_cols_array_2d(),
..crate::gfx::Globals::zeroed()
};
let globals = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::bytes_of(&globals),
usage: wgpu::BufferUsages::UNIFORM,
});
let size = wgpu::Extent3d {
width: 256,
height: 256,
depth_or_array_layers: 1,
};
let texture = |format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: None,
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
let white = device
.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&[255; 4],
)
.create_view(&Default::default());
let sampler = device.create_sampler(&Default::default());
let groups: Vec<_> = pipelines
.iter()
.map(|pipeline| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&white),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&white),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
})
})
.collect();
let mut renderer = Renderer::new();
let mut uploads = Uploads::new(&device);
let mut bolts = [Bolt {
seed: 123,
at: [29_999_999.5, 64.0, -29_999_999.5],
}; 3];
bolts[1].seed = -456;
bolts[1].at[0] -= 32.0;
bolts[2].at[2] += 20.0;
let indices = crate::gfx::Renderer::quad_indices(&device, QUADS * 3);
for frame in 0..4 {
let camera = DVec3::new(29_999_997.125 + frame as f64, 62.75, -29_999_998.875);
if frame == 2 {
bolts[0].seed = 789;
}
let input = Input {
bolts: &bolts[..if frame == 3 { 1 } else { 3 }],
uv: if frame == 3 { [0.75; 2] } else { [0.5; 2] },
};
let expected: Vec<_> = input
.bolts
.iter()
.flat_map(|bolt| reference(bolt.seed, bolt.at, camera, input.uv))
.collect();
let transient = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&expected),
usage: wgpu::BufferUsages::VERTEX,
});
let mut encoder = device.create_command_encoder(&Default::default());
renderer.prepare(&device, &mut uploads, &mut encoder, &input, camera);
let mut readbacks = Vec::new();
for mode in 0..2 {
let color = texture(
wgpu::TextureFormat::Rgba8Unorm,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
);
let view = color.create_view(&Default::default());
let depth = texture(
wgpu::TextureFormat::Depth32Float,
wgpu::TextureUsages::RENDER_ATTACHMENT,
)
.create_view(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Discard,
}),
stencil_ops: None,
}),
..Default::default()
});
pass.set_pipeline(&pipelines[mode]);
pass.set_bind_group(0, &groups[mode], &[]);
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
if mode == 0 {
pass.set_vertex_buffer(0, transient.slice(..));
pass.draw_indexed(0..expected.len() as u32 / 4 * 6, 0, 0..1);
} else {
renderer.draw(&mut pass, &input);
}
}
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 256 * 256 * 4,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
color.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &read,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(1024),
rows_per_image: None,
},
},
size,
);
readbacks.push(read);
}
uploads.finish(&encoder);
queue.submit([encoder.finish()]);
for read in &readbacks {
read.slice(..)
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
}
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let pixels: Vec<Vec<u8>> = readbacks
.iter()
.map(|read| read.slice(..).get_mapped_range().unwrap().to_vec())
.collect();
assert!(pixels[0].iter().any(|&b| b != 0), "empty reference frame");
assert_eq!(pixels[0], pixels[1], "frame {frame}: GPU output differs");
}
}
+330
View File
@@ -0,0 +1,330 @@
//! Weather's unsplit quads, using the entity atlas/lightmap resources.
use crate::weather::{Time, Vertex};
pub(super) struct Weather {
pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
vertices: wgpu::Buffer,
capacity: usize,
count: u32,
}
impl Weather {
pub fn new(
device: &wgpu::Device,
format: wgpu::TextureFormat,
entities: &wgpu::BindGroupLayout,
shader: &wgpu::ShaderModule,
) -> Self {
let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Weather time"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Weather layout"),
bind_group_layouts: &[Some(entities), Some(&bindings)],
..Default::default()
});
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Float32x4,
3=>Float32x4,4=>Uint32x4,5=>Unorm8x4,6=>Uint8x4,7=>Uint32];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Weather"),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: shader,
entry_point: Some("vs_weather"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: shader,
entry_point: Some("fs_weather"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Weather time"),
size: 16,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Weather time"),
layout: &bindings,
entries: &[wgpu::BindGroupEntry {
binding: 1,
resource: uniform.as_entire_binding(),
}],
});
Self {
pipeline,
group,
uniform,
vertices: Self::buffer(device, 4),
capacity: 4,
count: 0,
}
}
fn buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Weather vertices"),
size: (capacity * std::mem::size_of::<Vertex>()) as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}
pub fn prepare(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
uploads: &mut super::upload::Uploads,
vertices: &[Vertex],
time: Time,
) {
self.count = vertices.len() as u32;
if vertices.is_empty() {
return;
}
if vertices.len() > self.capacity {
self.capacity = vertices.len().next_power_of_two();
self.vertices = Self::buffer(device, self.capacity);
}
uploads.buffer(encoder, &self.vertices, 0, bytemuck::cast_slice(vertices));
uploads.buffer(encoder, &self.uniform, 0, bytemuck::bytes_of(&time));
}
pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>, entities: &wgpu::BindGroup) {
if self.count == 0 {
return;
}
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, entities, &[]);
pass.set_bind_group(1, &self.group, &[]);
pass.set_vertex_buffer(0, self.vertices.slice(..));
// The renderer binds the shared triangle-list quad indices.
pass.draw_indexed(0..self.count / 4 * 6, 0, 0..1);
}
}
#[cfg(test)]
mod tests {
use crate::weather::{Parameters, Time};
use wgpu::util::DeviceExt;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Case {
animation: [f32; 4],
bases: [u32; 4],
time: [f32; 4],
uv: [f32; 2],
snow: u32,
_pad: u32,
}
/// Execute the production WGSL math, rather than a Rust translation of it.
/// Requires a GPU; run explicitly on renderer changes, not on headless CI.
#[test]
#[ignore = "requires a Vulkan/Metal/DX12 adapter"]
fn weather_shader_uvs_match_legacy_bits() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
.unwrap();
eprintln!("weather parity adapter: {:?}", adapter.get_info());
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap();
let mut cases = Vec::new();
let mut expected = Vec::new();
for i in 0..4096i32 {
let x = i.wrapping_mul(45_238_971);
let z = i.wrapping_mul(-418_711).wrapping_add(i32::MIN);
let p = Parameters::new(x, z);
let bases = p.snow_base.map(f64::to_bits);
for ticks in [-1, 0, 511, 512, 131_071, 131_072, i64::MAX] {
let partial = [0.0, 0.5, 0.999, f32::from_bits(0x3f7fffff)][i as usize % 4];
for snow in [false, true] {
let column = p.column(snow, ticks, x, -64, 320, z, 0, partial);
let uv = [1.0, if i & 1 == 0 { -16.0 } else { 80.0 }];
cases.push(Case {
animation: [
p.rain_speed,
p.rain_tick_offset,
p.snow_drift[0],
p.snow_drift[1],
],
bases: [
bases[0] as u32,
(bases[0] >> 32) as u32,
bases[1] as u32,
(bases[1] >> 32) as u32,
],
time: Time::new(ticks, partial).values,
uv,
snow: u32::from(snow),
_pad: 0,
});
expected.push([
(uv[0] + column.u_offset).to_bits(),
(uv[1] + column.v_offset).to_bits(),
]);
}
}
}
// Force halfway rounding, cancellation, zero, tiny bases and either
// sign of drift. Gaussian seeds alone rarely land on exact midpoints.
for base in [
0.0,
2.0f64.powi(-53),
0.5,
0.5 + 2.0f64.powi(-25),
0.5 + 2.0f64.powi(-25) + 2.0f64.powi(-53),
0.5 + 2.0f64.powi(-14) + 2.0f64.powi(-53),
1.0 - 2.0f64.powi(-53),
] {
for delta in [0.0f32, -0.0, -0.5, 0.5, 1024.0, -1024.0, 2.0f32.powi(-40)] {
// time=100, u scale=.01 -> delta exactly, v is unused.
let bits = base.to_bits();
cases.push(Case {
animation: [3.0, 0.0, delta, 0.0],
bases: [bits as u32, (bits >> 32) as u32, 0, 0],
time: [100.0, 0.0, 0.0, 0.0],
uv: [0.0, 0.0],
snow: 1,
_pad: 0,
});
expected.push([((base + f64::from(delta)) as f32).to_bits(), 0]);
}
}
let expected: Vec<[u32; 4]> = expected
.into_iter()
.map(|bits| {
let uv = bits.map(f32::from_bits);
let texel = [
256 + ((uv[0] - uv[0].floor()) * 16.0).floor() as u32,
512 + ((uv[1] - uv[1].floor()) * 32.0).floor() as u32,
];
[bits[0], bits[1], texel[0], texel[1]]
})
.collect();
let math = include_str!("../entity.wgsl")
.split("// WEATHER_MATH_BEGIN")
.nth(1)
.unwrap()
.split("// WEATHER_MATH_END")
.next()
.unwrap();
let source = format!(
"{math}\n{}",
r#"
struct Case { animation: vec4<f32>, bases: vec4<u32>, time: vec4<f32>, uv: vec2<f32>, snow: u32, pad: u32 }
@group(0) @binding(0) var<storage, read> cases: array<Case>;
@group(0) @binding(1) var<storage, read_write> results: array<vec4<u32>>;
@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if id.x >= arrayLength(&cases) { return; }
let c = cases[id.x];
let uv = c.uv + weather_phase(c.animation, c.bases, c.snow, c.time);
let texel = weather_texel(uv, vec4(0.25, 0.5, 0.015625, 0.03125), vec2(1024u));
results[id.x] = vec4(bitcast<vec2<u32>>(uv), vec2<u32>(texel));
}"#
);
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Weather parity"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Weather parity"),
layout: None,
module: &shader,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&cases),
usage: wgpu::BufferUsages::STORAGE,
});
let size = (expected.len() * 16) as u64;
let output = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: input.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: output.as_entire_binding(),
},
],
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &group, &[]);
pass.dispatch_workgroups((cases.len() as u32).div_ceil(64), 1, 1);
}
encoder.copy_buffer_to_buffer(&output, 0, &readback, 0, size);
queue.submit([encoder.finish()]);
let (tx, rx) = std::sync::mpsc::channel();
readback.map_async(wgpu::MapMode::Read, .., move |r| tx.send(r).unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
rx.recv().unwrap().unwrap();
let mapped = readback.get_mapped_range(..).unwrap();
let actual: &[[u32; 4]] = bytemuck::cast_slice(&mapped);
for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
assert_eq!(
actual, expected,
"case {i}, snow={}, time={:?}, animation={:?}",
cases[i].snow, cases[i].time, cases[i].animation
);
}
eprintln!("{} GPU weather UV cases matched bit for bit", cases.len());
}
}
+60 -2
View File
@@ -365,6 +365,8 @@ pub struct HudBatch {
pub patches: Vec<crate::font::Patch>,
/// Vertex ranges with another blend or depth/scissor state, in order.
pub blends: Vec<(std::ops::Range<u32>, Blend)>,
/// Screen's first vertex: the preceding HUD is part of its blurred background.
pub blur_at: u32,
}
/// How a run of HUD vertices blends and tests depth.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -400,6 +402,7 @@ impl HudBatch {
height: (window[1] as f32 / scale as f32).ceil(),
patches: Vec::new(),
blends: Vec::new(),
blur_at: 0,
}
}
/// Draw the vertices added since `start` with the inverting blend.
@@ -452,6 +455,14 @@ impl HudBatch {
}
out
}
fn runs_in(&self, vertices: std::ops::Range<u32>) -> Vec<(std::ops::Range<u32>, Blend)> {
let mut runs = self.runs();
for (range, _) in &mut runs {
*range = range.start.max(vertices.start)..range.end.min(vertices.end);
}
runs.retain(|(range, _)| !range.is_empty());
runs
}
/// `AbstractContainerScreen.init`: center in integer GUI coordinates.
pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) {
(
@@ -1080,7 +1091,26 @@ impl HudRenderer {
batch: &HudBatch,
size: [u32; 2],
) {
if batch.vertices.is_empty() || size.contains(&0) {
self.draw_range(
encoder,
target,
depth,
batch,
size,
0..batch.vertices.len() as u32,
);
}
/// Draw part of the prepared batch, preserving its blend/depth runs.
pub fn draw_range(
&self,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
depth: &wgpu::TextureView,
batch: &HudBatch,
size: [u32; 2],
vertices: std::ops::Range<u32>,
) {
if vertices.is_empty() || size.contains(&0) {
return;
}
let attachments = [Some(wgpu::RenderPassColorAttachment {
@@ -1092,7 +1122,7 @@ impl HudRenderer {
store: wgpu::StoreOp::Store,
},
})];
let runs = batch.runs();
let runs = batch.runs_in(vertices);
let mut at = 0;
while at < runs.len() {
let clip = match runs[at].1 {
@@ -1331,6 +1361,33 @@ mod tests {
]
);
}
#[test]
fn blur_boundary_splits_blend_runs_without_losing_or_repeating_vertices() {
let mut batch = HudBatch::new([854, 480]);
for _ in 0..5 {
batch.quad([[0.0; 2]; 4], [[0.0; 2]; 4], 0);
}
batch.blends = vec![
(6..18, Blend::Invert),
(18..24, Blend::Depth([0, 0, 10, 10])),
];
for split in [0, 6, 12, 18, 24, 30] {
let before = batch.runs_in(0..split);
let after = batch.runs_in(split..30);
let actual: Vec<_> = before
.into_iter()
.chain(after)
.flat_map(|(range, blend)| range.map(move |v| (v, blend)))
.collect();
let expected: Vec<_> = batch
.runs()
.into_iter()
.flat_map(|(range, blend)| range.map(move |v| (v, blend)))
.collect();
assert_eq!(actual, expected, "blur at {split}");
}
}
#[test]
fn container_origins_use_java_integer_division() {
// Odd scaled dimensions, odd image sizes and an oversized panel.
@@ -1342,6 +1399,7 @@ mod tests {
height: height as f32,
patches: Vec::new(),
blends: Vec::new(),
blur_at: 0,
};
for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] {
assert_eq!(
+59
View File
@@ -609,6 +609,65 @@ mod tests {
assert!(container_lines(&ItemStack::new("minecraft:chest", 1), &name, &lang).is_empty());
}
#[test]
fn fireworks_use_loaded_tooltip_translations() {
let root = std::env::temp_dir().join(format!(
"horizon-firework-tooltip-language-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos(),
));
let dir = root.join("assets/minecraft/lang");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("en_us.json"),
serde_json::to_vec(&serde_json::json!({
"item.minecraft.firework_rocket.flight_duration": "Flight Duration: %s",
"item.minecraft.firework_rocket.multiple_stars": "%s x %s",
"item.minecraft.firework_star.shape.small_ball": "Small Ball",
"item.minecraft.firework_star.red": "Red",
"item.minecraft.firework_star.custom_color": "Custom",
"item.minecraft.firework_star.fade_to": "Fade to",
"item.minecraft.firework_star.trail": "Trail",
"item.minecraft.firework_star.flicker": "Twinkle",
}))
.unwrap(),
)
.unwrap();
let enchantments = crate::enchant::Enchantments::load(&root);
std::fs::remove_dir_all(&root).unwrap();
let translate = |key: &str| enchantments.translate(key).map(str::to_owned);
let mut rocket = ItemStack::new("minecraft:firework_rocket", 1);
assert_eq!(firework_lines(&rocket, &translate), ["Flight Duration: 1"]);
let explosion = crate::particles::FireworkExplosion {
colors: vec![0xB3312C],
fade: vec![0x123456],
trail: true,
twinkle: true,
..Default::default()
};
rocket.data_mut().fireworks = Some((3, vec![explosion.clone(), explosion.clone()]));
assert_eq!(
firework_lines(&rocket, &translate),
[
"Flight Duration: 3",
"2 x Small Ball",
" Red",
" Fade to Custom",
" Trail",
" Twinkle",
]
);
let mut star = ItemStack::new("minecraft:firework_star", 1);
star.data_mut().firework_explosion = Some(explosion);
assert_eq!(
firework_lines(&star, &translate),
["Small Ball", "Red", "Fade to Custom", "Trail", "Twinkle"]
);
}
#[test]
fn amounts_use_two_decimals_at_most() {
assert_eq!(format_amount(8.0), "8");
+10
View File
@@ -71,6 +71,13 @@ pub struct Guest {
/// The permission level (0 none, 2 game masters, 4 owners).
pub permission: u8,
pub sneaking: bool,
/// The last `ServerboundPlayerInputPacket` flags (forward 1, backward 2,
/// left 4, right 8, jump 16, shift 32, sprint 64).
pub input: u8,
/// The boat or minecart the player rides (`Entity.getVehicle`).
pub vehicle: Option<u32>,
/// `ServerGamePacketListenerImpl.lastGoodX/Y/Z` of the vehicle it controls.
pub vehicle_good: Option<[f64; 3]>,
pub sprinting: bool,
pub fall_flying: bool,
pub flying: bool,
@@ -233,6 +240,9 @@ impl Guest {
game_mode: SURVIVAL,
permission: 0,
sneaking: false,
input: 0,
vehicle: None,
vehicle_good: None,
sprinting: false,
fall_flying: false,
flying: false,
+6
View File
@@ -1968,6 +1968,7 @@ impl Hub {
g.center = None;
}
S::PlayerInput(p) => {
self.guests[i].input = p.flags;
self.guests[i].sneaking = p.flags & 32 != 0;
self.guests[i].sprinting = p.flags & 64 != 0 && p.flags & 1 != 0;
}
@@ -2050,6 +2051,11 @@ impl Hub {
to[2].clamp(-3.0E7, 3.0E7),
];
let (yaw, pitch) = (wrap_degrees(yaw), wrap_degrees(pitch));
// A passenger only turns: its vehicle carries it (absSnapTo where it is).
if g.vehicle.is_some() {
(g.yaw, g.pitch) = (yaw, pitch);
return;
}
let d = [0, 1, 2].map(|k| to[k] - g.first_good[k]);
let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if g.sleeping {
+212 -2
View File
@@ -1305,8 +1305,73 @@ pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) {
};
layers[si as usize] = (layer("SkyLight"), layer("BlockLight"));
}
let above = [if sky_light { 15 } else { 0 }; 256];
crate::light::light_from_layers(chunk, &layers, above, sky_light);
// Uniform saved layers need no expanded allocation. Both nibbles of
// each byte must match, not merely the bytes across the layer.
let uniform_layer = |layer: &[u8]| {
let first = layer[0];
(first & 15 == first >> 4 && layer.iter().all(|&v| v == first)).then_some(first & 15)
};
let mut above = [if sky_light { 15 } else { 0 }; 256];
for (si, (sky, block)) in layers.into_iter().enumerate().rev() {
let sky = sky.filter(|_| sky_light);
let sky_uniform = sky.map_or_else(
|| above.iter().all(|&v| v == above[0]).then_some(above[0]),
uniform_layer,
);
let block_uniform = block.map_or(Some(0), uniform_layer);
let section = Arc::make_mut(&mut chunk.sections[si]);
if let (Some(s), Some(b)) = (sky_uniform, block_uniform) {
section.light = Light::Uniform(s << 4 | b);
above.fill(s);
} else {
let mut data = Box::new([0u8; 4096]);
match (sky, block) {
(Some(sky), Some(block)) => {
for ((pair, &s), &b) in
data.as_chunks_mut::<2>().0.iter_mut().zip(sky).zip(block)
{
pair[0] = s << 4 | (b & 15);
pair[1] = (s & 0xf0) | (b >> 4);
}
}
(Some(sky), None) => {
for (pair, &s) in data.as_chunks_mut::<2>().0.iter_mut().zip(sky) {
pair[0] = s << 4;
pair[1] = s & 0xf0;
}
}
(None, Some(block)) => {
for (i, (pair, &b)) in data
.as_chunks_mut::<2>()
.0
.iter_mut()
.zip(block)
.enumerate()
{
pair[0] = above[(i * 2) & 255] << 4 | (b & 15);
pair[1] = above[(i * 2 + 1) & 255] << 4 | (b >> 4);
}
}
(None, None) => {
for layer in data.as_chunks_mut::<256>().0 {
for (v, &s) in layer.iter_mut().zip(&above) {
*v = s << 4;
}
}
}
}
if let Some(sky) = sky {
for (pair, &s) in above.as_chunks_mut::<2>().0.iter_mut().zip(sky) {
pair[0] = s & 15;
pair[1] = s >> 4;
}
}
section.light = Light::Full(data);
}
section.compact();
}
chunk.lit = true;
chunk.light_loaded = true;
}
type RegionCache = Mutex<HashMap<(i32, i32), Option<Arc<Mutex<RegionFile>>>>>;
@@ -3892,6 +3957,151 @@ mod tests {
assert!(!unlit.lit && !unlit.light_loaded);
}
#[test]
fn saved_light_matches_reference_for_layers_and_metadata() {
fn reference(tag: &Tag, chunk: &mut Chunk, sky_light: bool) {
if tag.get("isLightOn") != Some(&Tag::Byte(1)) {
return;
}
let Some(Tag::List(sections)) = tag.get("sections") else {
return;
};
let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS];
for section in sections {
let Some(y) = number(section.get("Y")) else {
continue;
};
let si = y as i32 - (MIN_Y >> 4);
if !(0..SECTIONS as i32).contains(&si) {
continue;
}
let layer = |name: &str| match section.get(name) {
Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]),
_ => None,
};
layers[si as usize] = (layer("SkyLight"), layer("BlockLight"));
}
let above = [if sky_light { 15 } else { 0 }; 256];
crate::light::light_from_layers(chunk, &layers, above, sky_light);
}
let section = |y: Tag, sky: Option<Tag>, block: Option<Tag>| {
let mut entries = vec![("Y", y)];
if let Some(v) = sky {
entries.push(("SkyLight", v));
}
if let Some(v) = block {
entries.push(("BlockLight", v));
}
Tag::compound(entries)
};
let root = |sections| {
Tag::compound([
("isLightOn", Tag::Byte(1)),
("sections", Tag::List(sections)),
])
};
let check = |tag: &Tag| {
for sky_light in [false, true] {
let mut expected = Chunk::empty(-3, 5);
let s = Arc::make_mut(&mut expected.sections[0]);
s.light = Light::Full(Box::new([0xab; 4096]));
s.blocks.set(0, 1);
s.blocks.set(0, 0);
s.biomes.set(0, 1);
s.biomes.set(0, 0);
let mut actual = expected.clone();
reference(tag, &mut expected, sky_light);
load_light(tag, &mut actual, sky_light);
assert_eq!(
(actual.lit, actual.light_loaded),
(expected.lit, expected.light_loaded)
);
for (a, b) in actual.sections.iter().zip(&expected.sections) {
assert_eq!(
std::mem::discriminant(&a.light),
std::mem::discriminant(&b.light)
);
assert_eq!(
format!("{:?}", a.blocks.to_wire()),
format!("{:?}", b.blocks.to_wire())
);
assert_eq!(
format!("{:?}", a.biomes.to_wire()),
format!("{:?}", b.biomes.to_wire())
);
for i in 0..4096 {
assert_eq!(a.light(i), b.light(i), "index {i}, sky {sky_light}");
}
}
}
};
for tag in [
Tag::compound(Vec::<(&str, Tag)>::new()),
Tag::compound([("isLightOn", Tag::Byte(0))]),
Tag::compound([("isLightOn", Tag::Byte(2))]),
Tag::compound([("isLightOn", Tag::Int(1)), ("sections", Tag::List(vec![]))]),
Tag::compound([("isLightOn", Tag::Byte(1)), ("sections", Tag::Int(0))]),
root(vec![]),
] {
check(&tag);
}
// Cover every repeated byte, including 0xF0/0x0F: a uniform byte
// array need not hold uniform nibbles.
for byte in 0..=255u8 {
check(&root(vec![section(
Tag::Byte(19),
Some(Tag::ByteArray(vec![byte; 2048])),
Some(Tag::ByteArray(vec![255 - byte; 2048])),
)]));
}
// Every pair of uniform sky/block nibble values, with missing
// sections below inheriting the stored bottom row.
for sky in 0..16u8 {
for block in 0..16u8 {
check(&root(vec![section(
Tag::Byte(1),
Some(Tag::ByteArray(vec![sky * 17; 2048])),
Some(Tag::ByteArray(vec![block * 17; 2048])),
)]));
}
}
for length in [0, 1, 2047, 2048, 2049] {
for invalid in [
Tag::Int(1),
Tag::List(vec![]),
Tag::ByteArray(vec![0xf0; length]),
] {
check(&root(vec![section(
Tag::Byte(-4),
Some(invalid.clone()),
Some(invalid),
)]));
}
}
let varied: Vec<u8> = (0..2048)
.map(|i| (i as u8).wrapping_mul(73).wrapping_add(31))
.collect();
check(&root(vec![
section(Tag::Byte(-5), Some(Tag::ByteArray(varied.clone())), None),
section(Tag::Byte(20), Some(Tag::ByteArray(varied.clone())), None),
section(
Tag::String("19".into()),
Some(Tag::ByteArray(varied.clone())),
None,
),
section(Tag::Byte(19), Some(Tag::ByteArray(varied.clone())), None),
section(Tag::Byte(17), None, Some(Tag::ByteArray(varied.clone()))),
section(Tag::Byte(-4), Some(Tag::ByteArray(varied.clone())), None),
// Last duplicate wins, even when its arrays have wrong types.
section(
Tag::Byte(-4),
Some(Tag::Int(15)),
Some(Tag::ByteArray(vec![7; 2047])),
),
section(Tag::Byte(0), None, Some(Tag::ByteArray(varied))),
]));
}
#[test]
fn level_round_trips_through_the_vanilla_files() {
let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
+286 -9
View File
@@ -3,8 +3,9 @@
//! Vanilla draws each column as one camera-facing quad whose texture
//! coordinates run past 0..1 (`v` advances a quarter of the texture per block,
//! so `rain.png` repeats every 4 blocks) and relies on a repeating sampler.
//! Horizon samples the sprite from its atlas, so [`tile`] splits a quad at
//! every whole texture repeat into pieces that stay inside the sprite.
//! The live renderer repeats UVs inside the atlas sprite in its shader, using
//! cached coordinate-only [`Parameters`]. The reference [`tile`] path splits
//! at whole repeats and remains available for CPU callers and parity probes.
use horizon_core::random::{LegacyRandom, RandomSource};
/// `WeatherEffectRenderer.ColumnInstance`.
@@ -47,6 +48,176 @@ pub fn column_random(x: i32, z: i32) -> LegacyRandom {
LegacyRandom::new(i64::from(column_seed(x, z)))
}
/// Coordinate-only random values. Keep the snow bases as doubles: rounding them
/// before adding the float drift changes vanilla's UVs at rounding boundaries.
#[derive(Clone, Copy, Debug)]
pub struct Parameters {
pub rain_speed: f32,
pub rain_tick_offset: f32,
pub snow_base: [f64; 2],
pub snow_drift: [f32; 2],
}
impl Parameters {
pub fn new(x: i32, z: i32) -> Self {
let rain_speed = 3.0 + column_random(x, z).next_float();
let mut random = column_random(x, z);
let u = random.next_double();
let du = random.next_gaussian() as f32;
let v = random.next_double();
let dv = random.next_gaussian() as f32;
Self {
rain_speed,
rain_tick_offset: (x
.wrapping_mul(x)
.wrapping_mul(3121)
.wrapping_add(x.wrapping_mul(45_238_971))
.wrapping_add(z.wrapping_mul(z).wrapping_mul(418_711))
.wrapping_add(z.wrapping_mul(13761))
& 255) as f32,
snow_base: [u, v],
snow_drift: [du, dv],
}
}
/// CPU reference for fixtures and GPU differential tests. The public random
/// source helpers below retain their original draw/advancement semantics.
#[allow(clippy::too_many_arguments)]
pub fn column(
self,
snow: bool,
ticks: i64,
x: i32,
bottom_y: i32,
top_y: i32,
z: i32,
light_coords: i32,
partial: f32,
) -> Column {
let time = (ticks & 131_071) as f32 + partial;
let (u_offset, v_offset, light_coords) = if snow {
let u = (self.snow_base[0] + f64::from(time * 0.01 * self.snow_drift[0])) as f32;
let v = (self.snow_base[1] + f64::from(time * self.snow_drift[1] * 0.001)) as f32;
let fall = -((ticks & 511) as f32 + partial) / 512.0;
let (block, sky) = (light_coords >> 4 & 15, light_coords >> 20 & 15);
(
u,
fall + v,
((block * 3 + 15) / 4) << 4 | ((sky * 3 + 15) / 4) << 20,
)
} else {
let offset = -(((ticks & 131_071) as f32 + self.rain_tick_offset) + partial) / 32.0
* self.rain_speed;
(0.0, offset % 32.0, light_coords)
};
Column {
x,
z,
bottom_y,
top_y,
u_offset,
v_offset,
light_coords,
}
}
}
/// Direct-mapped 32x32 cache: at most 1024 coordinate keys, including after
/// teleports or radius changes. Full keys disambiguate collisions and wrapping.
/// Nothing world-dependent is cached, so dimension/biome/pack changes need no
/// invalidation; the caller still samples heights, precipitation and light.
pub struct ParameterCache {
entries: Box<[Option<((i32, i32), Parameters)>]>,
}
impl Default for ParameterCache {
fn default() -> Self {
Self {
entries: vec![None; 32 * 32].into_boxed_slice(),
}
}
}
impl ParameterCache {
pub fn get(&mut self, x: i32, z: i32) -> Parameters {
let index = ((z as u32 & 31) * 32 + (x as u32 & 31)) as usize;
let entry = &mut self.entries[index];
if let Some((key, parameters)) = entry
&& *key == (x, z)
{
return *parameters;
}
let parameters = Parameters::new(x, z);
*entry = Some(((x, z), parameters));
parameters
}
}
/// One unsplit camera-relative weather vertex. UV animation and atlas-local
/// repetition happen in the weather shader, rather than rebuilding tiled quads.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Vertex {
pub pos: [f32; 3],
pub uv: [f32; 2],
pub rect: [f32; 4],
pub animation: [f32; 4],
pub bases: [u32; 4],
pub color: u32,
pub light: u32,
pub snow: u32,
}
/// Current ticks are masked on the CPU before conversion to float, including
/// negative/large tick values. Do not use the renderer's unbounded game_time.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Time {
pub values: [f32; 4],
}
impl Time {
pub fn new(ticks: i64, partial: f32) -> Self {
Self {
values: [(ticks & 131_071) as f32, (ticks & 511) as f32, partial, 0.0],
}
}
}
/// Emit a single quad, retaining column_quad's position, fade, UV rounding and
/// light semantics. The zero phase leaves the shader to animate both UV axes.
pub fn vertices(
column: &Column,
parameters: Parameters,
snow: bool,
camera: [f64; 3],
radius: i32,
intensity: f32,
rect: [f32; 4],
) -> [Vertex; 4] {
let quad = column_quad(
column,
camera,
if snow { 0.8 } else { 1.0 },
radius,
intensity,
);
let lc = column.light_coords;
let light = ((lc >> 20 & 15) * 16) as u32 | (((lc >> 4 & 15) * 16) as u32) << 8;
let [u, v] = parameters.snow_base.map(f64::to_bits);
quad.map(|q| Vertex {
pos: q.pos,
uv: q.uv,
rect,
animation: [
parameters.rain_speed,
parameters.rain_tick_offset,
parameters.snow_drift[0],
parameters.snow_drift[1],
],
bases: [u as u32, (u >> 32) as u32, v as u32, (v >> 32) as u32],
color: q.color,
light,
snow: u32::from(snow),
})
}
/// `createRainColumnInstance`.
#[allow(clippy::too_many_arguments)]
pub fn rain_column(
@@ -114,10 +285,15 @@ pub fn snow_column(
/// The constructor's 32x32 table of horizontal column half-widths, indexed
/// relative to the camera block. The camera's own column divides 0 by 0.
fn column_size(index: usize) -> (f32, f32) {
let delta_x = (index % 32) as f32 - 16.0;
let delta_z = (index / 32) as f32 - 16.0;
let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32;
(-delta_z / distance, delta_x / distance)
static SIZES: std::sync::LazyLock<[(f32, f32); 32 * 32]> = std::sync::LazyLock::new(|| {
std::array::from_fn(|index| {
let delta_x = (index % 32) as f32 - 16.0;
let delta_z = (index / 32) as f32 - 16.0;
let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32;
(-delta_z / distance, delta_x / distance)
})
});
SIZES[index]
}
/// `prepareInstances` for one column: rain uses `max_alpha` 1, snow 0.8.
@@ -135,8 +311,8 @@ pub fn column_quad(
let t = (distance_sq / radius_sq).min(1.0);
let alpha = (max_alpha + t * (0.5 - max_alpha)) * intensity;
let color = ((alpha * 255.0).floor() as i32 as u32) << 24 | 0xFF_FFFF;
let index =
(column.z - camera[2].floor() as i32 + 16) * 32 + column.x - camera[0].floor() as i32 + 16;
let index = (column.z - camera[2].floor() as i32 + 16) * 32
+ (column.x - camera[0].floor() as i32 + 16);
let (size_x, size_z) = column_size(index as usize);
let (half_x, half_z) = (size_x / 2.0, size_z / 2.0);
let (x0, x1) = (relative_x - half_x, relative_x + half_x);
@@ -219,6 +395,103 @@ fn pieces(a: f32, b: f32) -> impl Iterator<Item = (f32, f32)> {
mod tests {
use super::*;
#[test]
fn column_size_table_matches_original_arithmetic() {
for z in 0..32 {
for x in 0..32 {
let delta_x = x as f32 - 16.0;
let delta_z = z as f32 - 16.0;
let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32;
let expected = [-delta_z / distance, delta_x / distance];
let actual = column_size(z * 32 + x);
for (actual, expected) in [actual.0, actual.1].into_iter().zip(expected) {
if x == 16 && z == 16 {
assert!(expected.is_nan());
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), expected.to_bits(), "column ({x}, {z})");
}
}
}
}
}
#[test]
fn cached_parameters_match_original_random_draws() {
let mut cache = ParameterCache::default();
for i in 0..2048i32 {
let x = i.wrapping_mul(45_238_971);
let z = i.wrapping_mul(-418_711).wrapping_add(i32::MIN);
for ticks in [i64::MIN, -1, 0, 511, 512, 131_071, 131_072, i64::MAX] {
for partial in [0.0, 0.5, 0.999] {
for snow in [false, true] {
let mut random = column_random(x, z);
let reference = if snow {
snow_column(&mut random, ticks, x, -64, 320, z, 0xf000f0, partial)
} else {
rain_column(&mut random, ticks, x, -64, 320, z, 0xf000f0, partial)
};
assert_eq!(
cache
.get(x, z)
.column(snow, ticks, x, -64, 320, z, 0xf000f0, partial),
reference
);
}
}
}
}
}
#[test]
fn parameter_cache_reuses_full_keys_and_stays_bounded() {
let mut cache = ParameterCache::default();
let expected = cache.get(-1, i32::MAX);
// A changed entry proves that a hit does not regenerate random values.
let index = 31 * 32 + 31;
cache.entries[index].as_mut().unwrap().1.rain_speed = 123.0;
assert_eq!(cache.get(-1, i32::MAX).rain_speed, 123.0);
// Colliding positions must replace the entry, rather than reuse it.
cache.get(31, -1);
assert_eq!(cache.get(-1, i32::MAX).rain_speed, expected.rain_speed);
for i in 0..100_000i32 {
cache.get(i.wrapping_mul(3121), i.wrapping_mul(418_711));
}
assert_eq!(cache.entries.len(), 1024);
assert!(cache.entries.iter().flatten().count() <= 1024);
}
#[test]
fn unsplit_vertices_keep_live_geometry_light_and_atlas_inputs() {
let x = i32::MAX - 5;
let z = i32::MIN + 5;
let parameters = Parameters::new(x, z);
let camera = [f64::from(x) - 2.25, 80.75, f64::from(z) + 0.25];
for (bottom_y, top_y, light_coords, radius, intensity, rect) in [
(64, 90, 0, 5, 0.25, [0.1, 0.2, 0.03, 0.04]),
(85, 95, 0xf000f0, 10, 1.0, [0.5, 0.5, 0.1, 0.2]),
] {
let column = Column {
x,
z,
bottom_y,
top_y,
light_coords,
u_offset: 0.0,
v_offset: 0.0,
};
let quad = column_quad(&column, camera, 1.0, radius, intensity);
let vertices = vertices(&column, parameters, false, camera, radius, intensity, rect);
for (a, b) in vertices.iter().zip(quad) {
assert_eq!(a.pos, b.pos);
assert_eq!(a.uv, b.uv);
assert_eq!(a.color, b.color);
assert_eq!(a.rect, rect);
assert_eq!(a.light, if light_coords == 0 { 0 } else { 0xf0f0 });
}
}
}
#[test]
fn rain_repeats_every_four_blocks() {
let column = Column {
@@ -282,6 +555,10 @@ mod tests {
light_coords: 0,
};
let quad = column_quad(&column, [0.5, 70.0, 0.5], 1.0, 10, 1.0);
assert!(quad[0].pos[0].is_nan());
for vertex in quad {
assert!(vertex.pos[0].is_nan());
assert!(vertex.pos[2].is_nan());
assert!(vertex.pos[1].is_finite());
}
}
}
+139 -1
View File
@@ -50,6 +50,64 @@ impl EndIslandSampler {
}
height
}
// Nearby volume columns visit overlapping 25-by-25 island neighborhoods.
// Collect the eligible islands once, retaining their original X/Z order.
// Larger or coordinate-wrapping volumes keep the scalar evaluation path.
fn volume_islands(&self, volume: DensityVolume) -> Option<Vec<(i32, i32, f32)>> {
let sizes = volume.sizes();
if sizes[0] * sizes[2] < 4 {
return None;
}
let minimum = volume.minimum();
let steps = volume.steps();
let end = |axis: usize| {
i32::try_from(
i64::from(minimum[axis]) + (sizes[axis] - 1) as i64 * i64::from(steps[axis]),
)
.ok()
};
let first_x = minimum[0] / 8 / 2 - 12;
let first_z = minimum[2] / 8 / 2 - 12;
let last_x = end(0)? / 8 / 2 + 12;
let last_z = end(2)? / 8 / 2 + 12;
if last_x - first_x >= 64 || last_z - first_z >= 64 {
return None;
}
let mut islands = Vec::new();
for x in first_x..=last_x {
for z in first_z..=last_z {
if i64::from(x) * i64::from(x) + i64::from(z) * i64::from(z) <= 4096
|| self.noise.get2(f64::from(x), f64::from(z)) >= -0.9
{
continue;
}
let scale = ((x as f32).abs() * 3439.0 + (z as f32).abs() * 147.0) % 13.0 + 9.0;
islands.push((x, z, scale));
}
}
Some(islands)
}
fn density_from_islands(x: i32, z: i32, islands: &[(i32, i32, f32)]) -> f32 {
let x = x / 8;
let z = z / 8;
let center_x = x / 2;
let center_z = z / 2;
let mut height = -100.0;
for &(island_x, island_z, scale) in islands {
let offset_x = island_x - center_x;
let offset_z = island_z - center_z;
if !(-12..=12).contains(&offset_x) || !(-12..=12).contains(&offset_z) {
continue;
}
let dx = (x % 2 - offset_x * 2) as f32;
let dz = (z % 2 - offset_z * 2) as f32;
let candidate = 100.0 - ((dx * dx + dz * dz) as f64).sqrt() as f32 * scale;
let candidate =
super::arithmetic::java_min(super::arithmetic::java_max(candidate, -100.0), 80.0);
height = super::arithmetic::java_max(height, candidate);
}
(height - 8.0) / 128.0
}
fn density(&self, x: i32, z: i32) -> f32 {
(self.height(x / 8, z / 8) - 8.0) / 128.0
}
@@ -66,10 +124,15 @@ impl DensitySampler for EndIslandSampler {
) -> Result<(), SampleError> {
check_buffer(buffer, volume)?;
let [sx, sy, sz] = volume.sizes();
let islands = self.volume_islands(volume);
for z in 0..sz {
let block_z = volume.block(Axis::Z, z).unwrap();
for x in 0..sx {
let value = self.density(volume.block(Axis::X, x).unwrap(), block_z);
let block_x = volume.block(Axis::X, x).unwrap();
let value = match &islands {
Some(islands) => Self::density_from_islands(block_x, block_z, islands),
None => self.density(block_x, block_z),
};
let start = (x + z * sx) * sy;
buffer[start..start + sy].fill(value);
}
@@ -77,3 +140,78 @@ impl DensitySampler for EndIslandSampler {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn end_island_volumes_match_scalar_at_truncation_and_world_boundaries() {
let cases = [
([5, 3, 5], [0, -64, 0], [4, 8, 4]),
([5, 3, 5], [1920, -64, 2240], [8, 8, 8]),
([5, 3, 5], [-2049, -64, 3071], [4, 8, 4]),
([5, 3, 5], [1023, -64, -1025], [1, 8, 1]),
([5, 3, 5], [30_000_000, 0, -30_000_000], [8, 1, 8]),
([5, 3, 5], [i32::MIN, 0, i32::MIN], [8, 1, 8]),
([5, 3, 5], [i32::MAX - 32, 0, i32::MAX - 32], [8, 1, 8]),
// Also exercise wrapping, wide, sparse and single-column volumes.
([5, 3, 5], [i32::MAX - 12, 0, i32::MAX - 3], [8, 1, 8]),
([5, 3, 5], [4096, 0, -8192], [1024, 1, 1024]),
([2, 3, 2], [-4096, 0, 8192], [599, 1, 599]),
([1, 4, 1], [-15, 0, -17], [1, 1, 1]),
];
for seed in [0, 12345, -1, i64::MIN, i64::MAX] {
let sampler = EndIslandSampler::new(seed);
let mut context = SamplerContext::default();
let mut compare = |volume: DensityVolume| {
let sentinel = 123.0_f32;
let mut output = vec![sentinel; volume.size() + 1];
sampler
.sample_volume(&mut context, &mut output, volume)
.unwrap();
visit(volume, |index, position| {
let expected = sampler.sample_value(&mut context, position)?;
assert_eq!(
output[index].to_bits(),
expected.to_bits(),
"seed {seed}, position {position:?}, volume {volume:?}"
);
Ok(())
})
.unwrap();
assert_eq!(output[volume.size()], sentinel);
let mut short = vec![sentinel; volume.size() - 1];
assert_eq!(
sampler.sample_volume(&mut context, &mut short, volume),
Err(DensityError::BufferTooShort.into())
);
assert!(short.iter().all(|&value| value == sentinel));
};
for (sizes, minimum, steps) in cases {
compare(DensityVolume::new(sizes, minimum, steps).unwrap());
}
// Every signed remainder around both coordinate divisions, in a
// neighborhood that straddles the central-island exclusion circle.
for offset in -17..=17 {
compare(
DensityVolume::new([5, 2, 5], [1024 + offset, -32, -offset], [3, 16, 5])
.unwrap(),
);
}
}
let sampler = EndIslandSampler::new(12345);
assert!(
sampler
.volume_islands(DensityVolume::new([5, 2, 5], [-2049, 0, 3071], [4, 8, 4]).unwrap())
.is_some()
);
for (sizes, minimum, steps) in [cases[7], cases[8], cases[10]] {
assert!(
sampler
.volume_islands(DensityVolume::new(sizes, minimum, steps).unwrap())
.is_none()
);
}
}
}
@@ -672,6 +672,11 @@ packet!(
/// ClientboundSetPassengersPacket: a vehicle and every entity riding it.
SetPassengers { vehicle: i32 => VarInt, passengers: Vec<i32> => List<VarInt> }
);
packet!(
/// ClientboundMoveVehiclePacket: the server puts a vehicle its rider
/// controls back where it was (PositionAndRotation: x, y, z, yRot, xRot).
MoveVehicle { position: [f64; 3] => Vec3d, yaw: f32 => Float, pitch: f32 => Float }
);
/// ClientboundSetEquipmentPacket: (EquipmentSlot ordinal, stack) pairs.
pub struct Equipment;
impl Codec<Vec<(u8, Option<Stack>)>> for Equipment {
@@ -1529,6 +1534,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
SetHeldSlot(SetHeldSlot) = SET_HELD_SLOT,
SetObjective(SetObjective) = SET_OBJECTIVE,
SetPassengers(SetPassengers) = SET_PASSENGERS,
MoveVehicle(MoveVehicle) = MOVE_VEHICLE,
ProjectilePower(ProjectilePower) = PROJECTILE_POWER,
SetPlayerInventory(SetPlayerInventory) = SET_PLAYER_INVENTORY,
SetPlayerTeam(SetPlayerTeam) = SET_PLAYER_TEAM,
@@ -1802,6 +1808,15 @@ packet!(
packet!(MovePlayerPosRot { x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float, flags: u8 => UByte });
packet!(MovePlayerRot { yaw: f32 => Float, pitch: f32 => Float, flags: u8 => UByte });
packet!(MovePlayerStatus { flags: u8 => UByte });
packet!(
/// ServerboundMoveVehiclePacket: where the rider moved the vehicle it
/// controls (PositionAndRotation, then onGround).
MoveVehicleRequest { position: [f64; 3] => Vec3d, yaw: f32 => Float, pitch: f32 => Float, on_ground: bool => Bool }
);
packet!(
/// ServerboundPaddleBoatPacket: the boat's left and right paddles.
PaddleBoat { left: bool => Bool, right: bool => Bool }
);
packet!(PickItemFromBlock { pos: [i32; 3] => Pos, include_data: bool => Bool });
packet!(
/// ServerboundPlayerActionPacket.Action: 0 start destroy, 1 change destroy
@@ -1869,6 +1884,8 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
MovePlayerPosRot(MovePlayerPosRot) = MOVE_PLAYER_POS_ROT,
MovePlayerRot(MovePlayerRot) = MOVE_PLAYER_ROT,
MovePlayerStatus(MovePlayerStatus) = MOVE_PLAYER_STATUS_ONLY,
MoveVehicle(MoveVehicleRequest) = MOVE_VEHICLE,
PaddleBoat(PaddleBoat) = PADDLE_BOAT,
PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK,
PingRequest(crate::packets::status::Ping) = PING_REQUEST,
PlayerAbilities(PlayerAbilitiesRequest) = PLAYER_ABILITIES,
@@ -3,7 +3,7 @@
//! chunkgen_bench <client resource dir> [--seed S] [--size N] [--threads T]
//! [--center CX CZ] [--verify <material-stage parity dir>] [--no-decorate]
//! [--dimension overworld|the_nether|the_end]
//! [--warmup] [--json] [--no-map]
//! [--warmup] [--json] [--no-map] [--snapshot PATH]
use horizon_core::position::ChunkPos;
use horizon_world::{
DATA_VERSION,
@@ -275,6 +275,7 @@ fn main() -> Result<(), Error> {
let resources = PathBuf::from(args.next().expect("client resource directory"));
let (mut seed, mut size, mut threads, mut center) = (0i64, 16i32, 2usize, (0, 0));
let mut parity = None;
let mut snapshot_path = None;
let mut decorate = true;
let (mut warmup, mut json, mut map) = (false, false, true);
let mut dimension = String::from("minecraft:overworld");
@@ -287,6 +288,7 @@ fn main() -> Result<(), Error> {
"--threads" => threads = next().parse()?,
"--center" => center = (next().parse()?, next().parse()?),
"--verify" => parity = Some(PathBuf::from(next())),
"--snapshot" => snapshot_path = Some(PathBuf::from(next())),
"--no-decorate" => decorate = false,
"--warmup" => warmup = true,
"--json" => json = true,
@@ -409,6 +411,9 @@ fn main() -> Result<(), Error> {
.into_iter()
.map(|slot| slot.into_inner().unwrap())
.collect();
if let Some(path) = &snapshot_path {
snapshot(&chunks, path, "terrain")?;
}
if decorate && size >= 3 {
let totals = Mutex::new(DecorateStats::default());
let start = Instant::now();
@@ -494,6 +499,9 @@ fn main() -> Result<(), Error> {
);
}
}
if let Some(path) = &snapshot_path {
snapshot(&chunks, path, "decorated")?;
}
let mut structures = BTreeMap::<(String, i32, i32), [[i32; 3]; 2]>::new();
for chunk in chunks.iter().flatten() {
for (name, start, min, max) in chunk.structures() {
@@ -570,3 +578,75 @@ fn main() -> Result<(), Error> {
);
Ok(())
}
// Diagnostic only: full ordered chunk state, outside performance measurements.
fn snapshot(chunks: &[Option<ProtoChunk>], path: &Path, phase: &str) -> Result<(), Error> {
use std::io::Write;
let mut out =
std::io::BufWriter::new(fs::File::create(format!("{}-{phase}.bin", path.display()))?);
for chunk in chunks.iter().flatten() {
let terrain = &chunk.terrain;
writeln!(
out,
"chunk {:?} {:?} {} {:?} {:?}",
chunk.position(),
terrain.generation_stage(),
chunk.is_decorated(),
chunk.structures(),
terrain.below_zero_retrogen().map(|v| v.to_nbt())
)?;
for section in 0..terrain.height() as usize / 16 {
let data = terrain.section(section).unwrap();
writeln!(out, "section {section} {:?}", data.to_nbt()?)?;
for index in 0..4096 {
out.write_all(&data.get(index)?.0.to_le_bytes())?;
}
}
// Compare public reads too, including all-air section behavior.
for y in terrain.min_y()..terrain.min_y() + terrain.height() {
for z in 0..16 {
for x in 0..16 {
out.write_all(&terrain.block(x, y, z).0.to_le_bytes())?;
}
}
}
for y in (terrain.min_y() >> 2)..((terrain.min_y() + terrain.height()) >> 2) {
for z in 0..4 {
for x in 0..4 {
writeln!(
out,
"biome {}",
chunk.biome_at(
chunk.position().x * 16 + x * 4,
y * 4,
chunk.position().z * 16 + z * 4
)
)?;
}
}
}
for kind in HeightmapType::ALL {
writeln!(
out,
"heightmap {kind:?} {:?}",
terrain.heightmap(kind).map(|m| m.raw_data())
)?;
}
writeln!(out, "post {:?}", terrain.postprocessing())?;
writeln!(out, "blockticks {:?}", terrain.block_ticks().pack(0))?;
writeln!(out, "fluidticks {:?}", terrain.fluid_ticks().pack(0))?;
for (position, tag) in &chunk.block_entities {
writeln!(out, "blockentity {position:?}")?;
let bytes =
horizon_world::nbt::write_network(&Tag::Compound(tag.clone()), Default::default())?;
out.write_all(&(bytes.len() as u64).to_le_bytes())?;
out.write_all(&bytes)?;
}
let entities = Tag::List(chunk.entities.iter().cloned().map(Tag::Compound).collect());
let bytes = horizon_world::nbt::write_network(&entities, Default::default())?;
out.write_all(&(bytes.len() as u64).to_le_bytes())?;
out.write_all(&bytes)?;
}
out.flush()?;
Ok(())
}
@@ -20,6 +20,7 @@ struct Cells {
cells: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
obstructed: bool,
}
impl LevelAccess for Cells {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
@@ -37,6 +38,9 @@ impl LevelAccess for Cells {
fn game_time(&self) -> i64 {
0
}
fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool {
!self.obstructed
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -68,6 +72,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
cells,
air,
random: LegacyRandom::new(case["seed"].as_i64().unwrap()),
obstructed: case["obstructed"].as_bool().unwrap_or(false),
};
let mut ticks = Ticks::new(0);
for x in -2..=2 {
+323 -23
View File
@@ -995,6 +995,46 @@ where
worker.terrain_context = context;
result
}
/// With the native End source there are no badlands/iceberg extensions.
/// Disabled aquifers with air as their default fluid can only add lava or
/// air to the default solid, so this constant rule would rewrite each solid
/// with the state it already has. Check their imported material flags too.
/// Noise filling already built the WG maps; these writes add no fluid marks.
fn identity_end_surface(&self, pos: ChunkPos) -> bool {
if !matches!(self.source, ResolvedBiomeSource::End(_))
// At wrapped block coordinates the ordinary biome-region lookup
// can fail; retain that lookup and its error outside this range.
|| ![pos.x, pos.z].into_iter().all(|c| {
c.checked_mul(16).is_some_and(|b| {
b.checked_sub(16).is_some() && b.checked_add(31).is_some()
})
})
|| self.aquifer.is_some()
|| Some(self.settings.default_block)
!= self.data.registry.default_state("minecraft:end_stone")
|| Some(self.settings.default_fluid)
!= self.data.registry.default_state("minecraft:air")
|| !self.data.states.get(self.settings.default_fluid).air
|| !self
.data
.registry
.default_state("minecraft:lava")
.is_some_and(|lava| self.data.states.get(lava).fluid)
{
return false;
}
let mut rule = &self.rule;
// Restrict the shortcut to shallow block references; other rules still
// run their normal compilation, queries and error handling.
for _ in 0..32 {
match rule {
MaterialRule::Reference(next) => rule = next,
MaterialRule::Block(state) => return *state == self.settings.default_block,
_ => return false,
}
}
false
}
fn generate_with_context(
&self,
worker: &mut WorkerState,
@@ -1103,27 +1143,34 @@ where
.map_err(stage("noise"))?;
let generation = self.generation();
worker.timings.noise += lap(&mut clock);
build_surface(
&mut chunk,
self.rule.clone(),
SurfaceInputs::<R, _> {
generation,
noise_volume: volume,
root: self.root.clone(),
surface: SurfaceQueries {
pipeline: self,
temperatures: &mut worker.temperatures,
biome: Biomes::Region(&biomes),
possible: Some(possible),
if !self.identity_end_surface(pos) {
build_surface(
&mut chunk,
self.rule.clone(),
SurfaceInputs::<R, _> {
generation,
noise_volume: volume,
root: self.root.clone(),
surface: SurfaceQueries {
pipeline: self,
temperatures: &mut worker.temperatures,
biome: Biomes::Region(&biomes),
uniform_biomes: Some(UniformSurfaceBiomes::new(
pos,
self.settings.level_min_y,
self.settings.level_height,
)),
possible: Some(possible),
},
preliminary_surface: self.preliminary.clone(),
density_context: context,
write_min_y: min,
write_max_y: min + height - 1,
},
preliminary_surface: self.preliminary.clone(),
density_context: context,
write_min_y: min,
write_max_y: min + height - 1,
},
&self.extensions,
)
.map_err(stage("surface"))?;
&self.extensions,
)
.map_err(stage("surface"))?;
}
worker.timings.surface += lap(&mut clock);
let carvers = &data.biome_carvers;
let mask = generate_carving_mask(self.seed, pos, generation, false, |origin| {
@@ -1149,6 +1196,7 @@ where
pipeline: self,
temperatures: &mut worker.temperatures,
biome: Biomes::Resolver(&mut resolver, &mut biome_context),
uniform_biomes: None,
possible: None,
},
preliminary_surface: self.preliminary.clone(),
@@ -1393,6 +1441,63 @@ enum Biomes<'a, 'b> {
&'a mut SamplerContext,
),
}
// Lazy equality proofs for the eight quart corners of a block-biome cell.
// Adjacent blocks share these candidates even though their zoom distances differ.
struct UniformSurfaceBiomes {
origin: [i32; 3],
height: i32,
cells: Vec<Option<Option<BiomeId>>>,
}
impl UniformSurfaceBiomes {
fn new(pos: ChunkPos, min_y: i32, height: i32) -> Self {
let height = (height >> 2) + 1;
Self {
origin: [
pos.x.wrapping_shl(4).wrapping_sub(2) >> 2,
min_y.wrapping_sub(2) >> 2,
pos.z.wrapping_shl(4).wrapping_sub(2) >> 2,
],
height,
cells: vec![None; 25 * height as usize],
}
}
fn get(&mut self, region: &BiomeRegion<BiomeId>, p: BlockPos) -> Option<BiomeId> {
let base = [p.x, p.y, p.z].map(|v| v.wrapping_sub(2) >> 2);
let d: [i32; 3] = std::array::from_fn(|i| base[i].wrapping_sub(self.origin[i]));
if !(0..5).contains(&d[0]) || !(0..self.height).contains(&d[1]) || !(0..5).contains(&d[2]) {
return None;
}
let slot = &mut self.cells[((d[0] * 5 + d[2]) * self.height + d[1]) as usize];
if let Some(value) = slot {
return *value;
}
let value = (|| {
// These are immutable stored lookups. A missing candidate prevents
// the shortcut; only the original selected lookup may report errors.
let first = *region.noise_biome(base).ok()?;
for x in 0..2 {
for y in 0..2 {
for z in 0..2 {
if *region
.noise_biome([
base[0].wrapping_add(x),
base[1].wrapping_add(y),
base[2].wrapping_add(z),
])
.ok()?
!= first
{
return None;
}
}
}
}
Some(first)
})();
*slot = Some(value);
value
}
}
/// Material-rule world queries for one chunk: shared seed-bound noises, the
/// worker's temperature caches and either stored or raw-resolver biomes.
struct SurfaceQueries<'a, 'b, R: RandomSource> {
@@ -1400,6 +1505,7 @@ struct SurfaceQueries<'a, 'b, R: RandomSource> {
temperatures: &'a mut [BiomeTemperature],
biome: Biomes<'a, 'b>,
possible: Option<BTreeSet<String>>,
uniform_biomes: Option<UniformSurfaceBiomes>,
}
impl<R: RandomSource> SurfaceQueries<'_, '_, R> {
fn temperature(&mut self, name: &str) -> Result<&mut BiomeTemperature, MaterialRuleError> {
@@ -1437,9 +1543,16 @@ impl<R: RandomSource> MaterialSurfaceQueries for SurfaceQueries<'_, '_, R> {
fn biome(&mut self, p: BlockPos) -> Result<Option<Arc<str>>, MaterialRuleError> {
let data = &self.pipeline.data;
let id = match &mut self.biome {
Biomes::Region(region) => *region
.biome(p)
.map_err(|_| MaterialRuleError::MissingBiome)?,
Biomes::Region(region) => match self
.uniform_biomes
.as_mut()
.and_then(|cache| cache.get(region, p))
{
Some(id) => id,
None => *region
.biome(p)
.map_err(|_| MaterialRuleError::MissingBiome)?,
},
Biomes::Resolver(resolver, context) => {
let name = resolver
.sample(context, self.pipeline.zoom.quart_at_block(p))
@@ -1778,6 +1891,7 @@ where
pipeline: self,
temperatures: &mut worker.temperatures,
biome: Biomes::Resolver(&mut resolver, &mut biome_context),
uniform_biomes: None,
possible: None,
};
let sources = MaterialDensitySources::new(
@@ -1944,6 +2058,7 @@ where
pipeline: self,
temperatures: &mut worker.temperatures,
biome: Biomes::Resolver(&mut resolver, &mut biome_context),
uniform_biomes: None,
possible: None,
};
let sources = MaterialDensitySources::new(
@@ -2407,6 +2522,191 @@ impl GeneratorWorker {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn end_identity_surface_matches_normal_surface_and_rejects_custom_rules() {
let root = std::env::var_os("HORIZON_TEST_RESOURCES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3")
});
if !root.join("worldgen/world_presets.json").exists() {
eprintln!("skipping: no worldgen bundle at {}", root.display());
return;
}
let registry = Box::leak(Box::new(crate::level::data::load_registry(&root).unwrap()));
let data = GeneratorData::load(&root.join("worldgen"), registry).unwrap();
let preset: Value = serde_json::from_str(&data.world_presets["minecraft:normal"]).unwrap();
let settings: Value = serde_json::from_str(&data.settings["minecraft:end"]).unwrap();
let mut pipeline = Pipeline::new(
data.clone(),
12345,
LegacyRandom::new(12345),
&preset["dimensions"]["minecraft:the_end"]["generator"],
&settings,
false,
None,
)
.unwrap();
let mut worker = OverworldGenerator::for_world(
data.clone(),
12345,
"minecraft:normal",
"minecraft:the_end",
false,
)
.unwrap()
.worker();
assert!(pipeline.identity_end_surface(ChunkPos::new(0, 0)));
for pos in [
ChunkPos::new(0, 0),
ChunkPos::new(128, 128),
ChunkPos::new(-128, 192),
ChunkPos::new(1_875_000, -1_875_000),
] {
let actual = pipeline.generate(&mut worker.state, pos).unwrap();
let rule = pipeline.rule.clone();
// A singleton sequence evaluates the same block rule through the full surface path.
pipeline.rule = MaterialRule::Sequence(vec![rule.clone()]);
assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0)));
let expected = pipeline.generate(&mut worker.state, pos).unwrap();
pipeline.rule = rule;
assert_eq!(
actual.terrain.generation_stage(),
expected.terrain.generation_stage()
);
for section in 0..actual.terrain.height() as usize / 16 {
assert_eq!(
actual.terrain.section(section).unwrap().to_nbt().unwrap(),
expected.terrain.section(section).unwrap().to_nbt().unwrap()
);
}
for kind in HeightmapType::ALL {
assert_eq!(
actual.terrain.heightmap(kind).map(|m| m.raw_data()),
expected.terrain.heightmap(kind).map(|m| m.raw_data())
);
}
assert_eq!(
actual.terrain.postprocessing(),
expected.terrain.postprocessing()
);
assert_eq!(
actual.terrain.block_ticks().pack(0),
expected.terrain.block_ticks().pack(0)
);
assert_eq!(
actual.terrain.fluid_ticks().pack(0),
expected.terrain.fluid_ticks().pack(0)
);
assert_eq!(actual.block_entities, expected.block_entities);
assert_eq!(actual.entities, expected.entities);
assert_eq!(actual.structures(), expected.structures());
}
assert!(!pipeline.identity_end_surface(ChunkPos::new(i32::MAX, 0)));
let old_rule = pipeline.rule.clone();
pipeline.rule = MaterialRule::Block(registry.default_state("minecraft:stone").unwrap());
assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0)));
pipeline.rule = old_rule;
let old_fluid = pipeline.settings.default_fluid;
pipeline.settings.default_fluid = registry.default_state("minecraft:stone").unwrap();
assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0)));
pipeline.settings.default_fluid = old_fluid;
let old_source = std::mem::replace(
&mut pipeline.source,
ResolvedBiomeSource::Fixed(super::super::biome_source::FixedBiomeSource {
biome: "minecraft:the_end".into(),
}),
);
assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0)));
pipeline.source = old_source;
pipeline.aquifer = Some(std::array::from_fn(|_| {
pipeline.router.get(RouterField::Erosion).clone()
}));
assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0)));
}
#[test]
fn uniform_surface_biomes_preserve_zoom_and_missing_corner_errors() {
use super::super::biome_chunk::BiomeChunk;
use std::convert::Infallible;
for pos in [
ChunkPos::new(0, 0),
ChunkPos::new(-17, 23),
ChunkPos::new(i32::MIN >> 4, i32::MAX >> 4),
] {
for seed in [0, -1, i64::MIN] {
for mixed in [false, true] {
let mut chunks = Vec::new();
for dz in -1..=1 {
for dx in -1..=1 {
let mut chunk = BiomeChunk::new(
ChunkPos::new(pos.x + dx, pos.z + dz),
-64,
128,
BiomeId(7),
)
.unwrap();
chunk
.fill(-64, 63, |[x, y, z]| {
Ok::<_, Infallible>(if mixed {
BiomeId(
(x.div_euclid(3) + y.div_euclid(4) + z.div_euclid(2))
.rem_euclid(5)
as u32,
)
} else {
BiomeId(7)
})
})
.unwrap();
chunks.push(chunk);
}
}
let region = BiomeRegion::new(chunks, seed).unwrap();
let mut cache = UniformSurfaceBiomes::new(pos, -64, 128);
let mut hits = 0;
for x in 0..16 {
for z in 0..16 {
// Include clamped Y, out-of-cache Y, and revisit each
// cached proof in the ordinary descending traversal.
for y in (-70..70).rev() {
let p = BlockPos::new(pos.x * 16 + x, y, pos.z * 16 + z);
let shortcut = cache.get(&region, p);
hits += usize::from(shortcut.is_some());
let actual = shortcut.map_or_else(|| region.biome(p).copied(), Ok);
assert_eq!(actual, region.biome(p).copied());
}
}
}
if !mixed && pos.x != i32::MIN >> 4 {
assert!(hits > 0);
}
}
}
}
// Some unselected corners are missing. Probing them must neither invent
// an error nor hide the original selected-corner error.
let pos = ChunkPos::new(0, 0);
let region =
BiomeRegion::new(vec![BiomeChunk::new(pos, 0, 16, BiomeId(7)).unwrap()], -1).unwrap();
let mut cache = UniformSurfaceBiomes::new(pos, 0, 16);
let mut successes = 0;
let mut failures = 0;
for x in -2..18 {
for z in -2..18 {
let p = BlockPos::new(x, 7, z);
let actual = cache
.get(&region, p)
.map_or_else(|| region.biome(p).copied(), Ok);
assert_eq!(actual, region.biome(p).copied());
successes += usize::from(actual.is_ok());
failures += usize::from(actual.is_err());
}
}
assert!(successes > 0 && failures > 0);
}
#[test]
fn far_surface_matches_undecorated_land_and_keeps_end_void() {
Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

@@ -27,7 +27,7 @@ import net.minecraft.world.phys.shapes.CollisionContext;
/**
* Native BlockItem placement-state selection (BlockPlaceContext resolution,
* updatePlacementContext and getPlacementState) over generated neighbourhoods.
* Entities never obstruct; nothing is written to the world.
* Entity obstruction can be scripted; nothing is written to the world.
*/
public final class VanillaBlockPlacementOracle {
static Object unsafe;
@@ -67,6 +67,7 @@ public final class VanillaBlockPlacementOracle {
static final class World extends net.minecraft.server.level.ServerLevel {
Map<BlockPos, BlockState> cells;
RandomSource random;
boolean obstructed;
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@@ -77,7 +78,7 @@ public final class VanillaBlockPlacementOracle {
@Override public RandomSource getRandom() { return random; }
@Override public int getMinY() { return -64; }
@Override public int getHeight() { return 384; }
@Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return true; }
@Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return !obstructed; }
@Override public boolean isUnobstructed(Entity entity) { return true; }
@Override public void scheduleTick(BlockPos pos, Block block, int delay) { }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); }
@@ -116,6 +117,7 @@ public final class VanillaBlockPlacementOracle {
world.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt()));
}
world.random = new LegacyRandomSource(f.get("seed").getAsLong());
world.obstructed = f.has("obstructed") && f.get("obstructed").getAsBoolean();
var player = make(FakePlayer.class);
player.world = world;
player.yaw = f.get("yaw").getAsFloat();
@@ -6,9 +6,14 @@ import java.io.PrintWriter;
import net.minecraft.client.*;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.*;
import net.minecraft.world.item.*;
import net.minecraft.world.item.component.SwingAnimation;
import net.minecraft.world.level.GameType;
/** Runs the real key handler through its drop loop; stops before item-use handling. */
@@ -41,16 +46,36 @@ public final class VanillaHeldDropOracle {
}
static final class Actor extends LocalPlayer {
GameType mode;
int swings;
Actor() { super(null, null, null, null, null, null, false, null, null); }
@Override public GameType gameMode() { return mode; }
@Override public boolean isUsingItem() { throw new Done(); }
@Override public boolean swing(InteractionHand hand, SwingAnimation animation, boolean sendPacket) {
if (hand != InteractionHand.MAIN_HAND || !animation.equals(SwingAnimation.DEFAULT) || sendPacket)
throw new AssertionError("unexpected drop swing");
swings++;
return true;
}
}
static final class Connection extends ClientPacketListener {
int drops;
ServerboundPlayerActionPacket.Action expected;
Connection() { super(null, null, null); }
@Override public void send(Packet<?> packet) {
if (packet instanceof ServerboundPlayerActionPacket action) {
if (action.getAction() != expected) throw new AssertionError("unexpected drop action");
drops++;
}
}
}
static final class Controller extends MultiPlayerGameMode {
int dropped;
Controller() { super(null, null); }
// Controlled dispatch boundary: no networking, swings, statistics or item entities.
// Run vanilla's actual prediction, packet dispatch and conditional swing.
@Override public void dropItem(LocalPlayer player, boolean all) {
dropped += player.getInventory().removeFromSelected(all).getCount();
int before = player.getInventory().getSelectedItem().getCount();
super.dropItem(player, all);
dropped += before - player.getInventory().getSelectedItem().getCount();
}
}
public static void main(String[] args) throws Exception {
@@ -81,6 +106,9 @@ public final class VanillaHeldDropOracle {
field(Player.class, "inventory").set(actor, inventory);
field(Minecraft.class, "player").set(client, actor);
var controller = make(Controller.class);
var connection = make(Connection.class);
field(MultiPlayerGameMode.class, "minecraft").set(controller, client);
field(MultiPlayerGameMode.class, "connection").set(controller, connection);
field(Minecraft.class, "gameMode").set(client, controller);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) {
for (var mode : GameType.values()) for (boolean all : new boolean[]{false, true}) {
@@ -91,6 +119,10 @@ public final class VanillaHeldDropOracle {
inventory.setSelectedSlot(selected);
inventory.setItem(selected, new ItemStack(Items.STONE, count));
controller.dropped = 0;
actor.swings = 0;
connection.drops = 0;
connection.expected = all ? ServerboundPlayerActionPacket.Action.DROP_ALL_ITEMS
: ServerboundPlayerActionPacket.Action.DROP_ITEM;
// Two consecutive key presses also cover an emptied stack and repeated spectator drops.
for (int press = 0; press < 2; press++) {
((Key) options.keyDrop).clicks = 1;
@@ -100,7 +132,8 @@ public final class VanillaHeldDropOracle {
} catch (InvocationTargetException e) {
if (!(e.getCause() instanceof Done)) throw e;
}
out.println(inventory.getSelectedItem().getCount() + " " + controller.dropped);
out.println(inventory.getSelectedItem().getCount() + " " + controller.dropped
+ " " + actor.swings + " " + connection.drops);
}
}
}
+149
View File
@@ -0,0 +1,149 @@
"""Exercise the live remote_mining method with scripted world and packet sinks.
Vanilla reference: MultiPlayerGameMode.startDestroyBlock/continueDestroyBlock.
The first_person parity harness separately checks consecutive instant breaks
against the pinned client; this fixture catches drift in the multiplayer path.
"""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
@unittest.skipUnless(shutil.which("rustc"), "requires Rust")
class RemoteMiningTests(unittest.TestCase):
def test_break_timing_and_packets(self):
source = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text()
start = source.index(" fn remote_mining(")
end = source.index(" /// MultiPlayerGameMode.destroyBlock", start)
fixture = r'''
#![allow(dead_code)]
#[derive(Clone, Copy)]
struct Hit { pos: [i32; 3], face: u8 }
struct Mining { pos: [i32; 3], progress: f32, ticks: u32 }
#[derive(Default)]
struct Remote { destroy_delay: u32, destroying: Option<([i32; 3], u8, f32)> }
struct Ground { on_ground: bool }
struct Player { ground: Ground }
#[derive(Clone)]
struct Sounds { hit: String, volume: f32, pitch: f32 }
#[derive(Clone)]
struct Facts { hardness: f32, name: String, requires_tool: bool, sounds: Sounds }
struct Resources { facts: Facts, speed: f32 }
impl Resources {
fn facts(&self) -> &Self { self }
fn items(&self) -> &Self { self }
fn get(&self, _: u32) -> &Facts { &self.facts }
fn is_air(&self, state: u32) -> bool { state == 0 }
fn mining_speed(&self, _: Option<&()>, _: &str) -> f32 { self.speed }
fn correct_for_drops(&self, _: Option<&()>, _: &str) -> bool { true }
}
#[derive(Default)]
struct World { broken: Vec<[i32; 3]> }
impl World {
fn block(&self, x: i32, y: i32, z: i32) -> u32 {
u32::from(!self.broken.contains(&[x, y, z]))
}
}
struct Audio;
impl Audio {
fn play(&self, _: &str, _: Option<[f64; 3]>, _: f32, _: f32) {}
}
mod play {
#[derive(Debug, PartialEq)]
pub struct PlayerAction {
pub action: u8, pub pos: [i32; 3], pub direction: u8, pub sequence: i32,
}
}
enum S { PlayerAction(play::PlayerAction) }
fn face_direction(face: u8) -> u8 { face }
struct Game {
remote: Option<Remote>, mining: Option<Mining>, creative: bool,
world: World, res: Resources, player: Option<Player>, audio: Audio,
hit: Hit, sequence: i32, packets: Vec<play::PlayerAction>,
}
impl Game {
fn new(hardness: f32, speed: f32, creative: bool) -> Self {
Self {
remote: Some(Remote::default()), mining: None, creative,
world: World::default(),
res: Resources { facts: Facts { hardness, name: "block".into(),
requires_tool: false, sounds: Sounds { hit: "hit".into(), volume: 1.0, pitch: 1.0 } }, speed },
player: Some(Player { ground: Ground { on_ground: true } }), audio: Audio,
hit: Hit { pos: [0, 64, 0], face: 1 }, sequence: 0, packets: vec![],
}
}
fn pick(&self) -> Option<Hit> { Some(self.hit) }
fn held(&self) -> Option<&()> { None }
fn next_sequence(&mut self) -> i32 { self.sequence += 1; self.sequence }
fn predict_break(&mut self, pos: [i32; 3], _: u32, _: i32) { self.world.broken.push(pos); }
fn send(&mut self, S::PlayerAction(packet): S) { self.packets.push(packet); }
fn crack_particle(&mut self, _: [i32; 3], _: u8, _: u32) {}
METHOD
}
fn main() {
// Zero-hardness blocks and a tool fast enough to break in one tick.
for (hardness, speed) in [(0.0, 1.0), (0.5, 15.0), (0.5, 30.0)] {
let mut game = Game::new(hardness, speed, false);
for tick in 0..8 {
game.hit.pos[0] = tick;
game.remote_mining(tick == 0);
assert_eq!(game.world.broken.len(), tick as usize + 1,
"instant break must happen every held tick");
let remote = game.remote.as_ref().unwrap();
assert_eq!(remote.destroy_delay, 0);
assert!(remote.destroying.is_none());
assert!(game.mining.is_none());
assert_eq!(game.packets[tick as usize], play::PlayerAction {
action: 0, pos: [tick, 64, 0], direction: 1, sequence: tick + 1,
});
}
assert_eq!(game.packets.len(), 8, "instant breaks only send START");
}
// Gradual breaking still sends STOP and waits five continuation ticks.
let mut game = Game::new(1.0, 15.0, false);
game.remote_mining(true);
assert!(game.world.broken.is_empty());
game.remote_mining(false);
assert!(game.world.broken.is_empty());
game.remote_mining(false);
assert_eq!(game.world.broken.len(), 1);
assert_eq!(game.packets.iter().map(|p| p.action).collect::<Vec<_>>(), [0, 3]);
assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5);
game.hit.pos[0] = 1;
for _ in 0..5 {
game.remote_mining(false);
assert_eq!(game.packets.len(), 2);
}
game.remote_mining(false);
assert_eq!(game.packets.len(), 3);
assert_eq!(game.packets[2].action, 0);
// Creative also keeps its five-tick delay, even for zero-hardness blocks.
let mut game = Game::new(0.0, 1.0, true);
game.remote_mining(true);
game.hit.pos[0] = 1;
assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5);
for _ in 0..5 {
game.remote_mining(false);
assert_eq!(game.world.broken.len(), 1);
}
game.remote_mining(false);
assert_eq!(game.world.broken.len(), 2);
assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5);
}
'''.replace("METHOD", source[start:end])
with tempfile.TemporaryDirectory(prefix="remote-mining-") as directory:
path = Path(directory)
(path / "main.rs").write_text(fixture)
subprocess.run(["rustc", "--edition=2024", str(path / "main.rs"), "-o", str(path / "probe")],
check=True, capture_output=True, text=True)
result = subprocess.run([str(path / "probe")], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
if __name__ == "__main__":
unittest.main()
+46 -2
View File
@@ -10,7 +10,8 @@ the options scenario reads and sets options.txt values by key; the events scenar
states (wait-for) and reads the event log; the consume scenario eats and drinks consumables (a
golden apple, milk, honey, chorus fruit) and checks their effects, remainders and teleport; the
pick scenario middle-clicks slots (AbstractContainerScreen's cloning): a full stack in creative, from
the hotbar and from an item tab, and nothing in survival.
the hotbar and from an item tab, and nothing in survival; the suggestions scenario checks
slash-command Tab completion on single player's connected client after a fresh launch.
python3 tools/agent_control_e2e.py # both modes
python3 tools/agent_control_e2e.py --mode mcp # one of them
@@ -45,6 +46,7 @@ LOG_KINDS = ['oak_log', 'birch_log', 'spruce_log', 'jungle_log', 'acacia_log', '
'mangrove_log', 'cherry_log']
# Positional arguments of the commands the scenario uses, for the CLI.
POSITIONAL = {
'key': ['key', 'action'],
'goto': ['x', 'y', 'z'], 'break': ['x', 'y', 'z'], 'place': ['x', 'y', 'z'], 'block': ['x', 'y', 'z'],
'find_block': ['block', 'radius'], 'entities': ['radius', 'type'], 'click_slot': ['slot'],
'click_button': ['label'], 'type': ['text'], 'wait': ['ticks'], 'wait_ready': ['seconds'],
@@ -522,8 +524,50 @@ def pick_scenario(d, out):
return {'cloned': shown['item']}
def suggestions_scenario(d, out):
# Start from the title screen: single player's client joins through memory,
# without opening a server world and building its command registries.
d('click', id='singleplayer')
if 'game' not in widgets(d):
d('click', id='create-new-world')
d('type', field='name', replace=True, text='Suggestions')
d('click', id='game-mode') # survival -> hardcore -> creative (commands on)
d('click', id='game-mode')
d('type', field='seed', text='5')
d('click', id='world')
d('click', id='world-type') # superflat: this checks chat, without a spawn search
d('click', id='create-new-world')
d('wait_for', condition='loaded', timeout=400)
d('wait_ready', seconds=400)
cases = [
('/giv', '/give'),
('/fill ^', '/fill ^ ^'),
('/give @s diamond_sw', '/give @s minecraft:diamond_sword'),
('/setblock ~ ~ ~ diamond_blo', '/setblock ~ ~ ~ minecraft:diamond_block'),
('/fill ~ ~ ~ ~1 ~1 ~1 diamond_blo', '/fill ~ ~ ~ ~1 ~1 ~1 minecraft:diamond_block'),
('/setblock ~ ~ ~ oak_stairs[fa', '/setblock ~ ~ ~ oak_stairs[facing='),
('/clear @s diamond_sw', '/clear @s minecraft:diamond_sword'),
('/execute run give @s diamond_sw', '/execute run give @s minecraft:diamond_sword'),
]
for text, expected in cases:
d('key', key='t', action='tap')
d('type', text=text)
if text == '/give @s diamond_sw':
shot = d('screenshot', path=str((out / f'{d.name}-suggestions.png').resolve()))
if '_image' in shot:
(out / f'{d.name}-suggestions.png').write_bytes(shot['_image'])
d('key', key='tab', action='tap')
actual = d('screen')['chat_input']
assert actual == expected, (text, expected, actual)
d('key', key='esc', action='tap')
if d('screen')['screen'] == 'chat': # Escape first dismisses suggestions
d('key', key='esc', action='tap')
return {'completions': len(cases)}
SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario,
'consume': consume_scenario, 'pick': pick_scenario}
'consume': consume_scenario, 'pick': pick_scenario, 'suggestions': suggestions_scenario}
def run(mode, ctl, out, resources, which='survival'):
+228 -2
View File
@@ -116,6 +116,15 @@ address. The script then checks, from both sides, what a guest's game used to ge
and wheat on farmland grows (random ticks), however the host runs its world.
- ladder: the guest climbs down ten blocks of ladder and lands unhurt: the server resets its fall
distance on a ladder every tick, as LivingEntity.handleOnClimbable does (#1255).
- boats: the host (single player, on its server thread or not) and the guest each right-click a
boat on water and ride it, paddle it forward (the other side sees it move), sneak out,
and break it with their fists (#1222).
- minecarts: the host and the guest each get into a minecart on rails, sneak out beside it, and break
it (#1222).
- frames: the host and the guest each put a diamond in an item frame and turn it, and put a
helmet on an armor stand and take it back (#1222).
- lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the
sky (on its server thread the host's window is a client of it too).
- flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival:
the guest, and on the server thread the host's window too, take what may fly from the
server's abilities (ClientPacketListener.handlePlayerAbilities).
@@ -157,7 +166,7 @@ ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
# The host plays single player on its server thread (--server-thread).
SERVER_THREAD = False
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning']
class Game:
@@ -2310,6 +2319,223 @@ def check_ladder(host, guest, out):
guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
def apart(host, guest):
"""The host where it stands and the guest 12 blocks east, each on a stone floor with room
around: neither stands in the other's way (a ray from inside a player's box hits that player)."""
x, y, z = (int(v // 1) for v in pos_of(host))
spots = {}
for label, player, dx in (('host', host, 0), ('guest', guest, 12)):
px = x + dx
host('command', command=f'fill {px - 3} {y - 1} {z - 3} {px + 4} {y - 1} {z + 6} minecraft:stone')
host('command', command=f'fill {px - 3} {y} {z - 3} {px + 4} {y + 3} {z + 6} minecraft:air')
player('command', command=f'tp @s {px + 0.5} {y} {z + 0.5} 0 0')
spots[label] = (px, y, z)
host.wait(10)
guest.wait(10)
return spots
def board(player, kind, at):
"""Right-click the `kind` object near `at` and check `player` rides it."""
found = [o for o in player('status')['objects'] if o['kind'].endswith(kind)
and abs(o['position'][0] - at[0]) < 2 and abs(o['position'][2] - at[2]) < 2]
assert found, f'no {kind} near {at}'
vehicle = found[0]
vp = vehicle['position']
player.raw('look-at', f'{vp[0]:.2f}', f'{vp[1] + 0.3:.2f}', f'{vp[2]:.2f}')
player.raw('mouse', 'right', 'click')
player.wait(10)
riding = player('status').get('riding')
assert riding == vehicle['id'], f'right-clicking the {kind} {vehicle["id"]}: riding {riding}'
return vehicle
def leave_vehicle(player, kind):
player.raw('key', 'shift', 'down')
player.wait(10)
player.raw('key', 'shift', 'up')
player.wait(10)
riding = player('status').get('riding')
assert riding is None, f'sneaking out of the {kind}: riding {riding}'
def break_vehicle(player, vehicle_id, kind):
"""Hit it with fists until it breaks: VehicleEntity.tick takes 1 off its damage every tick."""
for _ in range(10):
here = [o for o in player('status')['objects'] if o['id'] == vehicle_id]
if not here:
return
vp = here[0]['position']
player.raw('look-at', f'{vp[0]:.2f}', f'{vp[1] + 0.3:.2f}', f'{vp[2]:.2f}')
player.raw('mouse', 'left', 'click')
player.wait(2)
raise AssertionError(f'ten hits left the {kind} in place')
def check_boats(host, guest, out):
"""#1222: the host (single player, on its server thread or not) and the guest each board a boat
on water with a right click, paddle it forward (the other side sees it move), sneak out, and
break it with their fists."""
result = {}
spots = apart(host, guest)
for label, player, other in (('host', host, guest), ('guest', guest, host)):
x, y, z = spots[label]
bx = x + 3
player('command', command='gamemode survival')
# A pool ten blocks long in a stone basin (the world may float), with a path beside it to
# walk back to the boat.
player('command', command=f'fill {bx - 3} {y} {z - 2} {bx + 2} {y + 3} {z + 10} minecraft:air')
player('command', command=f'fill {bx - 3} {y - 2} {z - 2} {bx + 2} {y - 1} {z + 10} minecraft:stone')
player('command', command=f'fill {bx - 1} {y - 1} {z - 1} {bx + 1} {y - 1} {z + 9} minecraft:water')
player('command', command=f'summon minecraft:oak_boat {bx + 0.5} {y - 0.1} {z + 0.5}')
player.wait(30)
try:
boat = board(player, 'oak_boat', (bx + 0.5, y, z + 0.5))
start = boat['position']
# The summoned boat faces south: forward paddles it along the pool.
player.raw('key', 'w', 'down')
player.wait(30)
player.raw('key', 'w', 'up')
player.wait(20)
mine = [o for o in player('status')['objects'] if o['id'] == boat['id']]
assert mine, f'the {label} lost its boat'
moved = math.dist(start, mine[0]['position'])
assert moved > 0.5, f'paddling forward moved the {label}\'s boat {moved:.2f} blocks'
# The other side sees the boat where its rider took it (the server accepted its moves).
theirs = [o for o in objects_near(other, mine[0]['position'], 'objects')
if o['kind'].endswith('oak_boat')]
assert theirs, f'the other side sees no boat near the {label}\'s'
far = min(math.dist(o['position'], mine[0]['position']) for o in theirs)
assert far < 1.0, f'the other side sees the {label}\'s boat {far:.2f} blocks off'
leave_vehicle(player, 'boat')
player('command', command=f'tp @s {bx - 1.5} {y} {mine[0]["position"][2]:.2f}')
player.wait(5)
break_vehicle(player, boat['id'], 'boat')
result[label] = {'boat': boat['id'], 'paddled': round(moved, 2), 'broken': True}
finally:
player('command', command=f'kill @e[type=minecraft:oak_boat,x={bx},y={y},z={z + 4},distance=..10]')
player('command', command=f'fill {bx - 1} {y - 1} {z - 1} {bx + 1} {y - 1} {z + 9} minecraft:stone')
player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
player.wait(5)
return result
def check_minecarts(host, guest, out):
"""#1222: the host and the guest each get into a minecart on rails with a right click, sneak out
beside it, and break it with their fists."""
result = {}
spots = apart(host, guest)
for label, player in (('host', host), ('guest', guest)):
x, y, z = spots[label]
cx = x + 3
player('command', command='gamemode survival')
player('command', command=f'fill {cx - 2} {y} {z - 2} {cx + 2} {y + 3} {z + 6} minecraft:air')
player('command', command=f'fill {cx - 2} {y - 1} {z - 2} {cx + 2} {y - 1} {z + 6} minecraft:stone')
player('command', command=f'fill {cx} {y} {z} {cx} {y} {z + 4} minecraft:rail')
player('command', command=f'summon minecraft:minecart {cx + 0.5} {y} {z + 0.5}')
player.wait(30)
try:
cart = board(player, 'minecart', (cx + 0.5, y, z + 0.5))
seated = pos_of(player)
assert abs(seated[0] - (cx + 0.5)) < 0.6, f'the {label} sits at {seated}, not in the cart'
leave_vehicle(player, 'minecart')
out_at = pos_of(player)
assert math.dist(out_at, seated) > 0.3, f'the {label} stayed in its seat at {out_at}'
player.wait(5)
break_vehicle(player, cart['id'], 'minecart')
result[label] = {'cart': cart['id'], 'out_at': [round(v, 2) for v in out_at], 'broken': True}
finally:
player('command', command=f'kill @e[type=minecraft:minecart,x={cx},y={y},z={z},distance=..8]')
player('command', command=f'kill @e[type=minecraft:item,x={cx},y={y},z={z},distance=..8]')
player('command', command=f'fill {cx} {y} {z} {cx} {y} {z + 4} minecraft:air')
player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
player.wait(5)
return result
def check_frames(host, guest, out):
"""#1222: the host and the guest each put a diamond in an item frame and turn it, and put a
helmet on an armor stand and take it back, with right clicks."""
result = {}
spots = apart(host, guest)
for label, player, other in (('host', host, guest), ('guest', guest, host)):
x, y, z = spots[label]
player('command', command='gamemode survival')
# Within a survival player's 3 blocks of reach: a frame on a wall, an armor stand beside it.
player('command', command=f'fill {x - 2} {y} {z + 1} {x + 2} {y + 2} {z + 2} minecraft:air')
player('command', command=f'fill {x - 2} {y} {z + 3} {x + 2} {y + 2} {z + 3} minecraft:stone')
player('command', command=f'summon minecraft:item_frame {x + 0.5} {y + 1.5} {z + 2.97} '
f'{{block_pos:[I;{x},{y + 1},{z + 2}],Facing:2b}}')
player('command', command=f'summon minecraft:armor_stand {x - 1.5} {y} {z + 1.5}')
player('command', command='clear @s')
player('command', command='item replace entity @s weapon.mainhand with minecraft:diamond')
player.wait(30)
try:
frame = [o for o in player('status')['objects'] if o['kind'].endswith('item_frame')
and o['position'] == [x, y + 1, z + 2]]
assert frame, f'the {label} sees no item frame at {[x, y + 1, z + 2]}'
player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 1.5:.2f}', f'{z + 2.95:.2f}')
player.raw('mouse', 'right', 'click')
player.wait(10)
player.raw('mouse', 'right', 'click')
player.wait(10)
frame = [o for o in player('status')['objects'] if o['id'] == frame[0]['id']][0]
assert frame['item'] == 'minecraft:diamond', f'the {label}\'s frame holds {frame["item"]}'
assert frame['rotation'] == 1, f'the {label}\'s frame turned to {frame["rotation"]}'
theirs = [o for o in other('status')['objects'] if o['kind'].endswith('item_frame')
and o['position'] == [x, y + 1, z + 2]]
assert theirs and theirs[0]['item'] == 'minecraft:diamond' and theirs[0]['rotation'] == 1, \
f'the other side sees the {label}\'s frame as {theirs}'
player('command', command='item replace entity @s weapon.mainhand with minecraft:iron_helmet')
player.wait(5)
stand = [o for o in player('status')['objects'] if o['kind'] == 'minecraft:armor_stand'
and abs(o['position'][0] - (x - 1.5)) < 0.5 and abs(o['position'][2] - (z + 1.5)) < 0.5]
assert stand, f'the {label} sees no armor stand'
player.raw('look-at', f'{x - 1.5:.2f}', f'{y + 1.7:.2f}', f'{z + 1.5:.2f}')
player.raw('mouse', 'right', 'click')
player.wait(10)
worn = [o for o in player('status')['objects'] if o['id'] == stand[0]['id']][0]['equipment']
assert 'minecraft:iron_helmet' in worn, f'the {label}\'s armor stand wears {worn}'
player.raw('look-at', f'{x - 1.5:.2f}', f'{y + 1.7:.2f}', f'{z + 1.5:.2f}')
player.raw('mouse', 'right', 'click')
player.wait(10)
worn = [o for o in player('status')['objects'] if o['id'] == stand[0]['id']][0]['equipment']
assert 'minecraft:iron_helmet' not in worn, f'taking the helmet back left {worn}'
result[label] = {'frame': 'diamond, turned', 'stand': 'helmet on and off'}
finally:
player('command', command=f'kill @e[type=!minecraft:player,x={x - 3},y={y - 1},z={z},dx=6,dy=4,dz=6]')
player('command', command=f'fill {x - 2} {y} {z + 3} {x + 2} {y + 2} {z + 3} minecraft:air')
player('command', command='clear @s')
return result
def check_lightning(host, guest, out):
"""A bolt summoned beside each player: both sides get the bolt entity and flash the sky (the
host's window too on its server thread, FEATURES 4z(f))."""
result = {}
for label, player in (('host', host), ('guest', guest)):
x, y, z = (int(v // 1) for v in pos_of(player))
before = {g.name: g('status')['lightning'] for g in (host, guest)}
# No fire where it strikes: on stone with nothing around.
player('command', command=f'fill {x + 4} {y - 1} {z - 2} {x + 8} {y - 1} {z + 2} minecraft:stone')
player('command', command=f'fill {x + 4} {y} {z - 2} {x + 8} {y + 3} {z + 2} minecraft:air')
player('command', command=f'summon minecraft:lightning_bolt {x + 6.5} {y} {z + 0.5}')
seen = {}
for _ in range(40):
player.wait(1)
seen = {g.name: g('status')['lightning'] for g in (host, guest)}
if all(seen[n]['struck'] > before[n]['struck'] and seen[n]['flashes'] > before[n]['flashes']
for n in seen):
break
player('command', command=f'fill {x + 4} {y} {z - 2} {x + 8} {y + 3} {z + 2} minecraft:air')
for n in seen:
assert seen[n]['struck'] > before[n]['struck'], f"{label}'s bolt: the {n} got no bolt ({seen[n]})"
assert seen[n]['flashes'] > before[n]['flashes'], f"{label}'s bolt: the {n}'s sky didn't flash ({seen[n]})"
result[label] = {n: {'bolts': seen[n]['struck'] - before[n]['struck'],
'flashes': seen[n]['flashes'] - before[n]['flashes']} for n in seen}
return result
def check_growth(host, guest, out):
"""Block ticks near a guest 1000 blocks from the host: only the guest's tickets tick them."""
x0, y0, z0 = pos_of(guest)
@@ -2622,7 +2848,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast,
'light': check_light, 'plates': check_plates,
'swings': check_swings, 'cracks': check_cracks,
'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder}
'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning}
def run(ctl, out, resources, checks):
+10
View File
@@ -69,6 +69,16 @@ def cases(count):
'history': rng.sample(HISTORY, rng.randint(0, len(HISTORY))), 'autoSuggest': rng.random() < 0.85,
'chatOnly': rng.random() < 0.7, 'opacity': rng.choice([0.0, 0.5, 1.0]), 'actions': actions,
'mouse': list(mouse), 'blink': rng.choice([0, 100, 400, 650])})
# Always exercise registry-backed suggestions and their replacement ranges,
# before and after Tab, including the redirect through execute's root.
for text in ['/give @s diamond_sw', '/setblock ~ ~ ~ sto', '/fill ~ ~ ~ ~1 ~1 ~1 sto',
'/setblock ~ ~ ~ oak_stairs[fa', '/clear @s diamond_sw',
'/execute run give @s diamond_sw', '/fill ']:
for keys in [[], ['tab'], ['tab', 'tab', 'shift+tab']]:
out.append({'width': 640, 'height': 360, 'initial': '', 'history': [], 'autoSuggest': True,
'chatOnly': True, 'opacity': 0.5, 'mouse': [0, 0], 'blink': 0,
'actions': [{'type': 'type', 'text': text}]
+ [{'type': 'key', 'key': key} for key in keys]})
return out
+2 -1
View File
@@ -67,6 +67,7 @@ if __name__ == '__main__':
'firework-tooltip-parity', 'VanillaFireworkTooltipOracle', 'firework_tooltip_fixture', cases,
'Firework rocket and star tooltip lines: flight duration, explosions (counted runs), colours, fade, trail, '
'twinkle, defaults and tooltip_display',
sources=[lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs',
sources=[lab.ROOT / 'crates/horizon-client/src/enchant.rs',
lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs',
lab.ROOT / 'crates/horizon-client/src/particles.rs'],
expected_lines=COUNT)
+6
View File
@@ -69,6 +69,12 @@ def block_hit(pos, face=1):
def scenarios():
stone = {TARGETS[0]: 'minecraft:stone', TARGETS[1]: 'minecraft:dirt', TARGETS[2]: 'minecraft:glass'}
# Consecutive instant survival breaks have no destroy delay. Cover both
# zero hardness and a shovel with haste reaching one-tick destroy progress.
for block, main, haste in [('minecraft:short_grass', None, None),
('minecraft:dirt', ['minecraft:diamond_shovel', 1], 9)]:
steps = [step(block_hit(p), ac=int(i == 0), ad=True) for i, p in enumerate(TARGETS)]
yield case(steps + [step()] * 6, main=main, blocks={p: block for p in TARGETS}, haste=haste)
for creative in (False, True):
for main in ITEMS:
# Hold attack on blocks until they break, then on the air behind.
+15 -3
View File
@@ -15,6 +15,9 @@ is off: nothing leaves the machine.
python3 tools/test_friends.py --client target/fast/horizon-client --relay target/fast/horizon-relay
`--server-thread` runs the host's world on its integrated server's own
thread (the window is a client of it, as Open to LAN publishes it).
`--role host|guest` runs one side only (two machines, e.g. over a tailnet):
the host prints the code, the guest takes it with `--code` (`--relay-url`
for a relay elsewhere, `--path relay` to force it). Needs a display on Linux
@@ -86,8 +89,12 @@ class Game:
# Extra words before and after the client (`--xvfb`, `--offscreen`).
prefix = []
extra = []
# The host's world on its server thread (`--server-thread`), else in the window.
server_thread = False
def __init__(self, client, resources, work, name, env):
# Either way explicitly, whatever the game's default.
env = dict(env, HORIZON_SERVER_THREAD='1' if Game.server_thread and name == 'host' else '0')
self.home = work / name
self.home.mkdir()
self.endpoint = self.home / 'c.sock'
@@ -155,7 +162,9 @@ def play_together(host, guest, name, round_index):
# The host moves; the guest sees the host's player there.
hp = host('status')['player']['position']
target = [hp[0] + 3.0, hp[1], hp[2] + 1.0]
host(f'tp {target[0]} {target[1]} {target[2]}')
# The /tp command, not the control socket's local move: on the server thread the window is a
# client, and its server has the last word on where the host stands.
host(f'command tp @s {target[0]} {target[1]} {target[2]}')
guest.wait('status', lambda v: any(math.dist(p, target) < 0.6 for p in v['server']['player_positions']), 20,
'host movement on the guest')
# A block the host places, which the guest sees and then breaks.
@@ -163,8 +172,9 @@ def play_together(host, guest, name, round_index):
feet = [math.floor(gp[0]), math.floor(gp[1]), math.floor(gp[2])]
block = [feet[0] + 2, feet[1] + 1, feet[2]]
# Clear the line of sight (the test terrain has hills), then the block at eye level.
host(f'fill {feet[0] + 1} {feet[1]} {feet[2]} {feet[0] + 1} {feet[1] + 2} {feet[2]} minecraft:air')
host(f'setblock {block[0]} {block[1]} {block[2]} minecraft:gold_block')
# As commands, for the same reason as the /tp above.
host(f'command fill {feet[0] + 1} {feet[1]} {feet[2]} {feet[0] + 1} {feet[1] + 2} {feet[2]} minecraft:air')
host(f'command setblock {block[0]} {block[1]} {block[2]} minecraft:gold_block')
guest.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:gold_block', 20,
'the host block on the guest')
eye = [gp[0], gp[1] + 1.62, gp[2]]
@@ -343,10 +353,12 @@ def main():
parser.add_argument('--hold', type=float, default=0, help='guest: stay this many seconds before leaving')
parser.add_argument('--baseline', action='store_true', help='first run the same checks over plain LAN')
parser.add_argument('--offscreen', action='store_true', help='run the games without a window')
parser.add_argument('--server-thread', action='store_true', help="the host's world on its server thread")
parser.add_argument('--xvfb', action='store_true', help='run the games under xvfb-run (headless Linux)')
args = parser.parse_args()
Game.prefix = ['xvfb-run', '-a'] if args.xvfb else []
Game.extra = ['--offscreen'] if args.offscreen else []
Game.server_thread = args.server_thread
args.client, args.resources = args.client.resolve(), args.resources.resolve()
# Short: Unix socket paths are limited to about 100 bytes.
with tempfile.TemporaryDirectory(prefix='hzf-', dir='/tmp') as directory:
+6 -4
View File
@@ -2,10 +2,12 @@
"""Compare selected-slot drops with Minecraft.handleKeybinds in all four game modes.
The oracle invokes the unmodified native key handler, consuming real drop-key
clicks. Its controlled dropItem callback removes from the real player Inventory;
other keys are idle and execution stops at the following item-use boundary.
clicks, and MultiPlayerGameMode.dropItem's real prediction and swing dispatch.
Other keys are idle and execution stops at the following item-use boundary.
Checks Q/Ctrl+Q, slots 0/8, empty/single/partial/full stacks and repeated drops.
Packet delivery, item entities, swing animation and statistics are outside scope.
Checks swing attempts and drop packet counts, including packets without swings
for empty slots. Packet delivery, animation ticks, item entities and statistics
are outside scope.
"""
import os
import subprocess
@@ -35,7 +37,7 @@ def main():
subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example',
'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True)
matched = base.compare(build / 'vanilla.txt', build / 'rust.txt')
print(f'Held drop parity passed: {matched} selected-stack/drop-count snapshots match vanilla')
print(f'Held drop parity passed: {matched} inventory/drop/swing/packet snapshots match vanilla')
if __name__ == '__main__':
+17 -1
View File
@@ -68,6 +68,22 @@ def generate(resources, count, seed):
return cases
def obstruction_cases(resources):
"""Placement failures must not predict a hand swing.
Exercise BlockItem.canPlace's entity-obstruction gate with the same
otherwise valid placements, including partial shapes and two-block items.
"""
facts = json.loads((resources / 'facts.json').read_text())
states = {s[0]: i for i, s in reversed(list(enumerate(facts['states'])))}
stone = states['minecraft:stone']
for item in ['minecraft:stone', 'minecraft:oak_slab', 'minecraft:oak_stairs',
'minecraft:oak_door', 'minecraft:torch']:
for obstructed in [False, True]:
yield dict(seed=0, item=item, pos=[0, 0, 0], face=1, hit=[0.5, 1.0, 0.5],
yaw=0, pitch=45, sneak=False, cells=[[0, 0, 0, stone]], obstructed=obstructed)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=20000)
@@ -77,7 +93,7 @@ def main():
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'level-place-parity'
work.mkdir(parents=True, exist_ok=True)
cases = generate(resources, args.count, args.seed)
cases = list(obstruction_cases(resources)) + generate(resources, args.count, args.seed)
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
+2 -2
View File
@@ -12,8 +12,8 @@ def make_input(build):
rng = random.Random(71)
cases = []
for kind in (0, 1):
for ticks in (0, 1, 511, 512, 131071, 131072, 24000 * 37 + 5, 9_000_000_123):
for x, z in ((0, 0), (1, 0), (0, -1), (3, 7), (-10, 10), (10, -10), (-4, -9), (1_000_003, -2_000_011)):
for ticks in (-9223372036854775808, -1, 0, 1, 511, 512, 131071, 131072, 24000 * 37 + 5, 9_000_000_123, 9223372036854775807):
for x, z in ((0, 0), (1, 0), (0, -1), (3, 7), (-10, 10), (10, -10), (-4, -9), (1_000_003, -2_000_011), (30_000_000, -30_000_000), (2_147_483_631, -2_147_483_632)):
for bottom, top in ((60, 80), (64, 65), (-64, -44), (300, 310)):
light = (rng.randrange(16) << 4) | (rng.randrange(16) << 20)
partial = rng.choice(("0.0", "0.5", "0.999", f"{rng.random():.6f}"))