Merge remote-tracking branch 'origin/main' into feat/java-packs-photon-chocapic
This commit is contained in:
@@ -0,0 +1 @@
|
||||
0.2
|
||||
@@ -18,6 +18,10 @@ concurrency:
|
||||
# A new push to a pull request replaces its running checks; main's runs all finish (releases follow them).
|
||||
group: checks-${{ github.event.pull_request.number || github.sha }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
env:
|
||||
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
|
||||
HORIZON_TELEMETRY_URL: "off"
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -49,6 +49,10 @@ concurrency:
|
||||
group: launcher-${{ github.ref == 'refs/heads/main' && 'release' || github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
|
||||
HORIZON_TELEMETRY_URL: "off"
|
||||
|
||||
jobs:
|
||||
decide:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -188,9 +192,6 @@ jobs:
|
||||
retry "$launcher" install latest
|
||||
"$launcher" versions --installed
|
||||
"$launcher" links --json
|
||||
"$launcher" menu-style classic
|
||||
grep -qx 'menuStyle:classic' "$HORIZON_HOME/horizon.txt"
|
||||
"$launcher" menu-style horizon
|
||||
clients=("$HORIZON_LAUNCHER_HOME"/versions/v*/horizon-client*)
|
||||
client="${clients[0]}"
|
||||
echo "installed client: $client"
|
||||
|
||||
@@ -23,6 +23,10 @@ permissions:
|
||||
concurrency:
|
||||
group: nightly-audit
|
||||
cancel-in-progress: false
|
||||
env:
|
||||
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
|
||||
HORIZON_TELEMETRY_URL: "off"
|
||||
|
||||
jobs:
|
||||
audit:
|
||||
runs-on: [self-hosted, horizon-game]
|
||||
|
||||
@@ -15,6 +15,10 @@ on:
|
||||
required: true
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
|
||||
HORIZON_TELEMETRY_URL: "off"
|
||||
|
||||
jobs:
|
||||
parity:
|
||||
runs-on: [self-hosted, horizon-game]
|
||||
|
||||
@@ -11,6 +11,10 @@ permissions:
|
||||
concurrency:
|
||||
group: run-parity-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
|
||||
HORIZON_TELEMETRY_URL: "off"
|
||||
|
||||
jobs:
|
||||
parity:
|
||||
if: github.event.label.name == 'run-parity'
|
||||
|
||||
Generated
+1
@@ -1395,6 +1395,7 @@ dependencies = [
|
||||
name = "horizon-bench"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-telemetry",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -46,7 +46,7 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these.
|
||||
- **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status).
|
||||
- **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings).
|
||||
- **Resource packs, shader packs and data packs:** resource packs work, Java shader packs run their full-screen effects (experimental), and data packs load functions, predicates and item modifiers.
|
||||
- **Playing with others:** invite friends from the pause menu with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
|
||||
- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
|
||||
- **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods).
|
||||
|
||||
Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders:
|
||||
@@ -56,8 +56,8 @@ Screenshots, captured in the Rust client itself with vanilla assets and no mods
|
||||
<td colspan="2"><img src="docs/media/sunset.webp" alt="Sunset over a savanna river valley and a plains village"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/menu-title.webp" alt="Horizon's title screen over a veiled snowy landscape"></td>
|
||||
<td width="50%"><img src="docs/media/settings.webp" alt="The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs"></td>
|
||||
<td width="50%"><img src="docs/media/survival.webp" alt="Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience"></td>
|
||||
<td width="50%"><img src="docs/media/settings.webp" alt="Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/village.webp" alt="A plains village among savanna hills, with farms, villagers and an iron golem"></td>
|
||||
|
||||
@@ -36,3 +36,15 @@ SOFTWARE.
|
||||
developers, with one upstream fix applied
|
||||
([gfx-rs/wgpu#10124](https://github.com/gfx-rs/wgpu/pull/10124)). It is licensed under MIT or
|
||||
Apache-2.0; both licenses are in that folder (`LICENSE.MIT`, `LICENSE.APACHE`).
|
||||
|
||||
## Pixelify Sans
|
||||
|
||||
`crates/horizon-theme/fonts/PixelifySans-*.ttf` is [Pixelify Sans](https://github.com/eifetx/Pixelify-Sans)
|
||||
by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1.1
|
||||
(`crates/horizon-theme/fonts/OFL-PixelifySans.txt`).
|
||||
|
||||
## Pixelarticons
|
||||
|
||||
`crates/horizon-theme/icons/pixel/*.svg` are icons from
|
||||
[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT
|
||||
license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`).
|
||||
|
||||
@@ -8,3 +8,5 @@ description = "The benchmark report format (docs/benchmark-report.md), shared by
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
# The hardware probes shared with telemetry (cores, clocks, drive, VRAM, power, form).
|
||||
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
|
||||
|
||||
@@ -16,8 +16,22 @@ pub struct Hardware {
|
||||
pub cpu: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cpu_threads: Option<usize>,
|
||||
/// Physical cores.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cpu_cores: Option<u16>,
|
||||
/// Base and top boost clock, where the OS gives them.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cpu_base_mhz: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cpu_boost_mhz: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ram_mb: Option<u64>,
|
||||
/// The drive under the game folder: `nvme`, `ssd` or `hdd`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub storage: Option<String>,
|
||||
/// `laptop` or `desktop`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub form: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub gpu: Option<Gpu>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -33,6 +47,9 @@ pub struct Gpu {
|
||||
pub backend: String,
|
||||
/// `integrated`, `discrete`, `virtual`, `cpu`, `other`.
|
||||
pub kind: String,
|
||||
/// Its own memory in MiB (rounded to 256), for a discrete GPU whose driver says.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub vram_mb: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -47,17 +64,50 @@ pub struct Display {
|
||||
|
||||
impl Hardware {
|
||||
pub fn detect() -> Hardware {
|
||||
let probes = probes();
|
||||
Hardware {
|
||||
os: std::env::consts::OS.to_owned(),
|
||||
os_version: os_version(),
|
||||
arch: std::env::consts::ARCH.to_owned(),
|
||||
cpu: cpu(),
|
||||
cpu_threads: std::thread::available_parallelism().ok().map(|n| n.get()),
|
||||
cpu_cores: probes.cores,
|
||||
cpu_base_mhz: probes.base,
|
||||
cpu_boost_mhz: probes.boost,
|
||||
ram_mb: ram_bytes().map(|b| b >> 20),
|
||||
storage: None,
|
||||
form: probes.form,
|
||||
gpu: None,
|
||||
display: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Hardware::detect`] with the kind of drive `game_dir` is on.
|
||||
pub fn detect_in(game_dir: &std::path::Path) -> Hardware {
|
||||
Hardware {
|
||||
storage: horizon_telemetry::system::storage(game_dir).map(str::to_owned),
|
||||
..Hardware::detect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the telemetry probes read (`horizon_telemetry::system`).
|
||||
struct Probes {
|
||||
cores: Option<u16>,
|
||||
base: Option<u32>,
|
||||
boost: Option<u32>,
|
||||
form: Option<String>,
|
||||
}
|
||||
|
||||
fn probes() -> Probes {
|
||||
let s = horizon_telemetry::payload::System::detect();
|
||||
let some = |n: u32| (n > 0).then_some(n);
|
||||
Probes {
|
||||
cores: (s.cores > 0).then_some(s.cores),
|
||||
base: some(s.cpu_base_mhz),
|
||||
boost: some(s.cpu_boost_mhz),
|
||||
form: (!s.form.is_empty()).then_some(s.form),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one-minute load average: above about the number of threads the machine was busy.
|
||||
@@ -82,25 +132,7 @@ pub fn load_average() -> Option<f64> {
|
||||
|
||||
/// `ac` or `battery`; `None` where it can't be read (and on machines without a battery on Linux).
|
||||
pub fn power_source() -> Option<&'static str> {
|
||||
if cfg!(target_os = "macos") {
|
||||
let batt = output("pmset", &["-g", "batt"])?;
|
||||
return Some(if batt.contains("'Battery Power'") {
|
||||
"battery"
|
||||
} else {
|
||||
"ac"
|
||||
});
|
||||
}
|
||||
let mut on_battery = None;
|
||||
for entry in std::fs::read_dir("/sys/class/power_supply").ok()?.flatten() {
|
||||
let read =
|
||||
|name: &str| std::fs::read_to_string(entry.path().join(name)).unwrap_or_default();
|
||||
match read("type").trim() {
|
||||
"Mains" if read("online").trim() == "1" => return Some("ac"),
|
||||
"Battery" => on_battery = Some("battery"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
on_battery
|
||||
horizon_telemetry::system::power()
|
||||
}
|
||||
|
||||
/// Resident memory of a process, in bytes (macOS, Linux).
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1133,7 +1133,7 @@ fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
#[allow(unused_mut)] // filled only with the rng-trace feature
|
||||
let mut traces: Vec<String> = Vec::new();
|
||||
let mut pushes = Vec::new();
|
||||
let mut pushes = horizon_client::mobs::PendingPushes::default();
|
||||
let mut born = Vec::new();
|
||||
for i in 0..mobs.len() {
|
||||
if mobs[i].removed {
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -140,7 +140,22 @@ fn run(control: &Control, setup: Setup) -> Result<PathBuf, String> {
|
||||
driver: text(&renderer["driver"]),
|
||||
backend: text(&renderer["backend"]).to_lowercase(),
|
||||
kind: text(&renderer["device_type"]),
|
||||
vram_mb: None,
|
||||
});
|
||||
if let Some(gpu) = report.hardware.gpu.as_mut() {
|
||||
let vendor = horizon_telemetry::system::gpu_vendor(&gpu.name, 0);
|
||||
let vendor = if gpu.vendor.is_empty() {
|
||||
vendor
|
||||
} else {
|
||||
gpu.vendor.as_str()
|
||||
}
|
||||
.to_owned();
|
||||
if gpu.kind.contains("iscrete") {
|
||||
gpu.vram_mb = horizon_telemetry::system::vram_mb(&vendor);
|
||||
}
|
||||
}
|
||||
report.hardware.storage =
|
||||
horizon_telemetry::system::storage(&setup.game_dir).map(str::to_owned);
|
||||
report.hardware.display = serde_json::from_value(title["display"].clone()).ok();
|
||||
|
||||
replace_world(&setup.game_dir)?;
|
||||
@@ -224,6 +239,10 @@ fn run(control: &Control, setup: Setup) -> Result<PathBuf, String> {
|
||||
|
||||
let status = control.status();
|
||||
let renderer = &status["renderer"];
|
||||
// On Wayland the window is on a screen only once it has been shown: ask again.
|
||||
if report.hardware.display.is_none() {
|
||||
report.hardware.display = serde_json::from_value(status["display"].clone()).ok();
|
||||
}
|
||||
let c = &mut report.conditions;
|
||||
c.scenario = Some(setup.scenario.clone());
|
||||
c.seed = Some(SEED.to_string());
|
||||
|
||||
@@ -32,16 +32,18 @@ pub enum Group {
|
||||
Move,
|
||||
Act,
|
||||
Screens,
|
||||
Multiplayer,
|
||||
World,
|
||||
Scripting,
|
||||
}
|
||||
impl Group {
|
||||
pub const ALL: [Group; 7] = [
|
||||
pub const ALL: [Group; 8] = [
|
||||
Group::Session,
|
||||
Group::Observe,
|
||||
Group::Move,
|
||||
Group::Act,
|
||||
Group::Screens,
|
||||
Group::Multiplayer,
|
||||
Group::World,
|
||||
Group::Scripting,
|
||||
];
|
||||
@@ -52,6 +54,7 @@ impl Group {
|
||||
Group::Move => "Move and look",
|
||||
Group::Act => "Act on the world",
|
||||
Group::Screens => "Screens, menus and chat",
|
||||
Group::Multiplayer => "Multiplayer, LAN and friends",
|
||||
Group::World => "World and cheats",
|
||||
Group::Scripting => "Scripting and benchmarks",
|
||||
}
|
||||
@@ -117,6 +120,50 @@ const OVER: Param = flag(
|
||||
"turn with mouse motion spread over this many seconds (eased), as a player would",
|
||||
);
|
||||
const FACE: Ty = Ty::Enum(&["down", "up", "north", "south", "west", "east"]);
|
||||
const BOX: [Param; 6] = [
|
||||
p("x1", Ty::Int, "corner X"),
|
||||
p("y1", Ty::Int, "corner Y"),
|
||||
p("z1", Ty::Int, "corner Z"),
|
||||
p("x2", Ty::Int, "opposite X"),
|
||||
p("y2", Ty::Int, "opposite Y"),
|
||||
p("z2", Ty::Int, "opposite Z"),
|
||||
];
|
||||
const PAGES: Ty = Ty::Enum(&[
|
||||
"main",
|
||||
"video",
|
||||
"sound",
|
||||
"controls",
|
||||
"keybinds",
|
||||
"controller",
|
||||
"controller-binds",
|
||||
"mouse",
|
||||
"chat",
|
||||
"accessibility",
|
||||
"language",
|
||||
"font",
|
||||
"packs",
|
||||
"mods",
|
||||
"graphics",
|
||||
"graphics-advanced",
|
||||
"extras",
|
||||
"horizon",
|
||||
"shader-packs",
|
||||
"agent",
|
||||
]);
|
||||
|
||||
/// `--confirm`, required by destructive commands: the player agreed.
|
||||
const CONFIRM: Param = Param {
|
||||
name: "confirm",
|
||||
ty: Ty::Bool,
|
||||
required: true,
|
||||
flag: true,
|
||||
help: "true once the player agreed: it cannot be undone",
|
||||
};
|
||||
|
||||
/// MCP tools that delete or overwrite the player's things (`destructiveHint`).
|
||||
pub const DESTRUCTIVE: &[&str] = &["world-delete", "fill", "setblock"];
|
||||
/// MCP tools that reach other players or the network (`openWorldHint`): only when the player asks.
|
||||
pub const OPEN_WORLD: &[&str] = &["connect", "lan", "friends", "chat", "command"];
|
||||
|
||||
macro_rules! cmd {
|
||||
($name:expr, $group:ident, $usage:expr, $summary:expr, $details:expr, [$($ex:expr),* $(,)?], $params:expr, mcp: $mcp:expr, local: $local:expr $(, wire: $wire:expr)?) => {
|
||||
@@ -164,7 +211,19 @@ pub const COMMANDS: &[Cmd] = &[
|
||||
&[flag("lines", Ty::Int, "how many lines of latest.log (default 100)"), flag("crash", Ty::Bool, "the newest crash report instead")],
|
||||
mcp: true, local: true),
|
||||
cmd!("status", Session, "status", "game, renderer and streaming state (the scripting socket's original summary)",
|
||||
"", ["horizon-ctl status"], &[], mcp: false, local: false),
|
||||
"Also what F3 shows: the overlay flags, the renderer, chunk streaming and memory.", ["horizon-ctl status"], &[], mcp: true, local: false),
|
||||
cmd!("worlds", Session, "worlds", "the saved worlds, newest first: folder, name, mode, last played, version",
|
||||
"folder is what open, world-rename, world-backup and world-delete take.", ["horizon-ctl worlds"], &[], mcp: true, local: false),
|
||||
cmd!("world-rename", Session, "world-rename FOLDER NAME", "rename a world, as Edit World does (its folder stays)",
|
||||
"Needs the title screen (no world open).", ["horizon-ctl world-rename Test \"My Base\""],
|
||||
&[p("folder", Ty::Str, "world folder from worlds"), p("name", Ty::Rest, "the new name")], mcp: true, local: false),
|
||||
cmd!("world-backup", Session, "world-backup FOLDER", "zip a world into backups/, as Edit World's Make Backup does",
|
||||
"Needs the title screen. Replies once the zip is written, with its size.", ["horizon-ctl world-backup Test"],
|
||||
&[p("folder", Ty::Str, "world folder from worlds")], mcp: true, local: false),
|
||||
cmd!("world-delete", Session, "world-delete FOLDER --confirm", "delete a world for good, as Select World's Delete does",
|
||||
"Needs the title screen and --confirm: ask the player first, it cannot be undone (world-backup keeps a copy).",
|
||||
["horizon-ctl world-delete Test --confirm"],
|
||||
&[p("folder", Ty::Str, "world folder from worlds"), CONFIRM], mcp: true, local: false),
|
||||
cmd!("open", Session, "open WORLD [SEED] [creative]", "open or create a world from the title screen",
|
||||
"Opens saves/WORLD, creating it with SEED (and creative mode) when it doesn't exist.",
|
||||
["horizon-ctl open Test 12345", "horizon-ctl open Build 0 creative"],
|
||||
@@ -190,10 +249,10 @@ pub const COMMANDS: &[Cmd] = &[
|
||||
cmd!("light", Observe, "light X1 Y1 Z1 X2 Y2 Z2", "the stored sky and block light of a box",
|
||||
"At most 32768 blocks per request. One hex digit per block in `sky` and `block`, x fastest, then z, then y; `.` where no chunk is loaded.",
|
||||
["horizon-ctl light 0 64 0 15 70 15"],
|
||||
&[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false),
|
||||
&BOX, mcp: true, local: false),
|
||||
cmd!("blocks", Observe, "blocks X1 Y1 Z1 X2 Y2 Z2", "the non-air blocks of a box, with counts per block",
|
||||
"At most 32768 blocks per request.", ["horizon-ctl blocks 0 60 0 15 70 15"],
|
||||
&[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false),
|
||||
&BOX, mcp: true, local: false),
|
||||
cmd!("find-block", Observe, "find-block BLOCK [RADIUS]", "the nearest loaded blocks of a kind",
|
||||
"Searches a cube of RADIUS (default 32, at most 64) around the player; returns the count and the 16 nearest.",
|
||||
["horizon-ctl find-block oak_log", "horizon-ctl find-block diamond_ore 48"],
|
||||
@@ -264,12 +323,15 @@ pub const COMMANDS: &[Cmd] = &[
|
||||
"down holds the key until key ... up, release or stop; wait does not release it. move, goto, jump, break and the other actions release the movement keys when they end.",
|
||||
["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap", "repeat"]), "what to do")], mcp: true, local: false),
|
||||
cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "",
|
||||
["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false),
|
||||
["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: true, local: false),
|
||||
cmd!("interact-entity", Act, "interact-entity ID", "right-click an entity: trade with a villager, mount a horse, ride a boat, shear a sheep",
|
||||
"Faces the entity (from entities), right-clicks it with the held item, waits two ticks and replies with the screen.",
|
||||
["horizon-ctl interact-entity 42"], &[p("id", Ty::Int, "entity id from entities")], mcp: true, local: true),
|
||||
cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them",
|
||||
"Buttons by position: south east west north lb rb lt rt select start ls rs up down left right (south is Xbox A / PlayStation cross). Sticks run -1..1 with up positive and stay tilted until centred; triggers 0..1. Merged with any real controller; status lists the connected ones and what is held.",
|
||||
["horizon-ctl pad south tap", "horizon-ctl pad stick left 0 1", "horizon-ctl pad trigger right 1", "horizon-ctl pad status"],
|
||||
&[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: false, local: false),
|
||||
cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false),
|
||||
&[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: true, local: false),
|
||||
cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: true, local: false),
|
||||
cmd!("stop", Act, "stop", "cancel the running action (goto, break...) and release every key", "", ["horizon-ctl stop"], &[], mcp: true, local: false),
|
||||
// Screens
|
||||
cmd!("open-inventory", Screens, "open-inventory", "open the inventory screen (crafting grid 100-103, result 200)", "",
|
||||
@@ -317,7 +379,31 @@ pub const COMMANDS: &[Cmd] = &[
|
||||
cmd!("respawn", Screens, "respawn", "respawn from the death screen", "", ["horizon-ctl respawn"], &[], mcp: true, local: false),
|
||||
cmd!("pause", Screens, "pause", "open the pause menu", "", ["horizon-ctl pause"], &[], mcp: true, local: false),
|
||||
cmd!("resume", Screens, "resume", "leave the pause menu", "", ["horizon-ctl resume"], &[], mcp: true, local: false),
|
||||
cmd!("options", Screens, "options [PAGE]", "open the options screen, or one of its pages (Horizon's too)",
|
||||
"Then ui lists its widgets and click, set and type change them, as with the mouse. options-set changes an options.txt value without the screen.",
|
||||
["horizon-ctl options video", "horizon-ctl options horizon"], &[opt("page", PAGES, "the page (default: the main options)")], mcp: true, local: false),
|
||||
cmd!("book", Screens, "book [next|back|take|done]", "the open book or lectern: its page text, or press one of its buttons",
|
||||
"", ["horizon-ctl book", "horizon-ctl book next"], &[opt("action", Ty::Enum(&["next", "back", "take", "done"]), "a button to press")], mcp: true, local: false),
|
||||
cmd!("signedit", Screens, "signedit X Y Z [front|back]", "open the sign editor of the sign at X Y Z (then type and close)",
|
||||
"", ["horizon-ctl signedit 3 64 1"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("side", Ty::Enum(&["front", "back"]), "which side")], mcp: true, local: false),
|
||||
cmd!("mount-menu", Screens, "mount-menu", "open the inventory of the horse, donkey, mule or llama being ridden",
|
||||
"As the inventory key does while riding; also opens the nearest one's.", ["horizon-ctl mount-menu"], &[], mcp: true, local: false),
|
||||
cmd!("chat-log", Screens, "chat-log [N]", "the newest N chat messages", "", ["horizon-ctl chat-log 5"], &[], mcp: false, local: false),
|
||||
// Multiplayer
|
||||
cmd!("connect", Multiplayer, "connect ADDRESS [NAME]", "join a multiplayer server, or a friend's world by its invite code, from the title screen",
|
||||
"ADDRESS is HOST[:PORT], or friend:CODE for an invite code. Only when the player asks: it reaches the network.",
|
||||
["horizon-ctl connect play.example.net", "horizon-ctl connect localhost:25565", "horizon-ctl connect friend:0B33K-Q405Q-..."],
|
||||
&[p("address", Ty::Str, "HOST[:PORT] or friend:CODE"), opt("name", Ty::Str, "player name when offline")], mcp: true, local: false),
|
||||
cmd!("disconnect", Multiplayer, "disconnect", "leave the server, back to the server list", "", ["horizon-ctl disconnect"], &[], mcp: true, local: false),
|
||||
cmd!("servers", Multiplayer, "servers", "the Multiplayer screen's server list: name and address",
|
||||
"Add, edit and remove them on the Multiplayer screen (click-button Multiplayer, then ui).", ["horizon-ctl servers"], &[], mcp: true, local: false),
|
||||
cmd!("lan", Multiplayer, "lan open [PORT] [commands] [force] | lan close | lan status", "open the world to LAN (Open to LAN), stop, or see the guests",
|
||||
"PORT 0 or none picks one; commands lets guests use cheats; force forces the game mode. Only when the player asks.",
|
||||
["horizon-ctl lan open", "horizon-ctl lan status", "horizon-ctl lan close"],
|
||||
&[p("action", Ty::Enum(&["open", "close", "status"]), "what to do"), opt("port", Ty::Int, "port for open"), opt("commands", Ty::Bool, "allow cheats"), opt("force", Ty::Bool, "force the game mode")], mcp: true, local: false),
|
||||
cmd!("friends", Multiplayer, "friends host|stop|status", "Play with Friends: share the open world behind an invite code, stop, or see who joined",
|
||||
"status gives the code: share it only when the player asks. Friends join with connect friend:CODE.",
|
||||
["horizon-ctl friends host", "horizon-ctl friends status"], &[p("action", Ty::Enum(&["host", "stop", "status"]), "what to do")], mcp: true, local: false),
|
||||
// World
|
||||
cmd!("give", World, "give ITEM [COUNT]", "add items to the inventory", "", ["horizon-ctl give oak_log 16"],
|
||||
&[p("item", Ty::Str, "item id"), opt("count", Ty::Int, "how many (default 1)")], mcp: true, local: false),
|
||||
@@ -325,8 +411,20 @@ pub const COMMANDS: &[Cmd] = &[
|
||||
&[p("ticks", Ty::Int, "day time")], mcp: true, local: false),
|
||||
cmd!("setblock", World, "setblock X Y Z BLOCK[props]", "set a block (with neighbour updates)", "", ["horizon-ctl setblock 0 64 0 stone"],
|
||||
&[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], p("block", Ty::Str, "block state such as oak_stairs[facing=east]")], mcp: true, local: false),
|
||||
cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob", "", ["horizon-ctl summon cow"], &[p("kind", Ty::Str, "mob type")], mcp: true, local: false),
|
||||
cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect", "", ["horizon-ctl effect speed 30 1"], &[], mcp: false, local: false),
|
||||
cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob (in front of the player without a position)", "Replies with its id.", ["horizon-ctl summon cow", "horizon-ctl summon pig 10 64 3 baby"],
|
||||
&[p("kind", Ty::Str, "mob type"), opt("x", Ty::Num, "X"), opt("y", Ty::Num, "Y"), opt("z", Ty::Num, "Z"), opt("baby", Ty::Bool, "a baby")], mcp: true, local: false),
|
||||
cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect, or clear them all", "", ["horizon-ctl effect speed 30 1", "horizon-ctl effect clear"],
|
||||
&[p("id", Ty::Str, "effect id such as speed, or clear"), opt("seconds", Ty::Num, "duration"), opt("amplifier", Ty::Int, "level - 1 (default 0)")], mcp: true, local: false),
|
||||
cmd!("effects", World, "effects", "the player's active status effects", "", ["horizon-ctl effects"], &[], mcp: true, local: false),
|
||||
cmd!("xp", World, "xp LEVELS", "add experience levels (negative removes)", "", ["horizon-ctl xp 30"], &[p("levels", Ty::Int, "levels to add")], mcp: true, local: false),
|
||||
cmd!("enchant", World, "enchant ID LEVEL", "enchant the held item (a book stores it)", "", ["horizon-ctl enchant sharpness 5"],
|
||||
&[p("id", Ty::Str, "enchantment id"), p("level", Ty::Int, "level")], mcp: true, local: false),
|
||||
cmd!("potion", World, "potion ITEM POTION", "give a potion item", "", ["horizon-ctl potion splash_potion healing"],
|
||||
&[p("item", Ty::Enum(&["potion", "splash_potion", "lingering_potion", "tipped_arrow"]), "which item"), p("potion", Ty::Str, "potion id")], mcp: true, local: false),
|
||||
cmd!("fill", World, "fill X1 Y1 Z1 X2 Y2 Z2 BLOCK", "set a box of loaded blocks", "", ["horizon-ctl fill 0 64 0 4 64 4 glass"],
|
||||
&[BOX[0], BOX[1], BOX[2], BOX[3], BOX[4], BOX[5], p("block", Ty::Str, "block state")], mcp: true, local: false),
|
||||
cmd!("container", World, "container X Y Z [ITEM COUNT]", "list a container's items, or add items to it", "", ["horizon-ctl container 3 64 1", "horizon-ctl container 3 64 1 diamond 3"],
|
||||
&[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("item", Ty::Str, "item to add"), opt("count", Ty::Int, "how many")], mcp: true, local: false),
|
||||
cmd!("render-distance", World, "render-distance N", "chunks, 2..64", "", ["horizon-ctl render-distance 8"], &[p("chunks", Ty::Int, "render distance")], mcp: false, local: false),
|
||||
cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)",
|
||||
"Keys and mouse buttons held with key ... down or mouse ... down stay held while it waits. Release them with key ... up, release or stop.",
|
||||
@@ -340,8 +438,8 @@ pub const COMMANDS: &[Cmd] = &[
|
||||
cmd!("mcp", Scripting, "mcp", "serve the Model Context Protocol on stdin/stdout, one tool per command",
|
||||
"Add it to an MCP client as a stdio server: command horizon-ctl, args [\"mcp\"] (with --socket PATH first if needed). The screenshot tool returns the image.",
|
||||
["horizon-ctl mcp"], &[], mcp: false, local: true),
|
||||
cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false),
|
||||
cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false),
|
||||
cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[p("seconds", Ty::Num, "how long to measure")], mcp: true, local: false),
|
||||
cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[opt("reset", Ty::Bool, "start counting again")], mcp: true, local: false),
|
||||
cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary",
|
||||
"The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).",
|
||||
["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false),
|
||||
@@ -366,8 +464,9 @@ pub fn overview() -> String {
|
||||
}
|
||||
out.push_str(
|
||||
"\nEvery reply is one JSON line. Errors are {\"error\": \"...\"}; the exit status is 0 on\n\
|
||||
success, 1 when the game replied with an error, 2 for a usage error and 3 when the\n\
|
||||
game cannot be reached or started. Actions (goto, break, place...) block until done.\n\
|
||||
success, 1 when the game replied with an error, 2 for a usage error, 3 when the\n\
|
||||
game cannot be reached or started and 4 while No AI is on (the launcher's settings).\n\
|
||||
Actions (goto, break, place...) block until done.\n\
|
||||
horizon-ctl help --game lists the running game's own commands, test hooks included.\n\
|
||||
The socket is $HORIZON_CONTROL, else $XDG_RUNTIME_DIR/horizon-control.sock (on Windows\n\
|
||||
%TEMP%\\horizon-control.json, a localhost TCP port with a token; any path ending in .json\n\
|
||||
@@ -402,6 +501,73 @@ pub fn detail(c: &Cmd) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The generated reference, docs/horizon-ctl-commands.md (`horizon-ctl help --markdown`).
|
||||
pub fn markdown() -> String {
|
||||
let cell = |s: &str| s.replace('|', "\\|");
|
||||
let mut out = String::from(
|
||||
"<!-- Generated by `horizon-ctl help --markdown` from the command table in \
|
||||
crates/horizon-client/src/bin/horizon-ctl/commands.rs: edit the table, then regenerate. -->\n\
|
||||
# horizon-ctl commands\n\n\
|
||||
Every command `horizon-ctl` takes, its MCP tool in `horizon-ctl mcp` (the launcher's \
|
||||
`horizon-launcher mcp` offers the same tools as `game_<tool>`, all but `launch`) and its \
|
||||
arguments. Positional arguments come first, in order; `--flags` after them. \
|
||||
`horizon-ctl help --game` lists the game's own commands, test hooks included. \
|
||||
Design rules and the full inventory: [agent-control.md](agent-control.md).\n",
|
||||
);
|
||||
for group in Group::ALL {
|
||||
out.push_str(&format!(
|
||||
"\n## {}\n\n| Command | MCP tool | What it does | Arguments |\n| --- | --- | --- | --- |\n",
|
||||
group.title()
|
||||
));
|
||||
for c in COMMANDS.iter().filter(|c| c.group == group) {
|
||||
let tool = if c.mcp {
|
||||
let mut t = format!("`{}`", tool_name(c));
|
||||
if DESTRUCTIVE.contains(&c.name) {
|
||||
t.push_str(" (destructive)");
|
||||
} else if OPEN_WORLD.contains(&c.name) {
|
||||
t.push_str(" (network)");
|
||||
}
|
||||
t
|
||||
} else {
|
||||
"CLI only".to_owned()
|
||||
};
|
||||
let args: Vec<String> = c
|
||||
.params
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let ty = match p.ty {
|
||||
Ty::Int => "integer".to_owned(),
|
||||
Ty::Num => "number".to_owned(),
|
||||
Ty::Str => "string".to_owned(),
|
||||
Ty::Rest => "text".to_owned(),
|
||||
Ty::Bool => "boolean".to_owned(),
|
||||
Ty::Enum(v) => v.join(", "),
|
||||
};
|
||||
let name = if p.flag {
|
||||
format!("--{}", p.name)
|
||||
} else {
|
||||
p.name.to_owned()
|
||||
};
|
||||
let need = if p.required { ", required" } else { "" };
|
||||
format!("`{name}` ({ty}{need}): {}", cell(p.help))
|
||||
})
|
||||
.collect();
|
||||
out.push_str(&format!(
|
||||
"| `{}` | {} | {} | {} |\n",
|
||||
cell(c.usage),
|
||||
tool,
|
||||
cell(&capitalize(c.summary)),
|
||||
if args.is_empty() {
|
||||
"none".to_owned()
|
||||
} else {
|
||||
args.join("<br>")
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn capitalize(s: &str) -> String {
|
||||
let mut chars = s.chars();
|
||||
chars
|
||||
@@ -640,6 +806,43 @@ mod tests {
|
||||
assert_eq!(tool_name(find("look-at-entity").unwrap()), "look_at_entity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_generated_reference_is_up_to_date() {
|
||||
let path = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../docs/horizon-ctl-commands.md"
|
||||
);
|
||||
let on_disk = std::fs::read_to_string(path).unwrap_or_default();
|
||||
assert!(
|
||||
on_disk == markdown(),
|
||||
"docs/horizon-ctl-commands.md is out of date: run `horizon-ctl help --markdown > docs/horizon-ctl-commands.md`"
|
||||
);
|
||||
for c in COMMANDS {
|
||||
assert!(
|
||||
on_disk.contains(&format!("`{}", c.usage.replace('|', "\\|"))),
|
||||
"{} undocumented",
|
||||
c.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destructive_and_network_tools_exist() {
|
||||
for name in DESTRUCTIVE.iter().chain(OPEN_WORLD) {
|
||||
assert!(find(name).is_some_and(|c| c.mcp), "{name}");
|
||||
}
|
||||
let delete = find("world-delete").unwrap();
|
||||
assert_eq!(
|
||||
line_for(delete, &json!({ "folder": "A", "confirm": true })).unwrap(),
|
||||
["world-delete", "A", "--confirm"]
|
||||
);
|
||||
let lan = find("lan").unwrap();
|
||||
assert_eq!(
|
||||
line_for(lan, &json!({ "action": "open", "commands": true })).unwrap(),
|
||||
["lan", "open", "commands"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_mentions_every_command() {
|
||||
let text = overview();
|
||||
|
||||
@@ -20,6 +20,8 @@ use serde_json::{Value, json};
|
||||
const GAME_ERROR: u8 = 1;
|
||||
const USAGE: u8 = 2;
|
||||
const UNREACHABLE: u8 = 3;
|
||||
/// No AI is on (`horizon_core::no_ai`): agent control is off.
|
||||
const DENIED: u8 = 4;
|
||||
|
||||
/// A failure, with the exit status it maps to.
|
||||
#[derive(Debug)]
|
||||
@@ -34,6 +36,13 @@ impl Failure {
|
||||
status: USAGE,
|
||||
}
|
||||
}
|
||||
/// No AI is on in the game's home.
|
||||
fn denied() -> Self {
|
||||
Self {
|
||||
reply: json!({ "error": horizon_core::no_ai::REFUSAL, "kind": "denied" }),
|
||||
status: DENIED,
|
||||
}
|
||||
}
|
||||
fn unreachable(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
reply: json!({ "error": message.into(), "kind": "connection" }),
|
||||
@@ -98,6 +107,8 @@ impl Client {
|
||||
pub struct Session {
|
||||
pub socket: PathBuf,
|
||||
pub timeout: Option<Duration>,
|
||||
/// The game's home, where No AI is read (`horizon_core::no_ai`).
|
||||
pub home: PathBuf,
|
||||
client: Option<Client>,
|
||||
}
|
||||
|
||||
@@ -106,9 +117,14 @@ impl Session {
|
||||
Self {
|
||||
socket,
|
||||
timeout,
|
||||
home: horizon_client::logging::game_home(),
|
||||
client: None,
|
||||
}
|
||||
}
|
||||
/// A failure while No AI is on: every command refuses (help aside).
|
||||
pub fn allowed(&self) -> Result<(), Failure> {
|
||||
horizon_core::no_ai::check(&self.home).map_err(|_| Failure::denied())
|
||||
}
|
||||
fn client(&mut self) -> Result<&mut Client, Failure> {
|
||||
if self.client.is_none() {
|
||||
self.client = Some(Client::connect(&self.socket, self.timeout)?);
|
||||
@@ -137,6 +153,7 @@ impl Session {
|
||||
let Some(name) = words.first().map(String::as_str) else {
|
||||
return Err(Failure::usage("no command; try horizon-ctl help"));
|
||||
};
|
||||
self.allowed()?;
|
||||
if words.iter().skip(1).any(|w| w == "--help" || w == "-h") {
|
||||
return Err(Failure::usage(
|
||||
"use horizon-ctl COMMAND --help outside scripts",
|
||||
@@ -174,6 +191,18 @@ impl Session {
|
||||
ready["launch"] = reply;
|
||||
Ok(ready)
|
||||
}
|
||||
"interact-entity" => {
|
||||
let id = match words {
|
||||
[_, id] if id.parse::<i64>().is_ok() => id,
|
||||
_ => return Err(Failure::usage(format!("usage: {}", usage(name)))),
|
||||
};
|
||||
self.game(&format!("look-at entity {id}"))?;
|
||||
self.game("mouse right click")?;
|
||||
self.game("wait 2")?;
|
||||
let mut screen = self.game("screen")?;
|
||||
screen["ok"] = json!(true);
|
||||
Ok(screen)
|
||||
}
|
||||
"hold" => {
|
||||
let (key, seconds) = match words {
|
||||
[_, key, _] => (key.clone(), number(2, "SECONDS")?),
|
||||
@@ -183,7 +212,7 @@ impl Session {
|
||||
thread::sleep(Duration::from_secs_f64(seconds.max(0.0)));
|
||||
self.game(&format!("key {key} up"))
|
||||
}
|
||||
"logs" => logs(&horizon_client::logging::game_home(), &words[1..]),
|
||||
"logs" => logs(&self.home, &words[1..]),
|
||||
"wait-ready" => {
|
||||
let limit = if words.len() > 1 {
|
||||
number(1, "SECONDS")?
|
||||
@@ -417,6 +446,10 @@ fn main() -> ExitCode {
|
||||
print!("{}", commands::overview());
|
||||
0
|
||||
}
|
||||
Some("help") if args.get(1).is_some_and(|a| a == "--markdown") => {
|
||||
print!("{}", commands::markdown());
|
||||
0
|
||||
}
|
||||
Some("help") if args.get(1).is_none_or(|a| a != "--game") => match args.get(1) {
|
||||
None => {
|
||||
print!("{}", commands::overview());
|
||||
@@ -451,6 +484,10 @@ fn main() -> ExitCode {
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("mcp") if session.allowed().is_err() => {
|
||||
eprintln!("horizon-ctl mcp: {}", horizon_core::no_ai::REFUSAL);
|
||||
DENIED
|
||||
}
|
||||
Some("mcp") => match mcp::serve(&mut session) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
@@ -581,6 +618,27 @@ mod tests {
|
||||
assert_eq!(f.status, USAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ai_refuses_every_command() {
|
||||
let home = std::env::temp_dir().join(format!("horizon-ctl-no-ai-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None);
|
||||
s.home = home.clone();
|
||||
assert_eq!(
|
||||
s.run(&["state".to_owned()]).unwrap_err().status,
|
||||
UNREACHABLE
|
||||
);
|
||||
horizon_core::no_ai::set(&home, true).unwrap();
|
||||
for words in [vec!["state"], vec!["logs"], vec!["launch", "--world", "A"]] {
|
||||
let words: Vec<String> = words.into_iter().map(str::to_owned).collect();
|
||||
let f = s.run(&words).unwrap_err();
|
||||
assert_eq!(f.status, DENIED, "{words:?}");
|
||||
assert_eq!(f.reply["kind"], "denied");
|
||||
assert_eq!(f.reply["error"], horizon_core::no_ai::REFUSAL);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screenshot_paths_become_absolute() {
|
||||
let mut words = vec!["screenshot".to_owned(), "a.png".to_owned()];
|
||||
|
||||
@@ -23,7 +23,13 @@ fn tools() -> Vec<Value> {
|
||||
schema = json!({ "type": "object", "properties": {} });
|
||||
description = "Capture the game window and return it as a PNG image.".into();
|
||||
}
|
||||
json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema })
|
||||
let mut tool = json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema });
|
||||
if commands::DESTRUCTIVE.contains(&c.name) {
|
||||
tool["annotations"] = json!({ "destructiveHint": true });
|
||||
} else if commands::OPEN_WORLD.contains(&c.name) {
|
||||
tool["annotations"] = json!({ "openWorldHint": true });
|
||||
}
|
||||
tool
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -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.")
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -107,6 +107,8 @@ pub struct Extras {
|
||||
pub sort: bool,
|
||||
/// A vanilla key name: sorts the part under the cursor.
|
||||
pub sort_key: String,
|
||||
/// No AI: every AI feature hidden and off (`horizon_core::no_ai`; the launcher writes it too).
|
||||
pub no_ai: bool,
|
||||
}
|
||||
impl Default for Extras {
|
||||
fn default() -> Self {
|
||||
@@ -135,6 +137,7 @@ impl Default for Extras {
|
||||
mouse_tweaks_wheel: true,
|
||||
sort: false,
|
||||
sort_key: "key.keyboard.unknown".into(),
|
||||
no_ai: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -198,6 +201,7 @@ impl Extras {
|
||||
"mouseTweaksWheel" => e.mouse_tweaks_wheel = flag(e.mouse_tweaks_wheel),
|
||||
"sort" => e.sort = flag(e.sort),
|
||||
"sortKey" if value.starts_with("key.") => e.sort_key = value.to_owned(),
|
||||
horizon_core::no_ai::KEY => e.no_ai = flag(e.no_ai),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -205,7 +209,7 @@ impl Extras {
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n",
|
||||
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\n",
|
||||
bool_text(self.fullbright),
|
||||
bool_text(self.dynamic_lights),
|
||||
bool_text(self.zoom),
|
||||
@@ -234,6 +238,8 @@ impl Extras {
|
||||
bool_text(self.mouse_tweaks_wheel),
|
||||
bool_text(self.sort),
|
||||
self.sort_key,
|
||||
horizon_core::no_ai::KEY,
|
||||
bool_text(self.no_ai),
|
||||
)
|
||||
}
|
||||
/// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Play with Friends: Horizon's own sharing of the open world behind an
|
||||
//! invite code (`game/friends.rs`). The pause menu's Friends button, the icon
|
||||
//! vanilla's PauseScreen already has, opens it. It is drawn the way a mod adds
|
||||
//! a screen to vanilla: the menu background, a centred title and text,
|
||||
//! vanilla's buttons and Done in the footer.
|
||||
use crate::{
|
||||
hud::{HudAtlas, HudBatch, rgba},
|
||||
multiplayer::wrap,
|
||||
text::Text,
|
||||
ui,
|
||||
};
|
||||
|
||||
pub const TITLE: &str = "Play with Friends";
|
||||
/// What the screen shows (game/friends.rs fills it).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FriendsView {
|
||||
/// A singleplayer world (not a server): sharing is offered.
|
||||
pub shown: bool,
|
||||
pub sharing: bool,
|
||||
pub code: Option<String>,
|
||||
/// Who can join and what to do when friends on the internet can't (or,
|
||||
/// before the code, what the game is doing).
|
||||
pub status: String,
|
||||
/// Friends on the internet can reach the host.
|
||||
pub reachable: bool,
|
||||
/// Where the troubleshooting is, when they can't.
|
||||
pub help: Option<String>,
|
||||
/// The players in the world besides the host.
|
||||
pub guests: Vec<String>,
|
||||
pub notice: Option<String>,
|
||||
/// The code was just copied.
|
||||
pub copied: bool,
|
||||
}
|
||||
|
||||
/// A button's action.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Action {
|
||||
Share,
|
||||
Copy,
|
||||
Stop,
|
||||
/// Open the troubleshooting page.
|
||||
Help,
|
||||
Done,
|
||||
}
|
||||
|
||||
fn grey() -> u32 {
|
||||
rgba(160, 160, 160, 255)
|
||||
}
|
||||
const WHITE: u32 = u32::MAX;
|
||||
const HINT: &str = "Friends paste the code after the title screen's Friends button, in Direct Connection, or on the launcher's Play page.";
|
||||
|
||||
struct Button {
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
label: &'static str,
|
||||
action: Action,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
/// The centred lines (text, colour, y) and the buttons.
|
||||
fn layout(
|
||||
atlas: &HudAtlas,
|
||||
(w, h): (f32, f32),
|
||||
view: &FriendsView,
|
||||
) -> (Vec<(String, u32, f32)>, Vec<Button>) {
|
||||
let width = (w - 40.0).min(310.0);
|
||||
let cx = (w / 2.0).floor();
|
||||
let mut lines = Vec::new();
|
||||
let mut y = 40.0;
|
||||
let add = |lines: &mut Vec<(String, u32, f32)>, text: &str, color: u32, y: &mut f32| {
|
||||
for line in wrap(text, width, atlas) {
|
||||
lines.push((line, color, *y));
|
||||
*y += 10.0;
|
||||
}
|
||||
};
|
||||
let mut buttons = Vec::new();
|
||||
if view.sharing {
|
||||
lines.push(("Invite Code".to_owned(), grey(), y));
|
||||
y += 12.0;
|
||||
match &view.code {
|
||||
Some(code) => {
|
||||
for line in code_lines(atlas, code, width) {
|
||||
lines.push((line, WHITE, y));
|
||||
y += 10.0;
|
||||
}
|
||||
}
|
||||
None => add(&mut lines, &view.status, WHITE, &mut y),
|
||||
}
|
||||
y += 6.0;
|
||||
buttons.push(Button {
|
||||
x: cx - 154.0,
|
||||
y,
|
||||
w: 150.0,
|
||||
label: if view.copied { "Copied" } else { "Copy Code" },
|
||||
action: Action::Copy,
|
||||
active: view.code.is_some(),
|
||||
});
|
||||
buttons.push(Button {
|
||||
x: cx + 4.0,
|
||||
y,
|
||||
w: 150.0,
|
||||
label: "Stop Sharing",
|
||||
action: Action::Stop,
|
||||
active: true,
|
||||
});
|
||||
y += 30.0;
|
||||
if view.code.is_some() {
|
||||
// Who can join: grey when friends anywhere can, white (it asks
|
||||
// for something) when only the LAN and VPNs can.
|
||||
let tint = if view.reachable { grey() } else { WHITE };
|
||||
add(&mut lines, &view.status, tint, &mut y);
|
||||
y += 4.0;
|
||||
}
|
||||
let here = if view.guests.is_empty() {
|
||||
"No friends here yet.".to_owned()
|
||||
} else {
|
||||
format!("Here now: {}", view.guests.join(", "))
|
||||
};
|
||||
add(&mut lines, &here, grey(), &mut y);
|
||||
if let Some(notice) = &view.notice {
|
||||
add(&mut lines, notice, WHITE, &mut y);
|
||||
}
|
||||
// Where friends paste the code, while it fits above the footer.
|
||||
if y + 10.0 * wrap(HINT, width, atlas).len() as f32 <= h - 33.0 {
|
||||
add(&mut lines, HINT, grey(), &mut y);
|
||||
}
|
||||
} else {
|
||||
add(
|
||||
&mut lines,
|
||||
"Share this world behind an invite code: it opens to LAN, and friends on the internet join with the code. No server of ours is involved.",
|
||||
WHITE,
|
||||
&mut y,
|
||||
);
|
||||
y += 4.0;
|
||||
add(&mut lines, HINT, grey(), &mut y);
|
||||
buttons.push(Button {
|
||||
x: cx - 100.0,
|
||||
y: y + 8.0,
|
||||
w: 200.0,
|
||||
label: "Start Sharing",
|
||||
action: Action::Share,
|
||||
active: view.shown,
|
||||
});
|
||||
}
|
||||
// HeaderAndFooterLayout's footer: Done, beside Troubleshooting when
|
||||
// friends on the internet can't reach the host.
|
||||
if view.sharing && view.help.is_some() {
|
||||
buttons.push(Button {
|
||||
x: cx - 154.0,
|
||||
y: h - 27.0,
|
||||
w: 150.0,
|
||||
label: "Troubleshooting...",
|
||||
action: Action::Help,
|
||||
active: true,
|
||||
});
|
||||
buttons.push(Button {
|
||||
x: cx + 4.0,
|
||||
y: h - 27.0,
|
||||
w: 150.0,
|
||||
label: "gui.done",
|
||||
action: Action::Done,
|
||||
active: true,
|
||||
});
|
||||
} else {
|
||||
buttons.push(Button {
|
||||
x: cx - 100.0,
|
||||
y: h - 27.0,
|
||||
w: 200.0,
|
||||
label: "gui.done",
|
||||
action: Action::Done,
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
(lines, buttons)
|
||||
}
|
||||
/// The code's groups packed into lines of at most `width`.
|
||||
fn code_lines(atlas: &HudAtlas, code: &str, width: f32) -> Vec<String> {
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
for group in code.split('-') {
|
||||
match lines.last_mut() {
|
||||
Some(l) if HudBatch::text_width(atlas, &format!("{l}-{group}")) <= width => {
|
||||
l.push('-');
|
||||
l.push_str(group);
|
||||
}
|
||||
_ => lines.push(group.to_owned()),
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
fn label(key: &str) -> Text {
|
||||
if key.starts_with("gui.") {
|
||||
Text::translate(key, &[])
|
||||
} else {
|
||||
Text::literal(key)
|
||||
}
|
||||
}
|
||||
pub fn draw(
|
||||
batch: &mut HudBatch,
|
||||
atlas: &HudAtlas,
|
||||
cursor: (f32, f32),
|
||||
view: &FriendsView,
|
||||
in_world: bool,
|
||||
) {
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world);
|
||||
let title = Text::literal(TITLE);
|
||||
let tw = atlas.font.width_text(&title);
|
||||
batch.text_styled(atlas, &title, ((w - tw) / 2.0).floor(), 15.0, WHITE, true);
|
||||
let (lines, buttons) = layout(atlas, (w, h), view);
|
||||
for (line, color, y) in lines {
|
||||
let lw = HudBatch::text_width(atlas, &line);
|
||||
batch.text(atlas, &line, ((w - lw) / 2.0).floor(), y, color, true);
|
||||
}
|
||||
for b in buttons {
|
||||
let hover = b.active && ui::hovered(cursor, b.x, b.y, b.w, 20.0);
|
||||
ui::button(
|
||||
batch,
|
||||
atlas,
|
||||
b.x,
|
||||
b.y,
|
||||
b.w,
|
||||
20.0,
|
||||
&label(b.label),
|
||||
b.active,
|
||||
hover,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// The button under a click, if it is active.
|
||||
pub fn click(
|
||||
atlas: &HudAtlas,
|
||||
size: (f32, f32),
|
||||
cursor: (f32, f32),
|
||||
view: &FriendsView,
|
||||
) -> Option<Action> {
|
||||
layout(atlas, size, view)
|
||||
.1
|
||||
.into_iter()
|
||||
.find(|b| b.active && ui::hovered(cursor, b.x, b.y, b.w, 20.0))
|
||||
.map(|b| b.action)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn atlas() -> HudAtlas {
|
||||
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_then_copy_and_stop() {
|
||||
let atlas = atlas();
|
||||
let size = (427.0, 240.0);
|
||||
let idle = FriendsView {
|
||||
shown: true,
|
||||
..FriendsView::default()
|
||||
};
|
||||
let (_, buttons) = layout(&atlas, size, &idle);
|
||||
let share = buttons.iter().find(|b| b.action == Action::Share).unwrap();
|
||||
assert_eq!(
|
||||
click(&atlas, size, (share.x + 1.0, share.y + 1.0), &idle),
|
||||
Some(Action::Share)
|
||||
);
|
||||
let sharing = FriendsView {
|
||||
shown: true,
|
||||
sharing: true,
|
||||
status: "Finding how friends can reach you…".into(),
|
||||
..FriendsView::default()
|
||||
};
|
||||
let (_, buttons) = layout(&atlas, size, &sharing);
|
||||
let copy = buttons.iter().find(|b| b.action == Action::Copy).unwrap();
|
||||
assert!(!copy.active, "nothing to copy before the code");
|
||||
let with_code = FriendsView {
|
||||
code: Some("0B33K-Q405Q-1Z5CV-X6NHY-R12N0-VK8T1-60N00-RA134-952PE-1HA08-910P0-K5M01-ST1NB-JDTB6-K4W1P-0".into()),
|
||||
status: "Friends on your network or VPN can join. For friends on the internet: turn on UPnP on your router, or forward TCP port 25580 to 10.0.0.2, or use a relay, or a VPN such as Tailscale or ZeroTier (the code already holds your VPN address).".into(),
|
||||
help: Some("https://example.invalid/help".into()),
|
||||
..sharing
|
||||
};
|
||||
let (lines, buttons) = layout(&atlas, size, &with_code);
|
||||
assert!(
|
||||
lines.iter().all(|(_, _, y)| y + 9.0 <= size.1 - 27.0),
|
||||
"the text stays above the footer"
|
||||
);
|
||||
for action in [Action::Copy, Action::Stop, Action::Help, Action::Done] {
|
||||
let b = buttons.iter().find(|b| b.action == action).unwrap();
|
||||
assert_eq!(
|
||||
click(&atlas, size, (b.x + 1.0, b.y + 1.0), &with_code),
|
||||
Some(action)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_offers_no_sharing() {
|
||||
let atlas = atlas();
|
||||
let view = FriendsView::default();
|
||||
let (_, buttons) = layout(&atlas, (427.0, 240.0), &view);
|
||||
let share = buttons.iter().find(|b| b.action == Action::Share).unwrap();
|
||||
assert!(!share.active);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+172
-196
@@ -5,7 +5,6 @@ mod advancements_screen;
|
||||
mod agent;
|
||||
mod allays;
|
||||
mod armor_stands;
|
||||
mod backdrop;
|
||||
mod banners;
|
||||
mod beacon;
|
||||
mod beehives;
|
||||
@@ -72,10 +71,12 @@ mod lan_chat;
|
||||
mod lan_crafting;
|
||||
mod lan_entities;
|
||||
mod lan_mobs;
|
||||
mod lan_mount_menu;
|
||||
mod lan_pvp;
|
||||
mod lan_screen;
|
||||
mod lan_stations;
|
||||
mod lan_trading;
|
||||
mod lan_vehicles;
|
||||
mod lan_waypoints;
|
||||
mod leads;
|
||||
mod level_particles;
|
||||
@@ -121,9 +122,11 @@ mod remote;
|
||||
mod remote_objects;
|
||||
mod remote_projectiles;
|
||||
mod remote_stations;
|
||||
mod remote_vehicles;
|
||||
mod render_control;
|
||||
mod render_tick;
|
||||
mod respawn_anchor;
|
||||
mod saves_control;
|
||||
mod saving;
|
||||
mod scoreboard;
|
||||
mod screens;
|
||||
@@ -273,10 +276,9 @@ struct Options {
|
||||
benchmark: Option<String>,
|
||||
/// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt.
|
||||
dev_mods: Vec<PathBuf>,
|
||||
/// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on an
|
||||
/// integrated server thread (game/integrated.rs), as vanilla's does. Off by
|
||||
/// default again until a server's players can board, ride and hit
|
||||
/// vehicles (#1222); `--no-server-thread` keeps it off.
|
||||
/// Single player runs on an integrated server thread (game/integrated.rs),
|
||||
/// as vanilla's does: the default. `--no-server-thread` or
|
||||
/// `HORIZON_SERVER_THREAD=0` runs the world in the frame instead.
|
||||
server_thread: bool,
|
||||
/// Set on the integrated server's own options: it draws nothing, so it skips meshing.
|
||||
integrated: bool,
|
||||
@@ -333,7 +335,7 @@ impl Options {
|
||||
dev_mods: Vec::new(),
|
||||
// The command harness (HORIZON_COMMAND_SCRIPT) drives the world
|
||||
// itself, without the event loop: it stays in the frame.
|
||||
server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1")
|
||||
server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0")
|
||||
&& std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(),
|
||||
integrated: false,
|
||||
};
|
||||
@@ -343,7 +345,7 @@ impl Options {
|
||||
match arg.as_str() {
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --server-thread Run single player's world on its server thread (no vehicles yet)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
|
||||
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
|
||||
horizon_core::VANILLA_VERSION
|
||||
);
|
||||
return Ok(None);
|
||||
@@ -455,6 +457,9 @@ enum Screen {
|
||||
Advancements,
|
||||
/// WorldOptionsScreen (game/lan_screen.rs).
|
||||
WorldOptions,
|
||||
/// Play with Friends, from the pause menu's Friends button
|
||||
/// (`friends_screen`, game/friends.rs).
|
||||
Friends,
|
||||
/// CommandBlockEditScreen (game/command_blocks.rs).
|
||||
CommandBlock,
|
||||
}
|
||||
@@ -1112,6 +1117,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,
|
||||
@@ -1314,14 +1320,12 @@ struct Game<'a> {
|
||||
settings: Settings,
|
||||
/// Where the options screen returns: true = title, false = pause menu.
|
||||
options_from_title: bool,
|
||||
/// The live title backdrop (game/backdrop.rs).
|
||||
backdrop: backdrop::Backdrop,
|
||||
/// When the pause menu opened (Horizon style's entrance).
|
||||
pause_since: Option<Instant>,
|
||||
dragging: bool,
|
||||
/// `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,
|
||||
@@ -4452,6 +4456,7 @@ impl Game<'_> {
|
||||
| Screen::Stats
|
||||
| Screen::Advancements
|
||||
| Screen::WorldOptions
|
||||
| Screen::Friends
|
||||
| Screen::CommandBlock
|
||||
) || self.book.is_some())
|
||||
}
|
||||
@@ -4679,20 +4684,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
if let Some(title) = &self.title {
|
||||
if horizon_client::ui_theme::horizon() {
|
||||
let fade = self.backdrop_fade();
|
||||
let mut ui =
|
||||
horizon_client::ui_theme::Ui::new(&self.gui.atlas, &mut batch, self.cursor);
|
||||
title.draw_horizon(&mut ui, fade);
|
||||
ui.finish();
|
||||
} else {
|
||||
title.draw(
|
||||
&self.gui.atlas,
|
||||
&mut batch,
|
||||
self.cursor,
|
||||
self.settings.file.bool("hideSplashTexts"),
|
||||
);
|
||||
}
|
||||
title.draw(
|
||||
&self.gui.atlas,
|
||||
&mut batch,
|
||||
self.cursor,
|
||||
self.settings.file.bool("hideSplashTexts"),
|
||||
);
|
||||
return batch;
|
||||
}
|
||||
let atlas_ptr: *const HudAtlas = &self.gui.atlas;
|
||||
@@ -4709,9 +4706,7 @@ impl Game<'_> {
|
||||
// the sleep overlay, debug screen and open screens still draw.
|
||||
let spectator = self.spectator();
|
||||
let (wi, hi) = (w as i32, h as i32);
|
||||
// Horizon's pause menu sits over the blurred world alone.
|
||||
let horizon_pause = self.horizon_pause();
|
||||
let show_hud = !self.ui.hide_gui && !horizon_pause;
|
||||
let show_hud = !self.ui.hide_gui;
|
||||
if show_hud {
|
||||
self.draw_spyglass(&mut batch);
|
||||
// Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth /
|
||||
@@ -4845,10 +4840,11 @@ impl Game<'_> {
|
||||
let tw = HudBatch::text_width(atlas, text);
|
||||
batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true);
|
||||
}
|
||||
if !horizon_pause {
|
||||
self.draw_chat(&mut batch);
|
||||
self.draw_tab_list(&mut batch);
|
||||
}
|
||||
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.
|
||||
@@ -4869,6 +4865,7 @@ impl Game<'_> {
|
||||
Screen::Stats => self.draw_stats(&mut batch),
|
||||
Screen::Advancements => self.draw_advancements(&mut batch),
|
||||
Screen::WorldOptions => self.draw_world_options(&mut batch),
|
||||
Screen::Friends => self.draw_friends_screen(&mut batch),
|
||||
Screen::CommandBlock => self.draw_command_block(&mut batch),
|
||||
Screen::Inventory => {
|
||||
self.draw_inventory(&mut batch);
|
||||
@@ -5480,6 +5477,16 @@ impl Game<'_> {
|
||||
let mut v = vec![None; 45];
|
||||
v.extend((0..9).map(Some));
|
||||
(Kind::ItemPicker, v)
|
||||
} else if let Some(columns) = self
|
||||
.mount_menu_columns()
|
||||
.filter(|_| self.remote.is_some() && self.mount_active())
|
||||
{
|
||||
// A server's HorseInventoryMenu: the saddle, the body armour,
|
||||
// the chest, then the inventory.
|
||||
let mut v = vec![Some(mount_menu::SADDLE), Some(mount_menu::ARMOR)];
|
||||
v.extend((0..columns * 3).map(|i| Some(mount_menu::CHEST + i)));
|
||||
v.extend((9..36).chain(0..9).map(Some));
|
||||
(Kind::Mount(columns), v)
|
||||
} else if merchant_open {
|
||||
// MerchantMenu: two payment slots, the result, then the inventory.
|
||||
let mut v: Vec<Option<usize>> = vec![
|
||||
@@ -5612,6 +5619,9 @@ impl Game<'_> {
|
||||
None => game_of.iter().position(|x| *x == Some(g)),
|
||||
};
|
||||
let mut menu = Menu::new(kind);
|
||||
if matches!(kind, Kind::Mount(_)) {
|
||||
menu.mount = self.mount_menu_entity();
|
||||
}
|
||||
let total = menu.slot_count();
|
||||
let before: Vec<Option<ItemStack>> = game_of
|
||||
.iter()
|
||||
@@ -7707,6 +7717,10 @@ impl Game<'_> {
|
||||
fullscreen: s.fullscreen,
|
||||
graphics: s.graphics_preset.clone(),
|
||||
};
|
||||
// Again now: on Wayland the window is on a screen only once it has been shown.
|
||||
if let Some(window) = &self.window {
|
||||
horizon_client::telemetry::note_display(window);
|
||||
}
|
||||
self.perf
|
||||
.finish(&horizon_client::logging::game_home(), settings);
|
||||
}
|
||||
@@ -8953,89 +8967,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.
|
||||
@@ -9597,12 +9606,7 @@ impl Game<'_> {
|
||||
// Camera.getCameraEntityPartialTicks: the view, the hand and the
|
||||
// player's own model stay smooth while the level is frozen.
|
||||
let camera_alpha = self.clock.camera_fraction();
|
||||
let live = self.backdrop_live();
|
||||
let view = if live {
|
||||
self.backdrop_view()
|
||||
} else {
|
||||
self.camera_view(camera_alpha as f32)
|
||||
};
|
||||
let view = self.camera_view(camera_alpha as f32);
|
||||
let (camera, underwater, view_yaw, view_pitch) = match view {
|
||||
Some((c, yaw, pitch)) => {
|
||||
let s =
|
||||
@@ -9750,9 +9754,7 @@ impl Game<'_> {
|
||||
// LevelLoadingScreen (Reason.OTHER) draws the title's panorama.
|
||||
let title = self.title.is_some()
|
||||
|| self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
|
||||
let (yaw, pitch) = if live {
|
||||
(view_yaw, view_pitch)
|
||||
} else if title {
|
||||
let (yaw, pitch) = if title {
|
||||
// PanoramaRenderer: the title cube spins at 0.1 degrees per tick, pitched 10 degrees.
|
||||
(
|
||||
self.panorama_rotation.update(
|
||||
@@ -9764,9 +9766,7 @@ impl Game<'_> {
|
||||
} else {
|
||||
(view_yaw, view_pitch)
|
||||
};
|
||||
let fov_degrees = if live {
|
||||
72.0
|
||||
} else if title {
|
||||
let fov_degrees = if title {
|
||||
85.0
|
||||
} else {
|
||||
self.fov_degrees(camera_alpha as f32, camera.to_array())
|
||||
@@ -9793,15 +9793,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`.
|
||||
@@ -9815,7 +9817,7 @@ impl Game<'_> {
|
||||
}
|
||||
.to_owned()
|
||||
};
|
||||
let (celestial, stars) = if title && !live {
|
||||
let (celestial, stars) = if title {
|
||||
(Vec::new(), None)
|
||||
} else if self.dim == Dim::Overworld
|
||||
&& self.potions.effects.get("darkness").is_none()
|
||||
@@ -9823,8 +9825,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)
|
||||
};
|
||||
@@ -9841,11 +9843,11 @@ 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 && 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();
|
||||
@@ -9856,6 +9858,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,
|
||||
@@ -9868,9 +9872,15 @@ impl Game<'_> {
|
||||
detail_distance: (self.streaming.radius * 16) as f32,
|
||||
depth_far,
|
||||
underwater,
|
||||
title: title && !live,
|
||||
title,
|
||||
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,
|
||||
@@ -9896,7 +9906,7 @@ impl Game<'_> {
|
||||
debug_lines_on_top: &debug_lines_on_top,
|
||||
debug_crosshair: &debug_crosshair,
|
||||
hud: &hud,
|
||||
clouds: ((!title || live)
|
||||
clouds: (!title
|
||||
&& self.dim == Dim::Overworld
|
||||
&& horizon_client::clouds::visible(&clouds_mode, sky.cloud_color[3]))
|
||||
.then(|| self.gui.atlas.sprites.get("horizon/white"))
|
||||
@@ -9913,6 +9923,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 {
|
||||
@@ -9944,13 +9961,6 @@ impl Game<'_> {
|
||||
darkness: self.darkness_lighting(alpha as f32),
|
||||
night_vision: self.night_vision_intensity(),
|
||||
block_flicker: self.fog.block_light_flicker,
|
||||
post: if live {
|
||||
Some(horizon_client::post::PostGrade::FROST)
|
||||
} else if self.horizon_pause() {
|
||||
Some(horizon_client::post::PostGrade::PAUSE)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
menu_blur: self.menu_blur(),
|
||||
};
|
||||
let result = match self.renderer.as_mut() {
|
||||
@@ -10018,17 +10028,18 @@ 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()
|
||||
&& (loading
|
||||
|| self.title.as_ref().is_some_and(|t| {
|
||||
self.screen == Screen::Options
|
||||
|| !matches!(t.mode, horizon_client::title::Mode::Main)
|
||||
}));
|
||||
let blurred = loading
|
||||
|| 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)
|
||||
}
|
||||
@@ -10107,7 +10118,7 @@ impl Game<'_> {
|
||||
}
|
||||
Screen::GameModeSwitcher => self.close_gamemode_switcher(false),
|
||||
Screen::Dead => {}
|
||||
Screen::Stats => self.screen = Screen::Paused,
|
||||
Screen::Stats | Screen::Friends => self.screen = Screen::Paused,
|
||||
Screen::Advancements => self.close_advancements(),
|
||||
Screen::WorldOptions => self.world_options_escape(),
|
||||
Screen::CommandBlock => self.close_command_block(),
|
||||
@@ -10508,6 +10519,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
return;
|
||||
}
|
||||
};
|
||||
horizon_client::telemetry::note_display(&window);
|
||||
match self.new_renderer(window.clone()) {
|
||||
Ok(r) => {
|
||||
self.renderer = Some(r);
|
||||
@@ -10581,15 +10593,6 @@ impl ApplicationHandler for Game<'_> {
|
||||
) {
|
||||
self.last_input = Instant::now();
|
||||
}
|
||||
if let WindowEvent::MouseInput {
|
||||
state,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} = &event
|
||||
{
|
||||
// The press state of Horizon-style buttons.
|
||||
horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed);
|
||||
}
|
||||
if (self.pending_entry.is_some() || self.world_loader.is_some())
|
||||
&& matches!(&event, WindowEvent::KeyboardInput { event, .. }
|
||||
if event.state == ElementState::Pressed
|
||||
@@ -10689,9 +10692,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
if matches!(self.screen, Screen::Inventory | Screen::Creative) {
|
||||
self.inventory_drag_move();
|
||||
}
|
||||
if let Some(title) = &mut self.title
|
||||
&& !horizon_client::ui_theme::horizon()
|
||||
{
|
||||
if let Some(title) = &mut self.title {
|
||||
title.drag(self.cursor, (b.width, b.height));
|
||||
title.drag_field(&self.gui.atlas, self.cursor.0);
|
||||
}
|
||||
@@ -10717,9 +10718,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
}) * wheel_sensitivity
|
||||
};
|
||||
let d = scaled(raw_y) as f32;
|
||||
if let Some(title) = &mut self.title
|
||||
&& !horizon_client::ui_theme::horizon()
|
||||
{
|
||||
if let Some(title) = &mut self.title {
|
||||
let size = self
|
||||
.window
|
||||
.as_ref()
|
||||
@@ -10807,21 +10806,13 @@ impl ApplicationHandler for Game<'_> {
|
||||
.as_ref()
|
||||
.map(|r| [r.config.width, r.config.height])
|
||||
.unwrap_or([1, 1]);
|
||||
let mut b = HudBatch::new(size);
|
||||
let b = HudBatch::new(size);
|
||||
let atlas = &self.gui.atlas;
|
||||
let shift = self.has_shift_down();
|
||||
let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| {
|
||||
if horizon_client::ui_theme::horizon() {
|
||||
(
|
||||
t.click_horizon(atlas, &mut b, self.cursor.0, self.cursor.1),
|
||||
false,
|
||||
)
|
||||
} else {
|
||||
let clicked =
|
||||
t.click(self.cursor.0, self.cursor.1, (b.width, b.height));
|
||||
t.press_field(atlas, self.cursor, (b.width, b.height), shift);
|
||||
clicked
|
||||
}
|
||||
let clicked = t.click(self.cursor.0, self.cursor.1, (b.width, b.height));
|
||||
t.press_field(atlas, self.cursor, (b.width, b.height), shift);
|
||||
clicked
|
||||
});
|
||||
self.save_title_options();
|
||||
if sound {
|
||||
@@ -10957,6 +10948,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
Screen::WorldOptions if pressed && button == MouseButton::Left => {
|
||||
self.world_options_click()
|
||||
}
|
||||
Screen::Friends if pressed && button == MouseButton::Left => {
|
||||
self.friends_screen_click()
|
||||
}
|
||||
Screen::CommandBlock if pressed && button == MouseButton::Left => {
|
||||
self.command_block_click()
|
||||
}
|
||||
@@ -11056,9 +11050,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => {
|
||||
if event.state == ElementState::Pressed
|
||||
&& self.title.as_ref().is_some_and(|t| !t.skip_opening())
|
||||
{
|
||||
if event.state == ElementState::Pressed {
|
||||
if let Some(shortcut) = self.edit_shortcut(&event) {
|
||||
self.title_shortcut(shortcut);
|
||||
return Ok(());
|
||||
@@ -11151,11 +11143,6 @@ impl ApplicationHandler for Game<'_> {
|
||||
+ (turn(KeyCode::ArrowDown) - turn(KeyCode::ArrowUp)) * 90.0 * secs)
|
||||
.clamp(-90.0, 90.0);
|
||||
}
|
||||
self.update_backdrop()?;
|
||||
horizon_client::ui_theme::set_backdrop(self.backdrop_fade());
|
||||
if self.screen != Screen::Paused {
|
||||
self.pause_since = None;
|
||||
}
|
||||
if self.title.is_none() {
|
||||
horizon_client::spans::time("update_world", || self.update_world());
|
||||
horizon_client::spans::time("spawn_player", || self.spawn_player())?;
|
||||
@@ -11177,8 +11164,6 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
self.tick_ambience();
|
||||
self.tick_fov();
|
||||
} else if self.title.is_some() {
|
||||
self.tick_backdrop();
|
||||
}
|
||||
self.tick_music();
|
||||
self.tick_sound_engine();
|
||||
@@ -11449,6 +11434,7 @@ impl<'a> Game<'a> {
|
||||
gui,
|
||||
fog: Default::default(),
|
||||
screen_fx: Default::default(),
|
||||
weather_parameters: Default::default(),
|
||||
panorama_rotation: Default::default(),
|
||||
world,
|
||||
streaming,
|
||||
@@ -11588,11 +11574,10 @@ impl<'a> Game<'a> {
|
||||
hand_strength: Default::default(),
|
||||
settings,
|
||||
options_from_title: false,
|
||||
backdrop: Default::default(),
|
||||
pause_since: None,
|
||||
dragging: false,
|
||||
avatar: Default::default(),
|
||||
flash: 0,
|
||||
lightning_seen: [0; 2],
|
||||
sleeping: None,
|
||||
sleep_timer: 0,
|
||||
dim: Dim::Overworld,
|
||||
@@ -11961,13 +11946,11 @@ impl Progress {
|
||||
/// Harness and dedicated runs keep the fully-synchronous startup so their
|
||||
/// output stays byte-identical; only an ordinary launch shows the window first.
|
||||
fn synchronous_startup(options: &Options) -> bool {
|
||||
let classic = std::env::var("HORIZON_MENU_STYLE").ok().as_deref() == Some("classic");
|
||||
options.frames.is_some()
|
||||
|| options.world_frames.is_some()
|
||||
|| options.benchmark.is_some()
|
||||
|| options.control.is_some()
|
||||
|| options.dedicated.is_some()
|
||||
|| classic
|
||||
|| std::env::var_os("HORIZON_DISPENSE_FIXTURE").is_some()
|
||||
|| std::env::var_os("HORIZON_SCULK_FIXTURE").is_some()
|
||||
|| std::env::var_os("HORIZON_COMMAND_SCRIPT").is_some()
|
||||
@@ -11988,7 +11971,7 @@ fn load_resources(
|
||||
let requested_root = root.clone();
|
||||
let threads = settings.horizon.worker_threads();
|
||||
// Stage A: the menu bundle (atlas and panorama). With a loading screen it is
|
||||
// published at once so the title backdrop can appear while the world bundle
|
||||
// published at once so the title screen can appear while the world bundle
|
||||
// loads; the synchronous launch instead carries it in `Loaded`.
|
||||
let mut loaded_gui = None;
|
||||
let mut ui_ready = false;
|
||||
@@ -12361,6 +12344,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,
|
||||
@@ -12375,6 +12360,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,
|
||||
@@ -12389,6 +12375,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
|
||||
entities: &[],
|
||||
dynamic_lights: &[],
|
||||
clouds: None,
|
||||
lightning: Default::default(),
|
||||
additive: &[],
|
||||
see_through: &[],
|
||||
celestial: &[],
|
||||
@@ -12405,7 +12392,6 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
|
||||
darkness: (0.0, 0.0),
|
||||
night_vision: 0.0,
|
||||
block_flicker: 0.0,
|
||||
post: None,
|
||||
menu_blur: None,
|
||||
shader: Default::default(),
|
||||
}
|
||||
@@ -12432,18 +12418,8 @@ fn start_game<'a>(
|
||||
let handoff = prepared.is_some();
|
||||
let mut settings = match settings {
|
||||
Some(settings) => settings,
|
||||
None => {
|
||||
horizon_client::ui_theme::load_preferences(&std::env::current_dir()?);
|
||||
Settings::load(&std::env::current_dir()?.join("options.txt"))
|
||||
}
|
||||
None => Settings::load(&std::env::current_dir()?.join("options.txt")),
|
||||
};
|
||||
// Scripted and frame-limited runs (the parity harnesses) see vanilla's
|
||||
// screens unless HORIZON_MENU_STYLE asks otherwise.
|
||||
if (options.frames.is_some() || options.control.is_some())
|
||||
&& std::env::var_os("HORIZON_MENU_STYLE").is_none()
|
||||
{
|
||||
horizon_client::ui_theme::set_style(horizon_client::ui_theme::MenuStyle::Classic);
|
||||
}
|
||||
if let Some(d) = options.distance_override {
|
||||
settings.render_distance = d;
|
||||
}
|
||||
@@ -12468,7 +12444,13 @@ fn start_game<'a>(
|
||||
game.mods.dev = game.options.dev_mods.clone();
|
||||
game.start_mods();
|
||||
}
|
||||
if let Some(path) = &game.options.control {
|
||||
if game.options.control.is_some() && game.settings.extras.no_ai {
|
||||
// No AI turns agent control off: the socket is never opened.
|
||||
log::warn!(
|
||||
"Horizon: control socket not opened: {}",
|
||||
horizon_core::no_ai::REFUSAL
|
||||
);
|
||||
} else if let Some(path) = &game.options.control {
|
||||
let server = horizon_client::control::Server::start(path)
|
||||
.map_err(|e| format!("control socket {}: {e}", path.display()))?;
|
||||
log::info!("Horizon: control socket {}", server.path().display());
|
||||
@@ -12549,12 +12531,6 @@ fn start_game<'a>(
|
||||
&game.options.resources,
|
||||
);
|
||||
title.last_server = game.settings.file.string("lastServer");
|
||||
// The launcher's opening, once per session and only in Horizon's style.
|
||||
if horizon_client::ui_theme::horizon() && game.options.frames.is_none() {
|
||||
title
|
||||
.opening
|
||||
.set(Some(horizon_client::front::Opening::new()));
|
||||
}
|
||||
game.title = Some(title);
|
||||
}
|
||||
}
|
||||
@@ -12641,6 +12617,7 @@ impl Loading {
|
||||
return;
|
||||
}
|
||||
};
|
||||
horizon_client::telemetry::note_display(&window);
|
||||
let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen);
|
||||
match loading_renderer(
|
||||
window.clone(),
|
||||
@@ -12912,7 +12889,6 @@ fn run_loading(
|
||||
pack_error: Option<String>,
|
||||
started: Instant,
|
||||
) -> Result<()> {
|
||||
horizon_client::ui_theme::load_preferences(&std::env::current_dir()?);
|
||||
let progress = Progress::new();
|
||||
let (receiver, loader) =
|
||||
startup_menu::spawn_loader(&options, &settings, &vanilla_root, started, &progress)?;
|
||||
|
||||
@@ -403,6 +403,7 @@ impl Game<'_> {
|
||||
Screen::Stats => "stats",
|
||||
Screen::Advancements => "advancements",
|
||||
Screen::WorldOptions => "world-options",
|
||||
Screen::Friends => "friends",
|
||||
Screen::CommandBlock => "command-block",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,303 +0,0 @@
|
||||
//! The live title backdrop (Menu style: Horizon): a frozen landscape that
|
||||
//! Horizon generates and renders itself behind the title screens, seen
|
||||
//! through a slow orbiting camera, falling snow, an overcast sky and the cold
|
||||
//! blur and grade of `gfx::PostGrade`. Nothing is bundled: the chunks come
|
||||
//! from the vanilla generator for a fixed seed and are cached in
|
||||
//! `saves/.horizon-title/backdrop` (no level.dat, so no world list entry).
|
||||
//! The ice-spikes spot is found once with `/locate biome`'s search and kept
|
||||
//! in `spot.txt` there. The generator is built and the spot found on a
|
||||
//! worker, so the title keeps drawing its panorama until both are ready.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
save::{Persistent, SaveDir},
|
||||
streaming::Streaming,
|
||||
vanillagen::VanillaTerrain,
|
||||
world::{Weather, World},
|
||||
};
|
||||
use horizon_core::biome::{BiomeZoom, obfuscate_seed};
|
||||
use std::{
|
||||
sync::{Arc, Mutex},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
/// The world the backdrop is cut from (HORIZON_BACKDROP_SEED overrides it).
|
||||
const SEED: i64 = 2_026_031_337;
|
||||
/// The biome the camera looks for.
|
||||
const BIOME: &str = "minecraft:ice_spikes";
|
||||
/// Late morning: the snow reads clearly; the grade (`PostGrade::FROST`) makes it cold.
|
||||
const DAY_TIME: i64 = 4_000;
|
||||
|
||||
/// The worker's result: the generator for [`SEED`], or why it failed.
|
||||
type Built = std::result::Result<Arc<VanillaTerrain>, String>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Backdrop {
|
||||
pub active: bool,
|
||||
/// The generator, once the worker has built it; taken when it is installed.
|
||||
terrain: Arc<Mutex<Option<Built>>>,
|
||||
/// The generator streams the backdrop's chunks.
|
||||
installed: bool,
|
||||
/// The search for the spot, then the spot (block x, z).
|
||||
spot: Arc<Mutex<Option<Option<(i32, i32)>>>>,
|
||||
centred: bool,
|
||||
/// Camera position once the ground under it has loaded.
|
||||
pub camera: Option<glam::DVec3>,
|
||||
pub ready: Option<Instant>,
|
||||
pub started: Option<Instant>,
|
||||
}
|
||||
fn seed() -> i64 {
|
||||
std::env::var("HORIZON_BACKDROP_SEED")
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(SEED)
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// How visible the live backdrop is (0 until its first chunks are drawn).
|
||||
pub(super) fn backdrop_fade(&self) -> f32 {
|
||||
let Some(at) = self.backdrop.ready else {
|
||||
return 0.0;
|
||||
};
|
||||
let x = (at.elapsed().as_secs_f32() / 1.6).clamp(0.0, 1.0);
|
||||
x * x * (3.0 - 2.0 * x)
|
||||
}
|
||||
/// Whether the frame should draw the backdrop world instead of the panorama.
|
||||
pub(super) fn backdrop_live(&self) -> bool {
|
||||
self.title.is_some() && self.backdrop.active && self.backdrop.camera.is_some()
|
||||
}
|
||||
/// The orbiting camera: position, yaw and pitch.
|
||||
pub(super) fn backdrop_view(&self) -> Option<(glam::DVec3, f32, f32)> {
|
||||
let c = self.backdrop.camera?;
|
||||
let t = self
|
||||
.backdrop
|
||||
.started
|
||||
.map_or(0.0, |s| s.elapsed().as_secs_f32());
|
||||
// A full turn in about six minutes.
|
||||
let yaw = (200.0 + t * 1.0) % 360.0;
|
||||
let pitch = 6.0 + (t * 0.05).sin() * 2.0;
|
||||
Some((c, yaw, pitch))
|
||||
}
|
||||
/// Called every frame while the title is up.
|
||||
pub(super) fn update_backdrop(&mut self) -> Result<()> {
|
||||
let wanted = self.pending_entry.is_none()
|
||||
&& self.title.is_some()
|
||||
&& horizon_client::ui_theme::horizon()
|
||||
&& self.world_renderer_ready
|
||||
&& self.renderer.is_some()
|
||||
&& self.options.frames.is_none();
|
||||
if !wanted {
|
||||
if self.backdrop.active && self.title.is_some() {
|
||||
self.stop_backdrop();
|
||||
}
|
||||
if self.title.is_none() && self.backdrop.active {
|
||||
// open_world / connect_server replaced the world and streaming.
|
||||
self.backdrop = Backdrop::default();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if !self.backdrop.active {
|
||||
self.start_backdrop()?;
|
||||
}
|
||||
if !self.backdrop.installed {
|
||||
let built = self
|
||||
.backdrop
|
||||
.terrain
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.take();
|
||||
match built {
|
||||
// Still building: the panorama stays up.
|
||||
None => return Ok(()),
|
||||
Some(Ok(terrain)) => self.install_backdrop(terrain)?,
|
||||
Some(Err(e)) => {
|
||||
// The panorama stays up for good.
|
||||
log::warn!("Horizon: title backdrop: {e}");
|
||||
self.backdrop.installed = true;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
let found = *self.backdrop.spot.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(Some((x, z))) = found else {
|
||||
return Ok(());
|
||||
};
|
||||
if !self.backdrop.centred {
|
||||
self.backdrop.centred = true;
|
||||
self.streaming.center = (x >> 4, z >> 4);
|
||||
self.streaming.paused = false;
|
||||
}
|
||||
self.update_world();
|
||||
if self.backdrop.camera.is_none()
|
||||
&& (-2..=2)
|
||||
.all(|dz| (-2..=2).all(|dx| self.streaming.is_lit((x >> 4) + dx, (z >> 4) + dz)))
|
||||
{
|
||||
// Above the tallest block nearby, so no spike pokes through the lens.
|
||||
let mut top = 64;
|
||||
for dz in (-12..=12).step_by(3) {
|
||||
for dx in (-12..=12).step_by(3) {
|
||||
if let Some(y) = self.surface_y(x + dx, z + dz) {
|
||||
top = top.max(y);
|
||||
}
|
||||
}
|
||||
}
|
||||
let ground = self.surface_y(x, z).unwrap_or(top);
|
||||
let y = (ground + 22).max(top + 4);
|
||||
self.backdrop.camera = Some(glam::DVec3::new(
|
||||
f64::from(x) + 0.5,
|
||||
f64::from(y),
|
||||
f64::from(z) + 0.5,
|
||||
));
|
||||
}
|
||||
if self.backdrop.camera.is_some()
|
||||
&& self.backdrop.ready.is_none()
|
||||
&& self
|
||||
.renderer
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.section_count() > 40)
|
||||
{
|
||||
self.backdrop.ready = Some(Instant::now());
|
||||
log::info!(
|
||||
"Horizon: title backdrop ready; world rest ready: {}",
|
||||
self.res.rest.get().is_some()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The world tick of the backdrop: time passes for clouds and snow only.
|
||||
pub(super) fn tick_backdrop(&mut self) {
|
||||
if self.backdrop.active {
|
||||
self.world.game_time += 1;
|
||||
// The snow's fall follows the client tick counter.
|
||||
self.ticks += 1;
|
||||
}
|
||||
}
|
||||
fn surface_y(&self, x: i32, z: i32) -> Option<i32> {
|
||||
let air = self.res.facts().air;
|
||||
(-60..320).rev().find(|&y| self.world.block(x, y, z) != air)
|
||||
}
|
||||
/// Start building the generator and finding the spot on a worker
|
||||
/// (`VanillaTerrain::new` takes seconds on a cold cache).
|
||||
fn start_backdrop(&mut self) -> Result<()> {
|
||||
log::info!(
|
||||
"Horizon: starting title backdrop after {} ms",
|
||||
self.started.elapsed().as_millis()
|
||||
);
|
||||
let seed = seed();
|
||||
let dir = self.backdrop_root()?.join(format!("{seed}"));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
// The streaming is replaced once the generator is built.
|
||||
self.streaming.paused = true;
|
||||
let mut world = World::new(self.res.facts().air, seed);
|
||||
world.day_time = DAY_TIME;
|
||||
world.game_time = 6000;
|
||||
// Light snow: the weather renders as snow in frozen biomes.
|
||||
world.weather = Weather {
|
||||
clear_time: 0,
|
||||
rain_time: i32::MAX / 2,
|
||||
thunder_time: i32::MAX / 2,
|
||||
raining: true,
|
||||
thundering: false,
|
||||
rain_level: (0.35, 0.35),
|
||||
thunder_level: (0.0, 0.0),
|
||||
};
|
||||
self.world = world;
|
||||
self.dim = super::Dim::Overworld;
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.clear_sections();
|
||||
}
|
||||
self.backdrop = Backdrop {
|
||||
active: true,
|
||||
started: Some(Instant::now()),
|
||||
..Default::default()
|
||||
};
|
||||
let (terrain, spot) = (self.backdrop.terrain.clone(), self.backdrop.spot.clone());
|
||||
let worldgen = self.options.resources.join("worldgen");
|
||||
let registry = self.pack.assets.registry;
|
||||
let biomes = self.res.biomes().clone();
|
||||
let cache = dir.join("spot.txt");
|
||||
std::thread::Builder::new()
|
||||
.name("horizon-backdrop".into())
|
||||
.spawn(move || {
|
||||
let built = Instant::now();
|
||||
let inner = match VanillaTerrain::new(&worldgen, registry, &biomes, seed) {
|
||||
Ok(t) => Arc::new(t),
|
||||
Err(e) => {
|
||||
*terrain.lock().unwrap_or_else(|e| e.into_inner()) =
|
||||
Some(Err(e.to_string()));
|
||||
return;
|
||||
}
|
||||
};
|
||||
log::info!(
|
||||
"Horizon: title backdrop generator built in {} ms",
|
||||
built.elapsed().as_millis()
|
||||
);
|
||||
*terrain.lock().unwrap_or_else(|e| e.into_inner()) = Some(Ok(inner.clone()));
|
||||
// Find (or recall) the spot.
|
||||
let known = std::fs::read_to_string(&cache).ok().and_then(|t| {
|
||||
let mut it = t.split_whitespace().map(|v| v.parse::<i32>().ok());
|
||||
Some((it.next()??, it.next()??))
|
||||
});
|
||||
let found = known.or_else(|| {
|
||||
let allowed = |name: &str| name == BIOME;
|
||||
let search = horizon_world::worldgen::generator::BiomeSearch {
|
||||
allowed: &allowed,
|
||||
origin: [0, 64, 0],
|
||||
radius: 6400,
|
||||
horizontal: 32,
|
||||
vertical: 64,
|
||||
min_y: -64,
|
||||
max_y: 320,
|
||||
};
|
||||
let found = inner.find_closest_biome(&search);
|
||||
log::info!("Horizon: title backdrop: {BIOME} at {found:?}");
|
||||
let (_, p) = found?;
|
||||
let _ = std::fs::write(&cache, format!("{} {}\n", p[0], p[2]));
|
||||
Some((p[0], p[2]))
|
||||
});
|
||||
*spot.lock().unwrap_or_else(|e| e.into_inner()) =
|
||||
Some(Some(found.unwrap_or((0, 0))));
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
fn backdrop_root(&self) -> Result<std::path::PathBuf> {
|
||||
Ok(std::env::current_dir()?
|
||||
.join("saves")
|
||||
.join(".horizon-title")
|
||||
.join("backdrop"))
|
||||
}
|
||||
/// The built generator streams the backdrop's chunks.
|
||||
fn install_backdrop(&mut self, inner: Arc<VanillaTerrain>) -> Result<()> {
|
||||
let seed = seed();
|
||||
let save = Arc::new(SaveDir::new(self.backdrop_root()?.join(format!("{seed}"))));
|
||||
let (res, pack) = (&*self.res, &self.pack);
|
||||
let mut streaming = Streaming::new(
|
||||
Arc::new(Persistent {
|
||||
inner,
|
||||
save: save.clone(),
|
||||
registry: pack.assets.clone(),
|
||||
biomes: res.biomes().clone(),
|
||||
}),
|
||||
pack.context.clone(),
|
||||
res.threads().min(6),
|
||||
);
|
||||
streaming.radius = self.settings.render_distance.clamp(4, 10);
|
||||
streaming.biome_blend = self.settings.biome_blend;
|
||||
streaming.smooth_lighting = self.settings.smooth_lighting;
|
||||
streaming.cutout_leaves = self.settings.cutout_leaves;
|
||||
streaming.cull_leaves = self.settings.horizon.cull_leaves;
|
||||
streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed));
|
||||
streaming.paused = true;
|
||||
self.streaming = streaming;
|
||||
self.save = save;
|
||||
self.backdrop.installed = true;
|
||||
Ok(())
|
||||
}
|
||||
fn stop_backdrop(&mut self) {
|
||||
self.streaming.paused = true;
|
||||
self.world = World::new(self.res.facts().air, 0);
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.clear_sections();
|
||||
}
|
||||
self.backdrop = Backdrop::default();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -165,6 +165,9 @@ impl Game<'_> {
|
||||
if let Some(value) = self.events_command(&words, reply)? {
|
||||
return Ok(value);
|
||||
}
|
||||
if let Some(value) = self.saves_control(&words, line, reply)? {
|
||||
return Ok(value);
|
||||
}
|
||||
if let Some(value) = self.options_control(&words, line)? {
|
||||
return Ok(Some(value));
|
||||
}
|
||||
@@ -192,6 +195,7 @@ impl Game<'_> {
|
||||
.chain(super::ui_control::HELP)
|
||||
.chain(super::options::CONTROL_HELP)
|
||||
.chain(super::events::HELP)
|
||||
.chain(super::saves_control::HELP)
|
||||
.chain(super::pad::HELP)
|
||||
.collect::<Vec<_>>() }))),
|
||||
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
|
||||
@@ -564,6 +568,8 @@ impl Game<'_> {
|
||||
"graphics" => Page::Graphics,
|
||||
"graphics-advanced" => Page::GraphicsAdvanced,
|
||||
"extras" => Page::Extras,
|
||||
"horizon" => Page::Horizon,
|
||||
"shader-packs" => Page::ShaderPacks,
|
||||
other => return Err(format!("unknown options page {other}").into()),
|
||||
};
|
||||
if self.screen == Screen::Playing && self.title.is_none() {
|
||||
@@ -736,6 +742,7 @@ impl Game<'_> {
|
||||
Screen::Stats => "stats",
|
||||
Screen::Advancements => "advancements",
|
||||
Screen::WorldOptions => "world-options",
|
||||
Screen::Friends => "friends",
|
||||
Screen::CommandBlock => "command-block",
|
||||
}
|
||||
}
|
||||
@@ -903,7 +910,7 @@ impl Game<'_> {
|
||||
"streaming": self.streaming.stages().into_iter().map(|(k, v)| (k.to_string(), v.into())).collect::<serde_json::Map<_, _>>(),
|
||||
"dirty_light": self.world.dirty_light.len(),
|
||||
"renderer": renderer,
|
||||
"display": self.window.as_ref().and_then(|w| w.current_monitor()).map(|m| json!({
|
||||
"display": self.window.as_deref().and_then(horizon_client::telemetry::monitor).map(|m| json!({
|
||||
"width": m.size().width,
|
||||
"height": m.size().height,
|
||||
"scale": m.scale_factor(),
|
||||
@@ -926,6 +933,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
|
||||
|
||||
@@ -330,6 +330,10 @@ impl Game<'_> {
|
||||
"held": m.extra.main_hand.as_deref(),
|
||||
"mount": m.extra.mount,
|
||||
"rider": m.extra.rider,
|
||||
// A player's input this tick, and whether it steers.
|
||||
"ridden": m.rider.map(|r| r.steer),
|
||||
"controlled": horizon_client::mobs::equine::controlled(m),
|
||||
"saddled": m.extra.saddled,
|
||||
"enchants": horizon_client::mobs::gear::gear(m).map(|g| g.slots.iter().map(|s| s.iter().map(|(e, l)| format!("{e}:{l}")).collect::<Vec<_>>()).collect::<Vec<_>>()),
|
||||
"ints": m.extra.ints,
|
||||
"pois": [m.extra.home, m.extra.bed, m.extra.meeting],
|
||||
@@ -500,7 +504,7 @@ impl Game<'_> {
|
||||
// The level random, lent to the mobs (brain behaviours draw from
|
||||
// it) and taken back after their ticks.
|
||||
let mut scratch = self.world.random.clone();
|
||||
let mut pushes = Vec::new();
|
||||
let mut pushes = horizon_client::mobs::PendingPushes::default();
|
||||
let mut keep = Vec::with_capacity(mobs.len());
|
||||
let mut grid =
|
||||
horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds));
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Play with friends, host side: "Invite friends" opens the world to LAN if
|
||||
//! Play with friends, host side: "Start Sharing" on the Play with Friends
|
||||
//! screen (`friends_screen`, the pause menu's Friends button) opens the world to LAN if
|
||||
//! it isn't (with Open to LAN's defaults) and shares that port behind an
|
||||
//! invite code (horizon-friends). The code holds this computer's addresses
|
||||
//! and the key, so friends join with no server of ours; a relay the player
|
||||
@@ -6,7 +7,12 @@
|
||||
//! LAN one, unchanged: tunnelled guests are LAN guests that connect from the
|
||||
//! loopback address.
|
||||
use super::{Game, lan::LanSettings};
|
||||
use horizon_client::{Result, front::FriendsView, text::Text};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
friends_screen::{self, Action, FriendsView},
|
||||
hud::HudBatch,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_friends::{Host, HostConfig, HostEvent, PathMode, host::DEFAULT_PORT, reach, stun};
|
||||
use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -52,10 +58,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 {
|
||||
@@ -153,7 +161,7 @@ impl Game<'_> {
|
||||
}
|
||||
if announce {
|
||||
self.system_message(Text::literal(
|
||||
"Your invite code is ready in the pause menu: copy it and send it to your friends.",
|
||||
"Your invite code is ready: Game Menu, Play with Friends. Copy it and send it to your friends.",
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -169,16 +177,55 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the pause menu shows.
|
||||
/// Play with Friends. The world is paused under it in singleplayer, so
|
||||
/// new codes and sessions are read while it is drawn.
|
||||
pub(super) fn draw_friends_screen(&mut self, batch: &mut HudBatch) {
|
||||
self.tick_friends();
|
||||
let view = self.friends_view();
|
||||
friends_screen::draw(batch, &self.gui.atlas, self.cursor, &view, true);
|
||||
}
|
||||
pub(super) fn friends_screen_click(&mut self) {
|
||||
let view = self.friends_view();
|
||||
let Some(action) =
|
||||
friends_screen::click(&self.gui.atlas, self.gui_size(), self.cursor, &view)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.audio.play_button_click();
|
||||
match action {
|
||||
Action::Share => {
|
||||
if let Err(e) = self.friends_start() {
|
||||
self.system_message(Text::literal(format!("Couldn't share the world: {e}")));
|
||||
}
|
||||
}
|
||||
Action::Copy => self.friends_copy(),
|
||||
Action::Stop => self.friends_stop(),
|
||||
// The system browser, as the Shader Packs page opens its folder.
|
||||
Action::Help => {
|
||||
if let Some(url) = &view.help {
|
||||
super::packs::open_folder(std::path::Path::new(url));
|
||||
}
|
||||
}
|
||||
Action::Done => self.screen = super::Screen::Paused,
|
||||
}
|
||||
}
|
||||
|
||||
/// What Play with Friends 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()
|
||||
};
|
||||
};
|
||||
|
||||
@@ -6,10 +6,9 @@
|
||||
//! the world's options) with [`Integrated::call`], as vanilla's client calls
|
||||
//! into its `IntegratedServer`.
|
||||
//!
|
||||
//! Opt-in again (`--server-thread` or `HORIZON_SERVER_THREAD=1`): it was the
|
||||
//! default for one day, but a server's players can't board, ride or hit
|
||||
//! boats and minecarts yet (#1222), and single player's window is one of
|
||||
//! them here.
|
||||
//! On by default. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` runs
|
||||
//! the world in the frame instead (the escape hatch while the network
|
||||
//! player's side catches up with the in-frame one).
|
||||
use super::{
|
||||
Game, Options, PackResources, Resources, UiResources,
|
||||
lan::{LanSettings, Owner},
|
||||
|
||||
@@ -800,6 +800,16 @@ impl Game<'_> {
|
||||
self.send_admin_feedback(&mut host, None);
|
||||
}
|
||||
let state = self.lan_host_state(&host);
|
||||
// An animal whose rider left the game (or the level) stops taking
|
||||
// its input.
|
||||
for m in &mut self.mobs {
|
||||
if m.rider.is_some()
|
||||
&& self.riding != Some(m.id)
|
||||
&& !host.hub.guests.iter().any(|g| g.vehicle == Some(m.id))
|
||||
{
|
||||
m.rider = None;
|
||||
}
|
||||
}
|
||||
// A dedicated server runs the hub without a host player.
|
||||
if state.is_some() || host.hub.config.dedicated {
|
||||
let has_guests = !host.hub.guests.is_empty();
|
||||
@@ -807,7 +817,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();
|
||||
|
||||
@@ -49,12 +49,16 @@ pub(super) struct GuestPlay {
|
||||
/// Swings the guest's actions started this tick, for the players around
|
||||
/// (`LivingEntity.swing` sends ClientboundSwingAnimationPacket).
|
||||
swings: u32,
|
||||
/// The guest's riding jump charge (`LocalPlayer.jumpRidingTicks`).
|
||||
mount: super::mounts::MountState,
|
||||
/// The trading screen the guest has open.
|
||||
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
|
||||
/// The inventory menu and the crafting table the guest crafts in.
|
||||
pub(super) crafting: super::lan_crafting::GuestCrafting,
|
||||
/// The workstation menu the guest has open (game/lan_stations.rs).
|
||||
pub(super) station: Option<super::lan_stations::GuestStation>,
|
||||
/// The mount inventory the guest has open (game/lan_mount_menu.rs).
|
||||
pub(super) mount_window: Option<super::lan_mount_menu::GuestMount>,
|
||||
/// The lectern the guest reads (game/lan_stations.rs).
|
||||
pub(super) lectern: Option<super::lan_stations::GuestLectern>,
|
||||
/// What the guest's body was given for its effects and enchantments.
|
||||
@@ -289,10 +293,12 @@ impl Game<'_> {
|
||||
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
|
||||
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
|
||||
let swing = std::mem::replace(&mut self.swing, play.swing);
|
||||
std::mem::swap(&mut self.mount, &mut play.mount);
|
||||
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 +473,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);
|
||||
@@ -477,6 +483,7 @@ impl Game<'_> {
|
||||
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
|
||||
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
|
||||
play.swing = std::mem::replace(&mut self.swing, swing);
|
||||
std::mem::swap(&mut self.mount, &mut play.mount);
|
||||
self.container = container;
|
||||
self.screen = screen;
|
||||
self.sign_edit = host_sign;
|
||||
@@ -488,9 +495,16 @@ impl Game<'_> {
|
||||
_ => None,
|
||||
};
|
||||
self.command_block_screen = host_command_block;
|
||||
self.mount_menu = host_mount_menu;
|
||||
// A mount inventory the guest's action opened (shift + use, or the
|
||||
// inventory key while riding).
|
||||
let guest_mount = std::mem::replace(&mut self.mount_menu, host_mount_menu).opened_mob();
|
||||
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 +563,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));
|
||||
}
|
||||
}
|
||||
@@ -589,6 +620,9 @@ impl Game<'_> {
|
||||
if opened_table {
|
||||
self.lan_open_crafting(host, conn);
|
||||
}
|
||||
if let Some(mob) = guest_mount {
|
||||
self.lan_open_mount(host, conn, mob);
|
||||
}
|
||||
}
|
||||
|
||||
/// `ServerLevel.players()` in turn: the host's own player, then each
|
||||
@@ -900,16 +934,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) {
|
||||
@@ -938,6 +978,14 @@ impl Game<'_> {
|
||||
S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {}
|
||||
S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {}
|
||||
S::ContainerClick(p) if self.lan_lectern_click(host, conn, &p) => {}
|
||||
S::ContainerClick(p) if self.lan_mount_click(host, conn, &p) => {}
|
||||
// ServerboundPlayerCommandPacket OPEN_INVENTORY: the ridden
|
||||
// mount's inventory (`HasCustomInventoryScreen`).
|
||||
S::PlayerCommand(p) if p.action == 5 => {
|
||||
self.as_guest(host, conn, |g| {
|
||||
g.open_ridden_mount_menu();
|
||||
});
|
||||
}
|
||||
S::ContainerButtonClick(p) => {
|
||||
self.lan_station_button(host, conn, p.container, p.button);
|
||||
}
|
||||
@@ -955,7 +1003,8 @@ impl Game<'_> {
|
||||
}
|
||||
S::ContainerClose(p)
|
||||
if self.lan_crafting_closed(host, conn, Some(p.container))
|
||||
|| self.lan_station_closed(host, conn, Some(p.container)) =>
|
||||
|| self.lan_station_closed(host, conn, Some(p.container))
|
||||
|| self.lan_mount_closed(host, conn, Some(p.container)) =>
|
||||
{
|
||||
let g = &mut host.hub.guests[gi];
|
||||
if let Some(c) = g.carried.take() {
|
||||
@@ -1147,19 +1196,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 +1279,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| {
|
||||
@@ -1475,6 +1544,7 @@ impl Game<'_> {
|
||||
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
|
||||
self.lan_merchant_tick(host);
|
||||
self.lan_stations_tick(host);
|
||||
self.tick_lan_mount_menus(host);
|
||||
self.announce_guest_advancements(host);
|
||||
let conns: Vec<u32> = host
|
||||
.hub
|
||||
@@ -1676,6 +1746,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;
|
||||
};
|
||||
@@ -1730,6 +1801,13 @@ impl Game<'_> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// A ServerPlayer travels on the server too
|
||||
// (MoveSimulationType.AUTHORITATIVE_SIDE_AND_SERVER), so every tick
|
||||
// on a ladder or vine LivingEntity.handleOnClimbable resets its fall
|
||||
// distance: climbing down doesn't hurt where it lands (#1255).
|
||||
if w.climbable().unwrap_or(false) {
|
||||
w.player.fall_distance = 0.0;
|
||||
}
|
||||
let _ = w.tick_environment_damage();
|
||||
let _ = w.apply_fire_contact();
|
||||
let _ = w.server_hazards_tick(in_wall);
|
||||
|
||||
@@ -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,222 @@
|
||||
//! The horse inventory for a server's players (`ServerPlayer.openHorseInventory`):
|
||||
//! shift + use on a tamed horse, donkey, mule, camel or llama, or the
|
||||
//! inventory key while riding one (`ServerboundPlayerCommandPacket`
|
||||
//! OPEN_INVENTORY), opens `HorseInventoryMenu` over the mount with
|
||||
//! `ClientboundMountScreenOpenPacket`. Clicks run on the menu engine
|
||||
//! (`Kind::Mount`) with the mount's saddle, body item and chest copied in and
|
||||
//! written back, and the slots go to the client after each change, as
|
||||
//! `broadcastChanges` does.
|
||||
use super::{Game, lan::LanHost, lan_crafting::input};
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
menu::{Kind, Menu},
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
|
||||
/// A guest's open mount menu.
|
||||
pub(super) struct GuestMount {
|
||||
window: i32,
|
||||
mob: u32,
|
||||
columns: usize,
|
||||
state: i32,
|
||||
/// The menu's slots and the carried stack the client was last sent.
|
||||
sent: Option<(Vec<Option<ItemStack>>, Option<ItemStack>)>,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `ServerPlayer.openHorseInventory` for mount `mob`: the open menu
|
||||
/// closes, the client gets the mount screen and the menu's slots.
|
||||
pub(super) fn lan_open_mount(&mut self, host: &mut LanHost, conn: u32, mob: u32) {
|
||||
let Some(index) = self.mobs.iter().position(|m| m.id == mob) else {
|
||||
return;
|
||||
};
|
||||
let columns = super::mount_menu::mount_columns(&self.mobs[index]);
|
||||
self.lan_mount_closed(host, conn, None);
|
||||
self.lan_station_closed(host, conn, None);
|
||||
self.lan_crafting_closed(host, conn, None);
|
||||
self.guest_container_closed(host, conn);
|
||||
let Some(window) = host.hub.open_mount_window(conn, columns as i32, mob as i32) else {
|
||||
return;
|
||||
};
|
||||
host.play.entry(conn).or_default().mount_window = Some(GuestMount {
|
||||
window,
|
||||
mob,
|
||||
columns,
|
||||
state: 0,
|
||||
sent: None,
|
||||
});
|
||||
self.lan_send_mount(host, conn);
|
||||
}
|
||||
|
||||
/// `HorseInventoryMenu` over mount `index`, with the player's inventory
|
||||
/// loaded by the caller.
|
||||
fn mount_engine_menu(&self, index: usize, columns: usize) -> Menu {
|
||||
let env = self.menu_env();
|
||||
let mut menu = Menu::new(Kind::Mount(columns));
|
||||
menu.mount = Some(self.mobs[index].kind.id.to_string());
|
||||
let (saddle, body, items) = self.mount_contents(index);
|
||||
menu.set_slot(&env, 0, saddle);
|
||||
menu.set_slot(&env, 1, body.flatten());
|
||||
for (k, item) in items.into_iter().take(columns * 3).enumerate() {
|
||||
menu.set_slot(&env, 2 + k, item);
|
||||
}
|
||||
menu
|
||||
}
|
||||
|
||||
/// The menu's slots (the mount's, then the inventory and the hotbar)
|
||||
/// and the carried stack, sent when they changed since the last time.
|
||||
fn lan_send_mount(&mut self, host: &mut LanHost, conn: u32) {
|
||||
let Some(gm) = host.play.get(&conn).and_then(|p| p.mount_window.as_ref()) else {
|
||||
return;
|
||||
};
|
||||
let (mob, columns) = (gm.mob, gm.columns);
|
||||
let Some(index) = self.mobs.iter().position(|m| m.id == mob) else {
|
||||
return;
|
||||
};
|
||||
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
|
||||
return;
|
||||
};
|
||||
let (saddle, body, items) = self.mount_contents(index);
|
||||
let mut slots = vec![saddle, body.flatten()];
|
||||
slots.extend(items.into_iter().take(columns * 3));
|
||||
slots.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone()));
|
||||
let carried = g.carried.clone();
|
||||
let now = Some((slots, carried));
|
||||
let Some(gm) = host
|
||||
.play
|
||||
.get_mut(&conn)
|
||||
.and_then(|p| p.mount_window.as_mut())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if gm.sent == now {
|
||||
return;
|
||||
}
|
||||
gm.state = (gm.state + 1) & 0x7FFF;
|
||||
let (window, state) = (gm.window, gm.state);
|
||||
let (slots, carried) = now.clone().unwrap_or_default();
|
||||
gm.sent = now;
|
||||
let content = C::ContainerSetContent(play::ContainerSetContent {
|
||||
container: window,
|
||||
state,
|
||||
items: slots.iter().map(|s| host.hub.stack(s)).collect(),
|
||||
carried: host.hub.stack(&carried),
|
||||
});
|
||||
host.hub.send_to(conn, &content);
|
||||
}
|
||||
|
||||
/// A click on the guest's mount window; false for other windows.
|
||||
pub(super) fn lan_mount_click(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
p: &play::ContainerClick,
|
||||
) -> bool {
|
||||
let Some((mob, columns)) = host
|
||||
.play
|
||||
.get(&conn)
|
||||
.and_then(|pl| pl.mount_window.as_ref())
|
||||
.filter(|m| m.window == p.container)
|
||||
.map(|m| (m.mob, m.columns))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
|
||||
&& !host.hub.guests[gi].spectator()
|
||||
&& let Some(index) = self.mobs.iter().position(|m| m.id == mob)
|
||||
{
|
||||
let mut menu = self.mount_engine_menu(index, columns);
|
||||
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
|
||||
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
|
||||
});
|
||||
self.lan_mount_store(index, columns, &menu);
|
||||
}
|
||||
// The client is told what the server has, whatever it predicted.
|
||||
if let Some(gm) = host
|
||||
.play
|
||||
.get_mut(&conn)
|
||||
.and_then(|pl| pl.mount_window.as_mut())
|
||||
{
|
||||
gm.sent = None;
|
||||
}
|
||||
self.lan_send_mount(host, conn);
|
||||
true
|
||||
}
|
||||
|
||||
/// The engine menu's mount slots back on mount `index`.
|
||||
fn lan_store_slots(menu: &Menu, columns: usize) -> Vec<Option<ItemStack>> {
|
||||
(0..columns * 3)
|
||||
.map(|k| menu.slot(2 + k).cloned())
|
||||
.collect()
|
||||
}
|
||||
fn lan_mount_store(&mut self, index: usize, columns: usize, menu: &Menu) {
|
||||
let (_, body, _) = self.mount_contents(index);
|
||||
let body = body.map(|_| menu.slot(1).cloned());
|
||||
let items = Self::lan_store_slots(menu, columns);
|
||||
self.mount_store(index, menu.slot(0).cloned(), body, items);
|
||||
}
|
||||
|
||||
/// `AbstractContainerMenu.removed` of the guest's mount menu (`window`;
|
||||
/// None closes it whichever it is): the carried stack goes back to the
|
||||
/// inventory. False when no such window is open.
|
||||
pub(super) fn lan_mount_closed(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
window: Option<i32>,
|
||||
) -> bool {
|
||||
let closed = host
|
||||
.play
|
||||
.get_mut(&conn)
|
||||
.and_then(|p| {
|
||||
p.mount_window
|
||||
.take_if(|m| window.is_none_or(|w| m.window == w))
|
||||
})
|
||||
.is_some();
|
||||
if closed
|
||||
&& let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
|
||||
&& let Some(carried) = host.hub.guests[gi].carried.take()
|
||||
{
|
||||
self.lan_place_back(host, gi, vec![carried]);
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// Each tick: a mount menu whose mount died or is out of reach closes
|
||||
/// (`AbstractMountInventoryMenu.stillValid`: alive, within the entity
|
||||
/// interaction range plus 4 of the eyes), and the others follow the
|
||||
/// mount's and the inventory's slots.
|
||||
pub(super) fn tick_lan_mount_menus(&mut self, host: &mut LanHost) {
|
||||
let open: Vec<(u32, u32, i32)> = host
|
||||
.play
|
||||
.iter()
|
||||
.filter_map(|(c, p)| p.mount_window.as_ref().map(|m| (*c, m.mob, m.window)))
|
||||
.collect();
|
||||
for (conn, mob, window) in open {
|
||||
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
|
||||
continue;
|
||||
};
|
||||
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
|
||||
let valid = self.mobs.iter().find(|m| m.id == mob).is_some_and(|m| {
|
||||
let (w, h) = (f64::from(m.width()) / 2.0, f64::from(m.height()));
|
||||
let p = [m.position.x, m.position.y, m.position.z];
|
||||
let lo = [p[0] - w, p[1], p[2] - w];
|
||||
let hi = [p[0] + w, p[1] + h, p[2] + w];
|
||||
let d: f64 = (0..3)
|
||||
.map(|k| (eye[k] - eye[k].clamp(lo[k], hi[k])).powi(2))
|
||||
.sum();
|
||||
// Player.ENTITY_INTERACTION_RANGE 3, plus 4.
|
||||
m.alive() && d < 7.0 * 7.0
|
||||
});
|
||||
if valid {
|
||||
self.lan_send_mount(host, conn);
|
||||
} else {
|
||||
self.lan_mount_closed(host, conn, Some(window));
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::ContainerClose(play::ContainerClose { container: window }),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! 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,
|
||||
sprint: flags & 64 != 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);
|
||||
let mount = self.mobs.iter().any(|m| m.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 && !mount) {
|
||||
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. An animal takes the rider's input
|
||||
// for its own tick (`travelRidden`), or lets it off.
|
||||
if !game.tick_cart_riding(keys) && game.tick_mount_riding(keys) {
|
||||
game.riding?;
|
||||
game.position_rider();
|
||||
}
|
||||
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)
|
||||
});
|
||||
if let Some(p) = at {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
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;
|
||||
return;
|
||||
}
|
||||
// An animal: the rider sits where `positionRider` puts it.
|
||||
let seat = self.as_guest(host, conn, |game| {
|
||||
game.position_rider();
|
||||
game.player
|
||||
.as_ref()
|
||||
.map(|p| [p.position.x, p.position.y, p.position.z])
|
||||
});
|
||||
if let Some(Some(at)) = seat {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
g.previous_position = g.position;
|
||||
g.position = at;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +93,8 @@ impl Game<'_> {
|
||||
return false;
|
||||
}
|
||||
if tamed && sneaking {
|
||||
// The horse inventory screen is not available yet.
|
||||
// AbstractHorse.openCustomInventoryScreen.
|
||||
self.open_mount_menu(index);
|
||||
return true;
|
||||
}
|
||||
let m = &self.mobs[index];
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
//! The horse inventory (`HorseInventoryMenu`, `HorseInventoryScreen`): the
|
||||
//! saddle and body armour slots, the 3x5 chest of donkeys and mules and the
|
||||
//! mount drawn following the cursor. It opens with E while riding a tamed
|
||||
//! mount or with shift + use on a tamed one.
|
||||
//! saddle and body armour slots (a llama's carpet), the chest of donkeys,
|
||||
//! mules and llamas and the mount drawn following the cursor. It opens with
|
||||
//! E while riding a tamed mount or with shift + use on a tamed one. On a
|
||||
//! server the screen shows the server's menu (`ClientboundMountScreenOpenPacket`)
|
||||
//! and its clicks go out as container clicks; a server's players get theirs
|
||||
//! from game/lan_mount_menu.rs.
|
||||
use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
hud::{HudBatch, rgba},
|
||||
items::ItemStack,
|
||||
mobs::{Mob, Species, equine},
|
||||
mobs::{Mob, Species, equine, llama},
|
||||
};
|
||||
|
||||
/// Menu slot ids: the saddle, the body armour and the chest from 710.
|
||||
@@ -17,11 +20,43 @@ pub(super) const CHEST: usize = 710;
|
||||
const CHEST_SIZE: usize = 15;
|
||||
const COLUMNS: usize = 5;
|
||||
|
||||
/// `AbstractHorse.getInventoryColumns`: five for a donkey's or mule's chest,
|
||||
/// a llama's strength for its chest, else none.
|
||||
pub(super) fn mount_columns(m: &Mob) -> usize {
|
||||
let species = m.species();
|
||||
if llama::is_llama(species) {
|
||||
llama::inventory_columns(m).clamp(0, 5) as usize
|
||||
} else if m.extra.chested && matches!(species, Species::Donkey | Species::Mule) {
|
||||
COLUMNS
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
/// Whether the mount has a horse inventory (`AbstractHorse`).
|
||||
pub(super) fn has_mount_menu(species: Species) -> bool {
|
||||
equine::is_equine(species) || llama::is_llama(species)
|
||||
}
|
||||
/// The saddle slot is active (`canUseSlot(SADDLE)` and `CAN_EQUIP_SADDLE`):
|
||||
/// not on llamas.
|
||||
fn shows_saddle(species: Species) -> bool {
|
||||
!llama::is_llama(species)
|
||||
}
|
||||
/// The body slot is active: horse armour, or a llama's carpet.
|
||||
fn shows_body(species: Species) -> bool {
|
||||
can_wear_horse_armor(species) || llama::is_llama(species)
|
||||
}
|
||||
|
||||
/// The open mount menu: copies of the mount's slots, written back on every change.
|
||||
#[derive(Default)]
|
||||
pub(super) struct MountMenu {
|
||||
open: Option<Open>,
|
||||
}
|
||||
impl MountMenu {
|
||||
/// The mount whose menu is open.
|
||||
pub(super) fn opened_mob(&self) -> Option<u32> {
|
||||
self.open.as_ref().map(|o| o.mob)
|
||||
}
|
||||
}
|
||||
struct Open {
|
||||
mob: u32,
|
||||
species: Species,
|
||||
@@ -40,6 +75,9 @@ fn can_wear_horse_armor(species: Species) -> bool {
|
||||
}
|
||||
/// Whether `item` fits the body slot of the species (`isEquippableInSlot`).
|
||||
fn body_armor_fits(species: Species, item: &str) -> bool {
|
||||
if llama::is_llama(species) {
|
||||
return item.ends_with("_carpet");
|
||||
}
|
||||
can_wear_horse_armor(species) && item.ends_with("_horse_armor")
|
||||
}
|
||||
|
||||
@@ -55,18 +93,16 @@ impl Game<'_> {
|
||||
pub(super) fn open_mount_menu(&mut self, index: usize) {
|
||||
let m = &self.mobs[index];
|
||||
let species = m.species();
|
||||
if !equine::is_equine(species) {
|
||||
if !has_mount_menu(species) {
|
||||
return;
|
||||
}
|
||||
let chested = m.extra.chested && matches!(species, Species::Donkey | Species::Mule);
|
||||
let columns = if chested { COLUMNS } else { 0 };
|
||||
let mut items = m.extra.items.clone();
|
||||
items.resize(CHEST_SIZE, None);
|
||||
let show_armor = can_wear_horse_armor(species);
|
||||
let show_armor = shows_body(species);
|
||||
self.mount_menu.open = Some(Open {
|
||||
mob: m.id,
|
||||
species,
|
||||
columns,
|
||||
columns: mount_columns(m),
|
||||
saddle: m.saddle_item(),
|
||||
armor: m
|
||||
.extra
|
||||
@@ -75,10 +111,40 @@ impl Game<'_> {
|
||||
.filter(|_| show_armor)
|
||||
.map(|i| ItemStack::new(i, 1)),
|
||||
items,
|
||||
show_saddle: true,
|
||||
show_saddle: shows_saddle(species),
|
||||
show_armor,
|
||||
});
|
||||
self.carried = None;
|
||||
self.show_mount_menu();
|
||||
}
|
||||
/// `ClientPacketListener.handleMountScreenOpen`: a server's horse
|
||||
/// inventory over mount `entity`, its slots to come in the menu's content.
|
||||
pub(super) fn open_remote_mount_menu(&mut self, entity: u32, columns: usize) -> bool {
|
||||
let Some(species) = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == entity)
|
||||
.map(Mob::species)
|
||||
.filter(|s| has_mount_menu(*s))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
self.mount_menu.open = Some(Open {
|
||||
mob: entity,
|
||||
species,
|
||||
columns: columns.min(COLUMNS),
|
||||
saddle: None,
|
||||
armor: None,
|
||||
items: vec![None; CHEST_SIZE],
|
||||
show_saddle: shows_saddle(species),
|
||||
show_armor: shows_body(species),
|
||||
});
|
||||
self.show_mount_menu();
|
||||
true
|
||||
}
|
||||
fn show_mount_menu(&mut self) {
|
||||
if self.remote.is_none() && self.lan_acting.is_none() {
|
||||
self.carried = None;
|
||||
}
|
||||
self.station = None;
|
||||
self.container = None;
|
||||
self.craft_size = 2;
|
||||
@@ -94,15 +160,39 @@ impl Game<'_> {
|
||||
return false;
|
||||
};
|
||||
let m = &self.mobs[index];
|
||||
if !equine::is_equine(m.species()) || !m.extra.tame || !m.alive() {
|
||||
if !has_mount_menu(m.species()) || !m.extra.tame || !m.alive() {
|
||||
return false;
|
||||
}
|
||||
self.open_mount_menu(index);
|
||||
true
|
||||
}
|
||||
/// Riding a mount that has a horse inventory (`HasCustomInventoryScreen`).
|
||||
pub(super) fn riding_mount_with_menu(&self) -> bool {
|
||||
self.riding
|
||||
.and_then(|id| self.mount_mob_index(id))
|
||||
.is_some_and(|i| has_mount_menu(self.mobs[i].species()))
|
||||
}
|
||||
/// A server closed its window: the screen's copy goes.
|
||||
pub(super) fn mount_menu_reset(&mut self) {
|
||||
self.mount_menu.open = None;
|
||||
}
|
||||
/// The entity type of the open mount menu's mount (`minecraft:horse`).
|
||||
pub(super) fn mount_menu_entity(&self) -> Option<String> {
|
||||
let open = self.mount_menu.open.as_ref()?;
|
||||
let m = self.mobs.iter().find(|m| m.id == open.mob)?;
|
||||
Some(m.kind.id.to_string())
|
||||
}
|
||||
/// The chest columns of the open mount menu (the server's window's).
|
||||
pub(super) fn mount_menu_columns(&self) -> Option<usize> {
|
||||
self.mount_menu.open.as_ref().map(|o| o.columns)
|
||||
}
|
||||
/// The menu ends when the mount dies or is more than 4 blocks away
|
||||
/// (`AbstractMountInventoryMenu.stillValid`).
|
||||
pub(super) fn tick_mount_menu(&mut self) {
|
||||
// A server's menu ends when the server closes it.
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(open) = self.mount_menu.open.as_ref() else {
|
||||
return;
|
||||
};
|
||||
@@ -126,8 +216,12 @@ impl Game<'_> {
|
||||
self.mount_sync();
|
||||
self.mount_menu.open = None;
|
||||
}
|
||||
/// Writes the menu slots to the mount, with the equip sounds.
|
||||
/// Writes the menu slots to the mount, with the equip sounds. A
|
||||
/// server's menu is the server's to write.
|
||||
fn mount_sync(&mut self) {
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(open) = self.mount_menu.open.as_ref() else {
|
||||
return;
|
||||
};
|
||||
@@ -135,25 +229,66 @@ impl Game<'_> {
|
||||
return;
|
||||
};
|
||||
let (saddle, armor) = (open.saddle.clone(), open.armor.clone());
|
||||
let body = open.show_armor.then_some(armor);
|
||||
let items = open.items.clone();
|
||||
let m = &mut self.mobs[index];
|
||||
self.mount_store(index, saddle, body, items);
|
||||
}
|
||||
/// The slots of mount `index` as its menu shows them: the saddle, the
|
||||
/// body item (None when the slot isn't active), the chest.
|
||||
pub(super) fn mount_contents(
|
||||
&self,
|
||||
index: usize,
|
||||
) -> (
|
||||
Option<ItemStack>,
|
||||
Option<Option<ItemStack>>,
|
||||
Vec<Option<ItemStack>>,
|
||||
) {
|
||||
let m = &self.mobs[index];
|
||||
let species = m.species();
|
||||
let body =
|
||||
shows_body(species).then(|| m.extra.head.as_deref().map(|i| ItemStack::new(i, 1)));
|
||||
let mut items = m.extra.items.clone();
|
||||
items.resize(mount_columns(m) * 3, None);
|
||||
(m.saddle_item(), body, items)
|
||||
}
|
||||
/// The menu's slots back on mount `index` (`body` None: not its slot),
|
||||
/// with the equip sound of what was put on (`Equippable.equipSound`).
|
||||
pub(super) fn mount_store(
|
||||
&mut self,
|
||||
index: usize,
|
||||
saddle: Option<ItemStack>,
|
||||
body: Option<Option<ItemStack>>,
|
||||
items: Vec<Option<ItemStack>>,
|
||||
) {
|
||||
let m = &self.mobs[index];
|
||||
let at = m.center();
|
||||
let sound = if saddle.is_some() && !m.extra.saddled {
|
||||
Some("minecraft:entity.horse.saddle")
|
||||
} else if armor.is_some() && m.extra.head.is_none() {
|
||||
Some("minecraft:entity.horse.armor")
|
||||
let put_on = if saddle.is_some() && !m.extra.saddled {
|
||||
saddle.as_ref()
|
||||
} else {
|
||||
None
|
||||
body.as_ref()
|
||||
.and_then(Option::as_ref)
|
||||
.filter(|_| m.extra.head.is_none())
|
||||
};
|
||||
let sound = put_on.map(|s| {
|
||||
self.res
|
||||
.items()
|
||||
.get(&s.item)
|
||||
.and_then(|i| i.equip_sound.clone())
|
||||
.unwrap_or_else(|| "minecraft:item.armor.equip_generic".into())
|
||||
});
|
||||
let m = &mut self.mobs[index];
|
||||
m.set_saddle(saddle);
|
||||
if open.show_armor {
|
||||
m.extra.head = armor.map(|a| a.item);
|
||||
if let Some(body) = body {
|
||||
m.extra.head = body.map(|a| a.item);
|
||||
}
|
||||
let mut items = items;
|
||||
let keep = m.extra.items.len().max(CHEST_SIZE);
|
||||
items.resize(keep, None);
|
||||
m.extra.items = items;
|
||||
let (x, z) = (at[0].floor() as i32 >> 4, at[2].floor() as i32 >> 4);
|
||||
self.world.modified.insert((x, z));
|
||||
if let Some(sound) = sound {
|
||||
self.audio.play(sound, Some(at), 0.5, 1.0);
|
||||
self.audio.play(&sound, Some(at), 0.5, 1.0);
|
||||
}
|
||||
}
|
||||
pub(super) fn mount_slots(&self) -> Option<Vec<usize>> {
|
||||
@@ -214,7 +349,8 @@ impl Game<'_> {
|
||||
}
|
||||
/// A click in the mount menu before the generic handling.
|
||||
pub(super) fn mount_click(&mut self, right: bool) -> bool {
|
||||
if !self.mount_active() {
|
||||
// A server's menu: the click goes out like any container click.
|
||||
if !self.mount_active() || self.remote.is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(r) = self.renderer.as_ref() else {
|
||||
@@ -314,12 +450,12 @@ impl Game<'_> {
|
||||
if open.show_armor {
|
||||
batch.sprite(atlas, "gui/sprites/container/slot", ox + 7.0, oy + 35.0);
|
||||
if open.armor.is_none() {
|
||||
batch.sprite(
|
||||
atlas,
|
||||
"gui/sprites/container/slot/horse_armor",
|
||||
ox + 8.0,
|
||||
oy + 36.0,
|
||||
);
|
||||
let sprite = if llama::is_llama(open.species) {
|
||||
"gui/sprites/container/slot/llama_armor"
|
||||
} else {
|
||||
"gui/sprites/container/slot/horse_armor"
|
||||
};
|
||||
batch.sprite(atlas, sprite, ox + 8.0, oy + 36.0);
|
||||
}
|
||||
}
|
||||
let grey = rgba(64, 64, 64, 255);
|
||||
@@ -448,4 +584,16 @@ mod tests {
|
||||
"minecraft:iron_chestplate"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llamas_wear_carpets_and_no_saddle() {
|
||||
assert!(body_armor_fits(Species::Llama, "minecraft:red_carpet"));
|
||||
assert!(!body_armor_fits(
|
||||
Species::Llama,
|
||||
"minecraft:iron_horse_armor"
|
||||
));
|
||||
assert!(shows_body(Species::TraderLlama));
|
||||
assert!(!shows_saddle(Species::Llama));
|
||||
assert!(shows_saddle(Species::Donkey) && !shows_body(Species::Donkey));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +107,10 @@ impl Game<'_> {
|
||||
let held = self.inventory[self.selected].clone();
|
||||
let m = &self.mobs[index];
|
||||
let species = m.species();
|
||||
// A server player rides it already (`isVehicle`: no seat, no feeding).
|
||||
if self.ridden_by_guest(m.id) {
|
||||
return false;
|
||||
}
|
||||
if matches!(species, Species::Pig | Species::Strider) {
|
||||
return self.interact_steerable(index, item);
|
||||
}
|
||||
@@ -246,24 +250,9 @@ impl Game<'_> {
|
||||
self.consume_held();
|
||||
true
|
||||
}
|
||||
/// The rider's input for this tick; returns false when not on a mount.
|
||||
pub(super) fn tick_mount_riding(&mut self, keys: Keys) -> bool {
|
||||
let Some(i) = self.mount_index() else {
|
||||
return false;
|
||||
};
|
||||
if keys.shift || !self.mobs[i].alive() {
|
||||
self.dismount_mount();
|
||||
return true;
|
||||
}
|
||||
let strafe = f32::from(u8::from(keys.left)) - f32::from(u8::from(keys.right));
|
||||
let forward = f32::from(u8::from(keys.forward)) - f32::from(u8::from(keys.backward));
|
||||
// LocalPlayer.aiStep: the riding jump charges while space is held.
|
||||
let held = self.held().map(|s| s.item.clone());
|
||||
let steer = match self.mobs[i].species() {
|
||||
Species::Pig => held.as_deref() == Some("minecraft:carrot_on_a_stick"),
|
||||
Species::Strider => held.as_deref() == Some("minecraft:warped_fungus_on_a_stick"),
|
||||
_ => false,
|
||||
};
|
||||
/// `LocalPlayer.aiStep`'s riding jump: the bar charges while jump is
|
||||
/// held; on release, the jump's strength (0 when there is none).
|
||||
pub(super) fn charge_mount_jump(&mut self, i: usize, keys: Keys) -> f32 {
|
||||
// PlayerRideableJumping: horses, camels and nautili (the dash).
|
||||
let saddled = self.mobs[i].extra.saddled
|
||||
&& (equine::is_equine(self.mobs[i].species())
|
||||
@@ -299,6 +288,27 @@ impl Game<'_> {
|
||||
}
|
||||
st.was_jumping = keys.jump;
|
||||
}
|
||||
jump
|
||||
}
|
||||
/// The rider's input for this tick; returns false when not on a mount.
|
||||
pub(super) fn tick_mount_riding(&mut self, keys: Keys) -> bool {
|
||||
let Some(i) = self.mount_index() else {
|
||||
return false;
|
||||
};
|
||||
if keys.shift || !self.mobs[i].alive() {
|
||||
self.dismount_mount();
|
||||
return true;
|
||||
}
|
||||
let strafe = f32::from(u8::from(keys.left)) - f32::from(u8::from(keys.right));
|
||||
let forward = f32::from(u8::from(keys.forward)) - f32::from(u8::from(keys.backward));
|
||||
// LocalPlayer.aiStep: the riding jump charges while space is held.
|
||||
let held = self.held().map(|s| s.item.clone());
|
||||
let steer = match self.mobs[i].species() {
|
||||
Species::Pig => held.as_deref() == Some("minecraft:carrot_on_a_stick"),
|
||||
Species::Strider => held.as_deref() == Some("minecraft:warped_fungus_on_a_stick"),
|
||||
_ => false,
|
||||
};
|
||||
let jump = self.charge_mount_jump(i, keys);
|
||||
let m = &mut self.mobs[i];
|
||||
if jump > 0.0 {
|
||||
// onPlayerJump: rear while jumping (horses).
|
||||
@@ -324,7 +334,7 @@ impl Game<'_> {
|
||||
pitch: self.pitch,
|
||||
jump: if jump > 0.0 { jump } else { pending },
|
||||
steer,
|
||||
sprint: self.keys.contains(&winit::keyboard::KeyCode::ControlLeft),
|
||||
sprint: keys.sprint || self.keys.contains(&winit::keyboard::KeyCode::ControlLeft),
|
||||
jumping: keys.jump,
|
||||
});
|
||||
true
|
||||
|
||||
@@ -113,7 +113,7 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
/// Where focus can land: buttons drawn last frame, every registered
|
||||
/// target (sliders, fields, rows, Horizon-style widgets), and the slots
|
||||
/// target (sliders, fields, rows, keyboard keys), and the slots
|
||||
/// and tabs of inventories (GUI pixels), on screen.
|
||||
fn pad_targets(&self) -> Vec<Target> {
|
||||
let mut targets = self.pad_all_targets();
|
||||
@@ -137,7 +137,7 @@ impl Game<'_> {
|
||||
})
|
||||
.collect();
|
||||
for t in widgets::last_targets() {
|
||||
// A Horizon button is both a labelled button and a target.
|
||||
// A button can be both a labelled button and a target.
|
||||
if let Some(same) = targets.iter_mut().find(|o| o.rect == t.rect) {
|
||||
same.kind = t.kind;
|
||||
} else {
|
||||
@@ -1026,45 +1026,13 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The focus highlight. Classic screens look as vanilla's keyboard focus
|
||||
/// does: buttons, sliders and slots already draw their highlighted
|
||||
/// sprite under the (hidden) pointer, and list rows and fields get
|
||||
/// vanilla's white one-pixel outline (`AbstractSelectionList`'s focused
|
||||
/// selection, `EditBox`'s highlighted border). Horizon-style screens get
|
||||
/// the design system's focus colour: a two-dp accent ring.
|
||||
/// The focus highlight, as vanilla's keyboard focus looks: buttons,
|
||||
/// sliders and slots already draw their highlighted sprite under the
|
||||
/// (hidden) pointer, and list rows and fields get vanilla's white
|
||||
/// one-pixel outline (`AbstractSelectionList`'s focused selection,
|
||||
/// `EditBox`'s highlighted border).
|
||||
fn draw_pad_focus(&self, batch: &mut HudBatch, focus: Target) {
|
||||
let [x, y, w, h] = focus.rect;
|
||||
// The options' sub-pages keep the classic layout under either style.
|
||||
let horizon = horizon_client::ui_theme::horizon()
|
||||
&& if self.screen == Screen::Options {
|
||||
self.ui.options.page() == Page::Main
|
||||
} else {
|
||||
self.title.is_some() || self.screen == Screen::Paused
|
||||
};
|
||||
if horizon {
|
||||
use horizon_client::ui_theme::{self as theme, Ui, color};
|
||||
let mut ui = Ui::new(&self.gui.atlas, batch, self.cursor);
|
||||
let k = ui.batch.scale / ui.density;
|
||||
let (x, y, w, h) = (x * k, y * k, w * k, h * k);
|
||||
let radius = match focus.kind {
|
||||
Kind::Button | Kind::Tab(_) | Kind::Slider { .. } => (h + 6.0) / 2.0,
|
||||
Kind::Field => theme::RADIUS + 3.0,
|
||||
_ => theme::RADIUS_PLATE + 3.0,
|
||||
};
|
||||
for inset in [0.0, 1.0] {
|
||||
let o = 3.0 - inset;
|
||||
ui.border(
|
||||
x - o,
|
||||
y - o,
|
||||
w + 2.0 * o,
|
||||
h + 2.0 * o,
|
||||
radius - inset,
|
||||
color::ACCENT,
|
||||
);
|
||||
}
|
||||
ui.finish();
|
||||
return;
|
||||
}
|
||||
if matches!(focus.kind, Kind::Row | Kind::Field) {
|
||||
let atlas = &self.gui.atlas;
|
||||
let white = rgba(255, 255, 255, 255);
|
||||
|
||||
@@ -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,
|
||||
@@ -183,6 +183,9 @@ const CHUNK_PACKETS_PER_FRAME: Duration = Duration::from_millis(1);
|
||||
/// whatever their cost: the packets after a slow machine's chunks never
|
||||
/// wait more than a tick.
|
||||
const BACKLOG_LIMIT: Duration = Duration::from_millis(50);
|
||||
/// The open menu name of a server's horse inventory, then its chest's
|
||||
/// columns (the packet names no `MenuType`).
|
||||
const MOUNT_MENU: &str = "horizon:mount";
|
||||
|
||||
fn face_direction(face: [i32; 3]) -> u8 {
|
||||
match face {
|
||||
@@ -332,6 +335,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 +1370,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);
|
||||
@@ -1431,6 +1443,19 @@ impl Game<'_> {
|
||||
// CrafterMenu: the grid, the inventory, then the result (the
|
||||
// client's own).
|
||||
"minecraft:crafter_3x3" => slots(9),
|
||||
// HorseInventoryMenu: the saddle, the body armour, the chest,
|
||||
// then the inventory.
|
||||
m if m.starts_with(MOUNT_MENU) => {
|
||||
let n = m[MOUNT_MENU.len()..].parse::<usize>().ok()? * 3;
|
||||
match s {
|
||||
0 => Some(super::mount_menu::SADDLE),
|
||||
1 => Some(super::mount_menu::ARMOR),
|
||||
_ if s < 2 + n => Some(super::mount_menu::CHEST + s - 2),
|
||||
_ if s < 2 + n + 27 => Some(9 + s - 2 - n),
|
||||
_ if s < 2 + n + 36 => Some(s - 2 - n - 27),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
// A workstation: its inputs, its result, then the inventory.
|
||||
m => {
|
||||
let kind = Self::remote_station_kind(m)?;
|
||||
@@ -1748,6 +1773,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() {
|
||||
@@ -2193,6 +2220,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
C::OpenScreen(p) => self.remote_open_screen(p),
|
||||
C::MountScreenOpen(p) => self.remote_open_mount(p),
|
||||
C::RecipeBookAdd(p) => self.remote_recipe_book_add(p),
|
||||
C::RecipeBookRemove(p) => self.remote_recipe_book_remove(p),
|
||||
C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p),
|
||||
@@ -2927,9 +2955,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 +2978,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 +3002,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 +3288,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 +3352,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 +3376,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 +3507,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 +3618,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 +3700,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 +3766,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 +3785,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 +4012,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 +4094,38 @@ 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)
|
||||
}
|
||||
// MultiPlayerGameMode.isServerControlledInventory: riding a
|
||||
// horse or llama, the server opens its inventory
|
||||
// (ServerboundPlayerCommandPacket OPEN_INVENTORY).
|
||||
KeyCode::KeyE if self.riding_mount_with_menu() => {
|
||||
let id = self.remote.as_ref().map_or(0, |r| r.entity_id);
|
||||
self.send(S::PlayerCommand(play::PlayerCommand {
|
||||
id,
|
||||
action: 5,
|
||||
data: 0,
|
||||
}));
|
||||
Ok(true)
|
||||
}
|
||||
KeyCode::KeyE => {
|
||||
@@ -4248,6 +4372,7 @@ impl Game<'_> {
|
||||
r.menu = None;
|
||||
r.menu_title = None;
|
||||
}
|
||||
self.mount_menu_reset();
|
||||
// The client's menu has no level access: what it holds is the server's.
|
||||
self.station = None;
|
||||
self.craft_size = 2;
|
||||
@@ -4432,6 +4557,21 @@ impl Game<'_> {
|
||||
self.screen = Screen::Inventory;
|
||||
self.capture(false);
|
||||
}
|
||||
/// `ClientPacketListener.handleMountScreenOpen`: a horse's or llama's
|
||||
/// inventory; for another entity the window is closed again.
|
||||
fn remote_open_mount(&mut self, p: play::MountScreenOpen) {
|
||||
let columns = usize::try_from(p.columns).unwrap_or(0).min(5);
|
||||
if !self.open_remote_mount_menu(p.entity as u32, columns) {
|
||||
self.send(S::ContainerClose(play::ContainerClose {
|
||||
container: p.container,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.menu = Some((p.container, format!("{MOUNT_MENU}{columns}")));
|
||||
r.menu_title = None;
|
||||
}
|
||||
}
|
||||
/// The type of the menu a server opened (`MenuType`'s id).
|
||||
pub(super) fn remote_menu_type(&self) -> Option<&str> {
|
||||
Some(self.remote.as_ref()?.menu.as_ref()?.1.as_str())
|
||||
@@ -4678,7 +4818,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 +4848,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 +4875,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 +4887,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 +5027,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(®istry, &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,189 @@
|
||||
//! 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;
|
||||
};
|
||||
if let Some(i) = self.mobs.iter().position(|m| m.id == id) {
|
||||
// An animal moves on the server with the rider's input
|
||||
// (PlayerInput); here the jump bar charges for the HUD and the
|
||||
// rider sits where `positionRider` puts it.
|
||||
self.charge_mount_jump(i, keys);
|
||||
self.position_rider();
|
||||
return true;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Worlds and the multiplayer server list from the control socket: what the Select World, Edit
|
||||
//! World and Multiplayer screens do, by world folder. Changing a world needs the title screen
|
||||
//! (no world open), as those screens do; deleting one needs `--confirm`.
|
||||
use super::Game;
|
||||
use horizon_client::{Result, title};
|
||||
use serde_json::{Value, json};
|
||||
use std::{path::PathBuf, sync::mpsc::Sender, time::UNIX_EPOCH};
|
||||
|
||||
pub(super) const HELP: &[&str] = &[
|
||||
"worlds the saved worlds, newest first: folder, name, mode, last played, version",
|
||||
"world-rename FOLDER NAME rename a world (Edit World; its folder stays)",
|
||||
"world-backup FOLDER zip a world into backups/ (Edit World > Make Backup)",
|
||||
"world-delete FOLDER --confirm delete a world for good (Select World > Delete)",
|
||||
"servers the multiplayer server list (servers.dat): name and address",
|
||||
];
|
||||
|
||||
fn saves() -> Result<PathBuf> {
|
||||
Ok(std::env::current_dir()?.join("saves"))
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Some(reply) for these commands (Some(None): the reply comes later), None for others.
|
||||
pub(super) fn saves_control(
|
||||
&mut self,
|
||||
words: &[&str],
|
||||
line: &str,
|
||||
reply: &Sender<String>,
|
||||
) -> Result<Option<Option<Value>>> {
|
||||
let folder = || {
|
||||
words
|
||||
.get(1)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("{} FOLDER: the folder from worlds", words[0]))
|
||||
};
|
||||
let on_title = || {
|
||||
if self.title.is_some() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"{} needs the title screen: save and leave the world first (pause, then Save and Quit to Title)",
|
||||
words[0]
|
||||
))
|
||||
}
|
||||
};
|
||||
let value = match words[0] {
|
||||
"worlds" => {
|
||||
let worlds: Vec<Value> = title::list_worlds(&saves()?)
|
||||
.iter()
|
||||
.map(|w| {
|
||||
json!({
|
||||
"folder": w.folder,
|
||||
"name": w.name,
|
||||
"mode": if w.creative { "creative" } else { "survival" },
|
||||
"last_played": w.modified.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64),
|
||||
"commands": w.commands,
|
||||
"version": w.version,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({ "worlds": worlds })
|
||||
}
|
||||
"world-rename" => {
|
||||
on_title()?;
|
||||
let folder = folder()?;
|
||||
let name = line
|
||||
.trim_start()
|
||||
.strip_prefix("world-rename")
|
||||
.and_then(|rest| rest.trim_start().strip_prefix(folder))
|
||||
.map(str::trim)
|
||||
.filter(|n| !n.is_empty())
|
||||
.ok_or("world-rename FOLDER NAME: missing the new name")?;
|
||||
title::world_management::rename(&saves()?, folder, name)?;
|
||||
if let Some(title) = self.title.as_mut() {
|
||||
title.worlds_changed();
|
||||
}
|
||||
json!({ "ok": true, "folder": folder, "name": name })
|
||||
}
|
||||
"world-delete" => {
|
||||
on_title()?;
|
||||
let folder = folder()?;
|
||||
if !words.contains(&"--confirm") {
|
||||
return Err(format!(
|
||||
"world-delete deletes {folder} for good: ask the player, then add --confirm"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
title::world_management::delete(&saves()?, folder)?;
|
||||
if let Some(title) = self.title.as_mut() {
|
||||
title.worlds_changed();
|
||||
}
|
||||
json!({ "ok": true, "deleted": folder })
|
||||
}
|
||||
"world-backup" => {
|
||||
on_title()?;
|
||||
let folder = folder()?.to_owned();
|
||||
let saves = saves()?;
|
||||
let backups = title::world_management::backups_path(&saves);
|
||||
// A big world takes a while to zip: off the game thread, as Make Backup does.
|
||||
let reply = reply.clone();
|
||||
std::thread::spawn(move || {
|
||||
let answer = match title::world_management::backup(&saves, &folder) {
|
||||
Ok(bytes) => {
|
||||
json!({ "ok": true, "folder": folder, "backups": backups, "bytes": bytes })
|
||||
}
|
||||
Err(e) => json!({ "error": format!("backup of {folder} failed: {e}") }),
|
||||
};
|
||||
let _ = reply.send(answer.to_string());
|
||||
});
|
||||
return Ok(Some(None));
|
||||
}
|
||||
"servers" => {
|
||||
let file = horizon_client::multiplayer::servers_file(&saves()?);
|
||||
let servers: Vec<Value> = horizon_protocol::servers::load(&file)
|
||||
.iter()
|
||||
.map(|s| json!({ "name": s.name, "address": s.ip }))
|
||||
.collect();
|
||||
json!({ "servers": servers })
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
Ok(Some(Some(value)))
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,28 @@ 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
|
||||
| Self::Friends => 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)> {
|
||||
@@ -43,6 +65,9 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s
|
||||
}
|
||||
|
||||
/// The icon row: report bugs, feedback, friends, player reporting.
|
||||
/// `FRIENDS_ICON` (vanilla's `CommonButtons.friends`) opens Horizon's
|
||||
/// Play with Friends; the others stay inactive.
|
||||
const FRIENDS_ICON: usize = 2;
|
||||
fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] {
|
||||
let x0 = ((w - 212.0) * 0.5).floor() + 60.0;
|
||||
let y = ((h - 166.0) * 0.25).floor() + 98.0;
|
||||
@@ -69,41 +94,8 @@ impl Game<'_> {
|
||||
pub(super) fn external_server(&self) -> bool {
|
||||
self.remote.is_some() && self.integrated.is_none()
|
||||
}
|
||||
/// Whether the pause menu is drawn in Horizon's style (over a blurred world).
|
||||
pub(super) fn horizon_pause(&self) -> bool {
|
||||
self.screen == Screen::Paused
|
||||
&& self.pause_menu
|
||||
&& self.title.is_none()
|
||||
&& horizon_client::ui_theme::horizon()
|
||||
}
|
||||
fn pause_labels(&self) -> (String, &'static str) {
|
||||
if let Some(server) = &self.integrated {
|
||||
return (server.world_name.clone(), "Save and quit");
|
||||
}
|
||||
if self.external_server() {
|
||||
("Multiplayer".to_owned(), "Disconnect")
|
||||
} else {
|
||||
(self.level.name.clone(), "Save and quit")
|
||||
}
|
||||
}
|
||||
pub(super) fn draw_pause_menu(&mut self, batch: &mut HudBatch) {
|
||||
if horizon_client::ui_theme::horizon() {
|
||||
let opened = *self.pause_since.get_or_insert_with(std::time::Instant::now);
|
||||
let (world, quit) = self.pause_labels();
|
||||
self.tick_friends();
|
||||
let friends = self.friends_view();
|
||||
let mut ui = horizon_client::ui_theme::Ui::new(&self.gui.atlas, batch, self.cursor);
|
||||
horizon_client::front::pause::draw(
|
||||
&mut ui,
|
||||
&world,
|
||||
quit,
|
||||
opened,
|
||||
&friends,
|
||||
self.external_server(),
|
||||
);
|
||||
ui.finish();
|
||||
return;
|
||||
}
|
||||
let friends = self.friends_view().shown;
|
||||
let atlas = &self.gui.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
|
||||
@@ -131,12 +123,41 @@ impl Game<'_> {
|
||||
hover,
|
||||
);
|
||||
}
|
||||
for (x, y, sprite) in pause_icons(w, h) {
|
||||
ui::button(batch, atlas, x, y, 20.0, 20.0, &Text::empty(), false, false);
|
||||
let mut tooltip = None;
|
||||
for (i, (x, y, sprite)) in pause_icons(w, h).into_iter().enumerate() {
|
||||
let active = i == FRIENDS_ICON && friends;
|
||||
let hover = ui::hovered(self.cursor, x, y, 20.0, 20.0);
|
||||
// The icon has no label: name it for controller focus and the
|
||||
// control socket's widget tree.
|
||||
if i == FRIENDS_ICON {
|
||||
horizon_client::widgets::record(
|
||||
horizon_client::friends_screen::TITLE,
|
||||
[x, y, 20.0, 20.0],
|
||||
active,
|
||||
);
|
||||
}
|
||||
ui::button(
|
||||
batch,
|
||||
atlas,
|
||||
x,
|
||||
y,
|
||||
20.0,
|
||||
20.0,
|
||||
&Text::empty(),
|
||||
active,
|
||||
active && hover,
|
||||
);
|
||||
// SpriteIconButton.CenteredIcon: the 15x15 sprite at
|
||||
// x + width / 2 - 15 / 2 in integer pixels, untinted even
|
||||
// when the button is inactive.
|
||||
batch.sprite_scaled(atlas, sprite, x + 3.0, y + 3.0, 15.0, 15.0, u32::MAX);
|
||||
if i == FRIENDS_ICON && hover {
|
||||
tooltip = Some(Text::literal(horizon_client::friends_screen::TITLE));
|
||||
}
|
||||
}
|
||||
// SpriteIconButton.withTootip: the label as a tooltip.
|
||||
if let Some(tip) = tooltip {
|
||||
ui::tooltip(batch, atlas, &[tip], self.cursor);
|
||||
}
|
||||
}
|
||||
pub(super) fn pause_click(&mut self) -> Result<()> {
|
||||
@@ -148,29 +169,16 @@ impl Game<'_> {
|
||||
let b = HudBatch::new(size);
|
||||
(b.width, b.height)
|
||||
};
|
||||
let hit = if horizon_client::ui_theme::horizon() {
|
||||
let size = self
|
||||
.renderer
|
||||
.as_ref()
|
||||
.map_or([1, 1], |r| [r.config.width, r.config.height]);
|
||||
let mut b = HudBatch::new(size);
|
||||
let (world, quit) = self.pause_labels();
|
||||
horizon_client::front::pause::click(
|
||||
&self.gui.atlas,
|
||||
&mut b,
|
||||
self.cursor.0,
|
||||
self.cursor.1,
|
||||
&world,
|
||||
quit,
|
||||
&self.friends_view(),
|
||||
self.external_server(),
|
||||
)
|
||||
} else {
|
||||
pause_buttons(w, h, self.external_server())
|
||||
.into_iter()
|
||||
.find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
|
||||
.map(|b| b.4)
|
||||
};
|
||||
let friends = pause_icons(w, h)[FRIENDS_ICON];
|
||||
let hit = pause_buttons(w, h, self.external_server())
|
||||
.into_iter()
|
||||
.find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
|
||||
.map(|b| b.4)
|
||||
.or_else(|| {
|
||||
(self.friends_view().shown
|
||||
&& ui::hovered(self.cursor, friends.0, friends.1, 20.0, 20.0))
|
||||
.then_some(10)
|
||||
});
|
||||
match hit {
|
||||
Some(0) => {
|
||||
self.screen = Screen::Playing;
|
||||
@@ -180,17 +188,11 @@ impl Game<'_> {
|
||||
Some(3) => self.open_stats(),
|
||||
Some(4) => self.open_advancements(true),
|
||||
Some(9) => self.open_world_options(),
|
||||
Some(10) => {
|
||||
if let Err(e) = self.friends_start() {
|
||||
self.system_message(Text::literal(format!("Couldn't share the world: {e}")));
|
||||
}
|
||||
}
|
||||
Some(11) => self.friends_copy(),
|
||||
Some(12) => self.friends_stop(),
|
||||
Some(10) => self.screen = Screen::Friends,
|
||||
Some(2) => self.close_world()?,
|
||||
_ => {}
|
||||
}
|
||||
if hit.is_some() && !horizon_client::ui_theme::horizon() {
|
||||
if hit.is_some() {
|
||||
self.audio.play_button_click();
|
||||
}
|
||||
Ok(())
|
||||
@@ -334,7 +336,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() {
|
||||
|
||||
@@ -73,11 +73,6 @@ impl StartupMenu {
|
||||
&self.root,
|
||||
);
|
||||
title.last_server = settings.file.string("lastServer");
|
||||
if horizon_client::ui_theme::horizon() {
|
||||
title
|
||||
.opening
|
||||
.set(Some(horizon_client::front::Opening::new()));
|
||||
}
|
||||
self.title = Some(title);
|
||||
}
|
||||
}
|
||||
@@ -152,9 +147,6 @@ impl StartupMenu {
|
||||
fn title_key(&mut self, event: &KeyEvent) {
|
||||
let shortcut = self.shortcut(event);
|
||||
let Some(title) = &mut self.title else { return };
|
||||
if title.skip_opening() {
|
||||
return;
|
||||
}
|
||||
if let Some(shortcut) = shortcut {
|
||||
if title.has_caret_field() {
|
||||
title.field_shortcut(shortcut, &mut self.clipboard);
|
||||
@@ -422,14 +414,6 @@ impl Loading {
|
||||
event_loop: &ActiveEventLoop,
|
||||
event: WindowEvent,
|
||||
) -> Result<()> {
|
||||
if let WindowEvent::MouseInput {
|
||||
state,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} = &event
|
||||
{
|
||||
horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed);
|
||||
}
|
||||
if let WindowEvent::KeyboardInput { event, .. } = &event
|
||||
&& let PhysicalKey::Code(key) = event.physical_key
|
||||
{
|
||||
@@ -455,7 +439,6 @@ impl Loading {
|
||||
WindowEvent::Focused(false) => {
|
||||
self.menu.modifiers = ModifiersState::empty();
|
||||
self.menu.physical_keys.clear();
|
||||
horizon_client::ui_theme::set_pressed(false);
|
||||
self.menu.dragging = false;
|
||||
if let Some(title) = &mut self.menu.title {
|
||||
title.release();
|
||||
@@ -508,41 +491,23 @@ impl Loading {
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} => {
|
||||
let mut batch = HudBatch::new(self.menu_size());
|
||||
let batch = HudBatch::new(self.menu_size());
|
||||
if let (Some(title), Some(gui)) = (&mut self.menu.title, &self.gui) {
|
||||
if state == ElementState::Released {
|
||||
title.release();
|
||||
title.release_field();
|
||||
} else {
|
||||
let action = if horizon_client::ui_theme::horizon() {
|
||||
let action = title.click_horizon(
|
||||
&gui.atlas,
|
||||
&mut batch,
|
||||
self.menu.cursor.0,
|
||||
self.menu.cursor.1,
|
||||
);
|
||||
// Horizon's deeper world-management pages use classic fields.
|
||||
title.press_field(
|
||||
&gui.atlas,
|
||||
self.menu.cursor,
|
||||
(batch.width, batch.height),
|
||||
self.menu.modifiers.shift_key(),
|
||||
);
|
||||
action
|
||||
} else {
|
||||
let (action, _) = title.click(
|
||||
self.menu.cursor.0,
|
||||
self.menu.cursor.1,
|
||||
(batch.width, batch.height),
|
||||
);
|
||||
title.press_field(
|
||||
&gui.atlas,
|
||||
self.menu.cursor,
|
||||
(batch.width, batch.height),
|
||||
self.menu.modifiers.shift_key(),
|
||||
);
|
||||
action
|
||||
};
|
||||
let (action, _) = title.click(
|
||||
self.menu.cursor.0,
|
||||
self.menu.cursor.1,
|
||||
(batch.width, batch.height),
|
||||
);
|
||||
title.press_field(
|
||||
&gui.atlas,
|
||||
self.menu.cursor,
|
||||
(batch.width, batch.height),
|
||||
self.menu.modifiers.shift_key(),
|
||||
);
|
||||
self.menu_action(event_loop, action);
|
||||
}
|
||||
}
|
||||
@@ -617,18 +582,12 @@ impl Loading {
|
||||
} else if let Some(title) = &mut self.menu.title {
|
||||
title.poll_backup();
|
||||
let _ = title.update_toast(self.settings.notification_display_time);
|
||||
if horizon_client::ui_theme::horizon() {
|
||||
let mut ui = horizon_client::ui_theme::Ui::new(&gui.atlas, batch, self.menu.cursor);
|
||||
title.draw_horizon(&mut ui, 0.0);
|
||||
ui.finish();
|
||||
} else {
|
||||
title.draw(
|
||||
&gui.atlas,
|
||||
batch,
|
||||
self.menu.cursor,
|
||||
self.settings.file.bool("hideSplashTexts"),
|
||||
);
|
||||
}
|
||||
title.draw(
|
||||
&gui.atlas,
|
||||
batch,
|
||||
self.menu.cursor,
|
||||
self.settings.file.bool("hideSplashTexts"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -730,7 +689,6 @@ mod tests {
|
||||
// Navigate and enter a world name without a registry, biomes, pack
|
||||
// tables or a Game. Replacing fallback artwork preserves this state.
|
||||
let title = loading.menu.title.as_mut().unwrap();
|
||||
title.opening.set(None);
|
||||
title.mode = horizon_client::title::Mode::Create {
|
||||
name: String::new(),
|
||||
seed: "42".into(),
|
||||
|
||||
@@ -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
|
||||
@@ -230,8 +239,6 @@ pub struct Frame<'a> {
|
||||
pub night_vision: f32,
|
||||
/// Torch flicker added to the block light factor of 1.4.
|
||||
pub block_flicker: f32,
|
||||
/// Blur and grade the frame under a Horizon-style menu (`post`).
|
||||
pub post: Option<crate::post::PostGrade>,
|
||||
/// `Screen.extractBlurredBackground`: blur the frame by this radius
|
||||
/// (`menuBackgroundBlurriness`) before the screen is drawn over it.
|
||||
pub menu_blur: Option<f32>,
|
||||
@@ -324,6 +331,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 +342,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.
|
||||
@@ -437,8 +448,6 @@ pub struct Renderer {
|
||||
/// The selected shader pack's stages (Horizon setting; none by default).
|
||||
pack: Option<Pack>,
|
||||
pub hud: HudRenderer,
|
||||
/// The menus' backdrop blur, made on first use.
|
||||
post: Option<crate::post::Post>,
|
||||
/// Vanilla's menu background blur, made on first use.
|
||||
menu_blur: Option<crate::menu_blur::MenuBlur>,
|
||||
pub info: wgpu::AdapterInfo,
|
||||
@@ -685,13 +694,15 @@ fn describe_adapter(adapter: &wgpu::Adapter) {
|
||||
info.backend,
|
||||
info.device_type
|
||||
);
|
||||
crate::telemetry::set_gpu(
|
||||
&info.name,
|
||||
format!("{} {}", info.driver, info.driver_info)
|
||||
crate::telemetry::set_gpu(crate::telemetry::Gpu {
|
||||
name: info.name.clone(),
|
||||
vendor: horizon_telemetry::system::gpu_vendor(&info.name, info.vendor).to_owned(),
|
||||
kind: crate::telemetry::gpu_kind(&format!("{:?}", info.device_type)).to_owned(),
|
||||
driver: format!("{} {}", info.driver, info.driver_info)
|
||||
.trim()
|
||||
.to_owned(),
|
||||
format!("{:?}", info.backend),
|
||||
);
|
||||
backend: format!("{:?}", info.backend),
|
||||
});
|
||||
crate::crash::set_detail(
|
||||
"Graphics Adapter",
|
||||
format!(
|
||||
@@ -1445,6 +1456,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 +1681,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 +1735,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 +2137,7 @@ impl Renderer {
|
||||
crosshair_group,
|
||||
crosshair_globals,
|
||||
entity_pipeline,
|
||||
weather,
|
||||
crumbling_pipeline,
|
||||
water_mask_pipeline,
|
||||
cloud_pipeline,
|
||||
@@ -2110,9 +2147,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,
|
||||
@@ -2181,7 +2221,6 @@ impl Renderer {
|
||||
world_post,
|
||||
pack: None,
|
||||
hud,
|
||||
post: None,
|
||||
menu_blur: None,
|
||||
info,
|
||||
suspended: size.width == 0 || size.height == 0,
|
||||
@@ -3229,6 +3268,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 +3292,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 +3326,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 +3364,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 +3375,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 +3573,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 +3670,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 +3692,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 +3917,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
|
||||
@@ -3858,29 +3944,13 @@ impl Renderer {
|
||||
radius,
|
||||
);
|
||||
}
|
||||
if let Some(grade) = &frame.post
|
||||
&& self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
|
||||
{
|
||||
let format = self.config.format;
|
||||
let device = &self.device;
|
||||
self.post
|
||||
.get_or_insert_with(|| crate::post::Post::new(device, format))
|
||||
.apply(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&mut encoder,
|
||||
&target_texture,
|
||||
&view_target,
|
||||
[self.config.width, self.config.height],
|
||||
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);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -204,8 +204,6 @@ pub struct Graphics {
|
||||
pub resolution_scale: u32,
|
||||
/// FXAA over the world.
|
||||
pub fxaa: bool,
|
||||
/// The settings level last shown: Advanced, or Simple.
|
||||
pub advanced: bool,
|
||||
/// Battery mode: at most 60 frames per second in a world and 30 in menus
|
||||
/// or behind other windows, and half the worker threads. Off by default;
|
||||
/// it changes when frames are drawn, never what they show or the ticks.
|
||||
@@ -236,7 +234,6 @@ impl Default for Graphics {
|
||||
overlay: Overlay::Off,
|
||||
resolution_scale: 100,
|
||||
fxaa: false,
|
||||
advanced: false,
|
||||
battery: false,
|
||||
shader_pack: String::new(),
|
||||
api: GraphicsApi::Auto,
|
||||
@@ -288,7 +285,6 @@ impl Graphics {
|
||||
"workers" => g.workers = number(g.workers).min(64),
|
||||
"resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200),
|
||||
"fxaa" => g.fxaa = flag(g.fxaa),
|
||||
"level" => g.advanced = value == "advanced",
|
||||
"batteryMode" => g.battery = flag(g.battery),
|
||||
"shaderPack" => g.shader_pack = value.to_string(),
|
||||
"graphicsApi" => g.api = GraphicsApi::from_name(value).unwrap_or_default(),
|
||||
@@ -306,7 +302,7 @@ impl Graphics {
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"preset:{}\nlodDistance:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\ngraphicsApi:{}\n",
|
||||
"preset:{}\nlodDistance:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nbatteryMode:{}\nshaderPack:{}\ngraphicsApi:{}\n",
|
||||
self.preset.name(),
|
||||
self.lod_distance,
|
||||
bool_text(self.cave_culling),
|
||||
@@ -331,7 +327,6 @@ impl Graphics {
|
||||
},
|
||||
self.resolution_scale,
|
||||
bool_text(self.fxaa),
|
||||
if self.advanced { "advanced" } else { "simple" },
|
||||
bool_text(self.battery),
|
||||
self.shader_pack,
|
||||
self.api.name(),
|
||||
@@ -425,13 +420,14 @@ mod tests {
|
||||
overlay: Overlay::Graph,
|
||||
resolution_scale: 75,
|
||||
fxaa: true,
|
||||
advanced: true,
|
||||
battery: true,
|
||||
shader_pack: "horizon-sample".into(),
|
||||
api: GraphicsApi::Dx12,
|
||||
};
|
||||
assert_eq!(Graphics::parse(&g.serialize()), g);
|
||||
assert_eq!(Graphics::parse(""), Graphics::default());
|
||||
// The old menus' Simple / Advanced choice is ignored.
|
||||
assert_eq!(Graphics::parse("level:advanced\n"), Graphics::default());
|
||||
assert_eq!(
|
||||
Graphics::parse("workers:abc\nsky:maybe\ncullLeaves:maybe\nentityCulling:maybe\n"),
|
||||
Graphics::default()
|
||||
|
||||
@@ -285,7 +285,7 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
|
||||
const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384];
|
||||
|
||||
/// Classic's submenus supplement the vanilla options on their parent screens.
|
||||
/// Horizon's graphics screens supplement the vanilla options on Video Settings.
|
||||
fn extra_rows(level: Level) -> Vec<Row> {
|
||||
let mut rows = rows(level);
|
||||
rows.retain(|row| !matches!(row, Row::Setting(s) if matches!(s.item, Item::Vanilla(_))));
|
||||
@@ -444,7 +444,7 @@ fn max_workers() -> u32 {
|
||||
}
|
||||
|
||||
impl Item {
|
||||
/// On/off settings, drawn as switches by the Horizon menus.
|
||||
/// On/off settings and their value.
|
||||
pub fn switch(self, s: &Settings) -> Option<bool> {
|
||||
let g = &s.horizon;
|
||||
Some(match self {
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! launcher's "N playing now". While the game runs, a thread of its own sends a random session
|
||||
//! ID made here and kept only in memory, the version, the platform and whether a LAN or
|
||||
//! play-with-friends world is open, every minute and at once when that last one changes.
|
||||
//! It sends nothing when there is no server (`HORIZON_TELEMETRY_URL`, none by default) or
|
||||
//! with `HORIZON_NO_HEARTBEAT=1` (automated runs).
|
||||
//! It sends nothing when sending is turned off (`HORIZON_TELEMETRY_URL=off`) or with
|
||||
//! `HORIZON_NO_HEARTBEAT=1` (automated runs).
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::Thread;
|
||||
|
||||
@@ -160,7 +160,7 @@ impl HudAtlas {
|
||||
)
|
||||
}
|
||||
/// Empty slots written at run time: map textures (game/maps.rs), the
|
||||
/// minimap, downloaded skins, world icons and the Horizon menu text.
|
||||
/// minimap, downloaded skins, world icons and the on-screen keyboard's text.
|
||||
fn slots(images: &mut Vec<PackedImage>) {
|
||||
for i in 0..MAP_SLOTS {
|
||||
images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4]));
|
||||
@@ -184,7 +184,7 @@ impl HudAtlas {
|
||||
vec![0; 64 * 64 * 4],
|
||||
));
|
||||
}
|
||||
// Horizon-style menu text and corner masks (ui_theme), rasterized at run time.
|
||||
// The on-screen keyboard's text and corner masks (ui_theme), rasterized at run time.
|
||||
images.push((
|
||||
"horizon/ui-text".into(),
|
||||
2048,
|
||||
@@ -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!(
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -234,6 +234,23 @@ impl Hub {
|
||||
Some(window)
|
||||
}
|
||||
|
||||
/// ServerPlayer.openHorseInventory: the open container closes, a new
|
||||
/// window id opens mount `entity`'s inventory with its chest's columns
|
||||
/// (ClientboundMountScreenOpenPacket).
|
||||
pub fn open_mount_window(&mut self, conn: u32, columns: i32, entity: i32) -> Option<i32> {
|
||||
let i = self.guests.iter().position(|g| g.conn == conn)?;
|
||||
self.close_container_at(i);
|
||||
let g = &mut self.guests[i];
|
||||
g.next_window = g.next_window % 100 + 1;
|
||||
let window = g.next_window;
|
||||
g.send(&C::MountScreenOpen(play::MountScreenOpen {
|
||||
container: window,
|
||||
columns,
|
||||
entity,
|
||||
}));
|
||||
Some(window)
|
||||
}
|
||||
|
||||
fn send_menu_content(&mut self, i: usize, mut items: Vec<Option<ItemStack>>) {
|
||||
for j in 0..36 {
|
||||
items.push(self.guests[i].inventory[player_slot(j)].clone());
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1968,9 +1968,14 @@ 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;
|
||||
}
|
||||
// OPEN_INVENTORY is the game's: the ridden mount's inventory.
|
||||
S::PlayerCommand(p) if p.action == 5 => {
|
||||
events.push(HostEvent::Packet(conn, Box::new(S::PlayerCommand(p))));
|
||||
}
|
||||
S::PlayerCommand(p) => match p.action {
|
||||
1 => self.guests[i].sprinting = true,
|
||||
2 => self.guests[i].sprinting = false,
|
||||
@@ -2050,6 +2055,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 {
|
||||
|
||||
@@ -69,7 +69,7 @@ pub mod first_person;
|
||||
pub mod flatgen;
|
||||
pub mod fog;
|
||||
pub mod font;
|
||||
pub mod front;
|
||||
pub mod friends_screen;
|
||||
pub mod game_mode_switcher;
|
||||
pub mod gamepad;
|
||||
pub mod gamerules;
|
||||
@@ -127,7 +127,6 @@ pub mod nether_portal;
|
||||
pub mod offline_name;
|
||||
pub mod options_file;
|
||||
pub mod options_fixes;
|
||||
pub mod options_horizon;
|
||||
pub mod options_ui;
|
||||
pub mod osk;
|
||||
pub mod overlay;
|
||||
@@ -141,7 +140,6 @@ pub mod player_sync;
|
||||
pub mod poi_sections;
|
||||
pub mod portal_sections;
|
||||
pub mod pose;
|
||||
pub mod post;
|
||||
pub mod projectiles;
|
||||
pub mod raid;
|
||||
pub mod random_sequences;
|
||||
|
||||
@@ -114,6 +114,10 @@ pub enum Kind {
|
||||
Lectern,
|
||||
/// `MerchantMenu`: two payment slots, the result, then the inventory.
|
||||
Merchant,
|
||||
/// `HorseInventoryMenu`: the saddle and body armour slots (`ArmorSlot`s
|
||||
/// of the mount, whose entity type is `Menu::mount`), a chest of three
|
||||
/// rows of this many columns (`getInventoryColumns`), then the inventory.
|
||||
Mount(usize),
|
||||
/// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45
|
||||
/// display slots, then the hotbar.
|
||||
ItemPicker,
|
||||
@@ -124,6 +128,9 @@ impl Kind {
|
||||
if let Some(rows) = name.strip_prefix("chest") {
|
||||
return rows.parse().ok().map(Self::Chest);
|
||||
}
|
||||
if let Some(columns) = name.strip_prefix("mount") {
|
||||
return columns.parse().ok().map(Self::Mount);
|
||||
}
|
||||
Some(match name {
|
||||
"inventory" => Self::Inventory,
|
||||
"crafting" => Self::Crafting,
|
||||
@@ -207,6 +214,9 @@ enum Role {
|
||||
/// `CustomCreativeSlot`: a creative tab's display slot, which the
|
||||
/// screen clicks itself; drags and PICKUP_ALL pass it by.
|
||||
CreativeDisplay,
|
||||
/// An `ArmorSlot` of a mount for this `EquipmentSlot` ("saddle" or
|
||||
/// "body"): `isEquippableInSlot` for `Menu::mount`, one item.
|
||||
MountEquip(&'static str),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -298,6 +308,9 @@ pub struct Menu {
|
||||
pub enchant_button: Option<usize>,
|
||||
/// `Player.mayBuild` (not adventure mode): the lectern's Take Book.
|
||||
pub may_build: bool,
|
||||
/// A mount menu's entity type (`minecraft:horse`): what its saddle and
|
||||
/// body slots take.
|
||||
pub mount: Option<String>,
|
||||
}
|
||||
|
||||
/// `AnvilMenu`'s state besides its slots and `cost`.
|
||||
@@ -560,6 +573,22 @@ impl Menu {
|
||||
// The open page (LecternBlockEntity.dataAccess).
|
||||
data = 1;
|
||||
}
|
||||
Kind::Mount(columns) => {
|
||||
containers[MAIN] = vec![None; 2 + columns * 3];
|
||||
for (index, slot) in ["saddle", "body"].into_iter().enumerate() {
|
||||
slots.push(Slot {
|
||||
container: MAIN,
|
||||
index,
|
||||
role: Role::MountEquip(slot),
|
||||
});
|
||||
}
|
||||
slots.extend((2..2 + columns * 3).map(|index| Slot {
|
||||
container: MAIN,
|
||||
index,
|
||||
role: Role::Plain,
|
||||
}));
|
||||
player(&mut slots);
|
||||
}
|
||||
Kind::ItemPicker => {
|
||||
containers[MAIN] = vec![None; 45];
|
||||
slots.extend(main(45, Role::CreativeDisplay));
|
||||
@@ -654,6 +683,7 @@ impl Menu {
|
||||
enchant_changed: false,
|
||||
enchant_button: None,
|
||||
may_build: true,
|
||||
mount: None,
|
||||
}
|
||||
.with_initial_data()
|
||||
}
|
||||
@@ -1186,6 +1216,15 @@ impl Menu {
|
||||
Some(slot == eq && allowed)
|
||||
})
|
||||
.unwrap_or(false),
|
||||
// LivingEntity.isEquippableInSlot: the item's equippable slot,
|
||||
// and the mount among its allowed entities.
|
||||
Role::MountEquip(slot) => env.items.get(&stack.item).is_some_and(|i| {
|
||||
i.equip_slot.as_deref() == Some(slot)
|
||||
&& self
|
||||
.mount
|
||||
.as_deref()
|
||||
.is_some_and(|m| i.equip_allowed.as_ref().is_none_or(|a| a.contains(m)))
|
||||
}),
|
||||
Role::Shulker => Self::fits_inside(stack),
|
||||
Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack),
|
||||
Role::Output | Role::CraftResult | Role::Inert => false,
|
||||
@@ -1257,7 +1296,7 @@ impl Menu {
|
||||
);
|
||||
o.satisfied_by(env.items, a, b) || o.satisfied_by(env.items, b, a)
|
||||
}),
|
||||
Role::Armor(_) => match self.slot(s) {
|
||||
Role::Armor(_) | Role::MountEquip(_) => match self.slot(s) {
|
||||
Some(stack) => {
|
||||
self.creative || stack.enchantment_level("minecraft:binding_curse") == 0
|
||||
}
|
||||
@@ -1270,7 +1309,11 @@ impl Menu {
|
||||
/// `Slot.getMaxStackSize(stack)`.
|
||||
fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 {
|
||||
let own = match self.slots[s].role {
|
||||
Role::Armor(_) | Role::Potion | Role::EnchantItem | Role::BeaconPay => 1,
|
||||
Role::Armor(_)
|
||||
| Role::MountEquip(_)
|
||||
| Role::Potion
|
||||
| Role::EnchantItem
|
||||
| Role::BeaconPay => 1,
|
||||
// The lectern's bookAccess holds one.
|
||||
Role::Plain if self.kind == Kind::Lectern && self.slots[s].container == MAIN => 1,
|
||||
Role::Fuel if Self::is_bucket(stack) => return 1,
|
||||
@@ -2026,6 +2069,38 @@ impl Menu {
|
||||
}
|
||||
// LecternMenu.quickMoveStack moves nothing.
|
||||
Kind::Lectern => return None,
|
||||
Kind::Mount(columns) => {
|
||||
// AbstractMountInventoryMenu.quickMoveStack: no count check
|
||||
// and no onTake.
|
||||
check_count = false;
|
||||
let start = 2 + columns * 3;
|
||||
if index < start {
|
||||
if !self.move_to(env, &mut stack, start, total, true) {
|
||||
return None;
|
||||
}
|
||||
} else if self.may_place(env, 1, &stack) && self.containers[MAIN][1].is_none() {
|
||||
if !self.move_to(env, &mut stack, 1, 2, false) {
|
||||
return None;
|
||||
}
|
||||
} else if self.may_place(env, 0, &stack) && self.containers[MAIN][0].is_none() {
|
||||
if !self.move_to(env, &mut stack, 0, 1, false) {
|
||||
return None;
|
||||
}
|
||||
} else if columns == 0 || !self.move_to(env, &mut stack, 2, start, false) {
|
||||
// Between the inventory and the hotbar: the stack shrinks
|
||||
// in its slot and EMPTY is returned either way.
|
||||
let (main_end, hotbar_end) = (start + 27, start + 36);
|
||||
if (main_end..hotbar_end).contains(&index) {
|
||||
self.move_to(env, &mut stack, start, main_end, false);
|
||||
} else if (start..main_end).contains(&index) {
|
||||
self.move_to(env, &mut stack, main_end, hotbar_end, false);
|
||||
}
|
||||
let slot = self.slots[index];
|
||||
self.containers[slot.container][slot.index] =
|
||||
(stack.count > 0).then(|| stack.clone());
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Kind::Beacon => {
|
||||
// BeaconMenu.quickMoveStack.
|
||||
after_take = true;
|
||||
@@ -2946,6 +3021,65 @@ pub(crate) mod tests {
|
||||
test(&env, &mut menu);
|
||||
}
|
||||
|
||||
/// `HorseInventoryMenu`: a shift-click wears horse armour, then saddles,
|
||||
/// then fills the chest; the body slot takes only what the mount may wear.
|
||||
#[test]
|
||||
fn mount_menu_slots_take_what_the_mount_wears() {
|
||||
with_menu(Kind::Mount(5), |env, menu| {
|
||||
menu.creative = false;
|
||||
menu.mount = Some("minecraft:donkey".into());
|
||||
// 2 saddle and body, 15 chest, then the inventory from 17.
|
||||
assert_eq!(menu.slot_count(), 2 + 15 + 36);
|
||||
let hotbar = 17 + 27;
|
||||
menu.set_slot(env, hotbar, stack("iron_horse_armor", 1));
|
||||
menu.click(env, hotbar as i32, 0, Input::QuickMove).unwrap();
|
||||
// A donkey wears no horse armour: it goes in the chest.
|
||||
assert_eq!(menu.slot(1), None);
|
||||
assert_eq!(
|
||||
menu.slot(2).map(|s| &*s.item),
|
||||
Some("minecraft:iron_horse_armor")
|
||||
);
|
||||
menu.set_slot(env, hotbar, stack("saddle", 1));
|
||||
menu.click(env, hotbar as i32, 0, Input::QuickMove).unwrap();
|
||||
assert_eq!(menu.slot(0).map(|s| &*s.item), Some("minecraft:saddle"));
|
||||
// Back out of the mount: to the inventory, from the hotbar's end.
|
||||
menu.click(env, 0, 0, Input::QuickMove).unwrap();
|
||||
assert_eq!(menu.slot(0), None);
|
||||
assert_eq!(
|
||||
menu.slot(17 + 35).map(|s| &*s.item),
|
||||
Some("minecraft:saddle")
|
||||
);
|
||||
});
|
||||
with_menu(Kind::Mount(0), |env, menu| {
|
||||
menu.creative = false;
|
||||
menu.mount = Some("minecraft:horse".into());
|
||||
let hotbar = 2 + 27;
|
||||
menu.set_slot(env, hotbar, stack("diamond_horse_armor", 1));
|
||||
menu.click(env, hotbar as i32, 0, Input::QuickMove).unwrap();
|
||||
assert_eq!(
|
||||
menu.slot(1).map(|s| &*s.item),
|
||||
Some("minecraft:diamond_horse_armor")
|
||||
);
|
||||
// No chest: dirt goes between the hotbar and the inventory.
|
||||
menu.set_slot(env, hotbar, stack("dirt", 3));
|
||||
menu.click(env, hotbar as i32, 0, Input::QuickMove).unwrap();
|
||||
assert_eq!(
|
||||
menu.slot(2).map(|s| (&*s.item, s.count)),
|
||||
Some(("minecraft:dirt", 3))
|
||||
);
|
||||
assert_eq!(menu.slot(hotbar), None);
|
||||
// Placing by hand: a saddle doesn't go in the body slot.
|
||||
menu.carried = stack("saddle", 1);
|
||||
menu.click(env, 1, 0, Input::Pickup).unwrap();
|
||||
assert_eq!(
|
||||
menu.slot(1).map(|s| &*s.item),
|
||||
Some("minecraft:diamond_horse_armor")
|
||||
);
|
||||
menu.click(env, 0, 0, Input::Pickup).unwrap();
|
||||
assert_eq!(menu.slot(0).map(|s| &*s.item), Some("minecraft:saddle"));
|
||||
});
|
||||
}
|
||||
|
||||
/// `onEquipItem` runs from the armour and off-hand slots' `setByPlayer`
|
||||
/// when the item changes: never from `Inventory.setItem` (a swap's source).
|
||||
#[test]
|
||||
|
||||
@@ -1317,31 +1317,67 @@ impl Mob {
|
||||
/// `Entity.push` on other mobs acts at once in vanilla: a mob ticking later
|
||||
/// moves with it this tick. Takes the `Push` events aimed at mobs out of
|
||||
/// `events[from..]` into `pending`, which the caller adds to each mob's
|
||||
/// velocity before its tick (and to every mob once all have ticked).
|
||||
pub fn take_mob_pushes(events: &mut Vec<MobEvent>, from: usize, pending: &mut Vec<(u32, Vec3)>) {
|
||||
let mut i = from;
|
||||
while i < events.len() {
|
||||
/// velocity before its tick (and to every mob once all have ticked). The
|
||||
/// other events keep their order.
|
||||
pub fn take_mob_pushes(events: &mut Vec<MobEvent>, from: usize, pending: &mut PendingPushes) {
|
||||
// One pass: a crowd's tick holds a push per neighbour, and removing each
|
||||
// in place would shift the rest every time.
|
||||
let mut kept = from;
|
||||
for i in from..events.len() {
|
||||
if let MobEvent::Push {
|
||||
target: Who::Mob(id),
|
||||
velocity,
|
||||
} = events[i]
|
||||
{
|
||||
pending.push((id, Vec3::new(velocity[0], velocity[1], velocity[2])));
|
||||
events.remove(i);
|
||||
pending.push(id, Vec3::new(velocity[0], velocity[1], velocity[2]));
|
||||
} else {
|
||||
i += 1;
|
||||
events.swap(kept, i);
|
||||
kept += 1;
|
||||
}
|
||||
}
|
||||
events.truncate(kept);
|
||||
}
|
||||
/// Pushes waiting for their mob's tick, in push order. A list while short;
|
||||
/// past [`PendingPushes::LIST_MAX`] (a crowd pushing each other) one list
|
||||
/// per mob, as scanning the whole list for each mob grows with its square.
|
||||
#[derive(Default)]
|
||||
pub struct PendingPushes {
|
||||
list: Vec<(u32, Vec3)>,
|
||||
by_mob: crate::fast_hash::FxHashMap<u32, Vec<Vec3>>,
|
||||
}
|
||||
impl PendingPushes {
|
||||
const LIST_MAX: usize = 64;
|
||||
pub fn push(&mut self, id: u32, v: Vec3) {
|
||||
if self.by_mob.is_empty() && self.list.len() < Self::LIST_MAX {
|
||||
self.list.push((id, v));
|
||||
return;
|
||||
}
|
||||
// Older pushes first, so each mob's stay in order.
|
||||
for (id, v) in self.list.drain(..) {
|
||||
self.by_mob.entry(id).or_default().push(v);
|
||||
}
|
||||
self.by_mob.entry(id).or_default().push(v);
|
||||
}
|
||||
}
|
||||
/// Adds the pending pushes aimed at `m` to its velocity, in push order.
|
||||
pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) {
|
||||
pending.retain(|(id, v)| {
|
||||
if *id != m.id {
|
||||
return true;
|
||||
}
|
||||
pub fn apply_mob_pushes(m: &mut Mob, pending: &mut PendingPushes) {
|
||||
let mut add = |v: Vec3| {
|
||||
m.velocity = Vec3::new(m.velocity.x + v.x, m.velocity.y + v.y, m.velocity.z + v.z);
|
||||
false
|
||||
});
|
||||
};
|
||||
if !pending.list.is_empty() {
|
||||
pending.list.retain(|(id, v)| {
|
||||
if *id != m.id {
|
||||
return true;
|
||||
}
|
||||
add(*v);
|
||||
false
|
||||
});
|
||||
}
|
||||
if !pending.by_mob.is_empty()
|
||||
&& let Some(pushes) = pending.by_mob.remove(&m.id)
|
||||
{
|
||||
pushes.into_iter().for_each(add);
|
||||
}
|
||||
}
|
||||
/// Applies the brain memories a mob's tick set on other mobs (from event
|
||||
/// index `from` on), at once: vanilla sets them on the other entity during
|
||||
@@ -2436,3 +2472,221 @@ mod sensor_scan_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod push_tests {
|
||||
use super::*;
|
||||
use horizon_core::geometry::Vec3;
|
||||
use serde_json::json;
|
||||
|
||||
fn kind() -> Arc<MobType> {
|
||||
Arc::new(MobType {
|
||||
id: "minecraft:cow".into(),
|
||||
species: Species::Cow,
|
||||
width: 0.9,
|
||||
height: 1.4,
|
||||
eye_height: 1.3,
|
||||
category: "creature".into(),
|
||||
max_health: 10.0,
|
||||
speed: 0.2,
|
||||
flying_speed: 0.4,
|
||||
attack_damage: 0.0,
|
||||
attack_knockback: 0.0,
|
||||
follow_range: 16.0,
|
||||
step_height: 0.6,
|
||||
armor: 0.0,
|
||||
armor_toughness: 0.0,
|
||||
knockback_resistance: 0.0,
|
||||
jump_strength: 0.42,
|
||||
attributes: Arc::default(),
|
||||
gravity: 0.08,
|
||||
safe_fall_distance: 3.0,
|
||||
fall_damage_multiplier: 1.0,
|
||||
water_efficiency: 0.0,
|
||||
water_slowdown: 0.8,
|
||||
air_speed: 0.02,
|
||||
baby_scale: 0.5,
|
||||
head_rot_speed: 10.0,
|
||||
max_head_x_rot: 40.0,
|
||||
max_head_y_rot: 75.0,
|
||||
ambient_interval: 120,
|
||||
flags: Flags {
|
||||
animal: true,
|
||||
..Default::default()
|
||||
},
|
||||
model: Arc::new(Part::parse("root", &json!({}))),
|
||||
layers: HashMap::new(),
|
||||
texture: String::new(),
|
||||
brain: Brain::Passive,
|
||||
anim: Anim::Rabbit,
|
||||
sounds: [""; 3],
|
||||
step_sound: None,
|
||||
food: Arc::default(),
|
||||
tempt: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The pending pushes as one list, scanned for each mob, as before.
|
||||
fn take_old(events: &mut Vec<MobEvent>, from: usize, pending: &mut Vec<(u32, Vec3)>) {
|
||||
let mut i = from;
|
||||
while i < events.len() {
|
||||
if let MobEvent::Push {
|
||||
target: Who::Mob(id),
|
||||
velocity,
|
||||
} = events[i]
|
||||
{
|
||||
pending.push((id, Vec3::new(velocity[0], velocity[1], velocity[2])));
|
||||
events.remove(i);
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn apply_old(velocity: &mut Vec3, id: u32, pending: &mut Vec<(u32, Vec3)>) {
|
||||
pending.retain(|(to, v)| {
|
||||
if *to != id {
|
||||
return true;
|
||||
}
|
||||
*velocity = Vec3::new(velocity.x + v.x, velocity.y + v.y, velocity.z + v.z);
|
||||
false
|
||||
});
|
||||
}
|
||||
fn mobs(n: u32) -> Vec<Mob> {
|
||||
let kind = kind();
|
||||
(0..n)
|
||||
.map(|id| Mob::new(id, kind.clone(), Vec3::ZERO, 0.0))
|
||||
.collect()
|
||||
}
|
||||
/// A crowd tick: each mob takes its pushes, then pushes every other
|
||||
/// mob (and the player, and hisses now and then); then all take theirs.
|
||||
fn crowd_tick(
|
||||
n: u32,
|
||||
tick: u32,
|
||||
mut on_push: impl FnMut(&mut Vec<MobEvent>, usize),
|
||||
mut on_apply: impl FnMut(u32),
|
||||
) -> Vec<MobEvent> {
|
||||
let mut events = Vec::new();
|
||||
for i in 0..n {
|
||||
on_apply(i);
|
||||
let from = events.len();
|
||||
for j in 0..n {
|
||||
if j != i && !(i * 31 + j * 17 + tick).is_multiple_of(5) {
|
||||
let f = f64::from(i * 7 + j + tick) * 0.001;
|
||||
events.push(MobEvent::Push {
|
||||
target: Who::Mob(j),
|
||||
velocity: [f, -f * 0.5, f * 0.25],
|
||||
});
|
||||
}
|
||||
if j.is_multiple_of(9) {
|
||||
events.push(MobEvent::Hiss { mob: j });
|
||||
}
|
||||
}
|
||||
events.push(MobEvent::Push {
|
||||
target: Who::Player,
|
||||
velocity: [0.1, 0.0, 0.1],
|
||||
});
|
||||
on_push(&mut events, from);
|
||||
}
|
||||
for i in 0..n {
|
||||
on_apply(i);
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pushes_land_as_with_the_list() {
|
||||
for n in [1u32, 3, 8, 20, 60] {
|
||||
let mut new_mobs = mobs(n);
|
||||
let mut old_v = vec![Vec3::ZERO; n as usize];
|
||||
let mut pending = PendingPushes::default();
|
||||
let mut old_pending = Vec::new();
|
||||
for tick in 0..4 {
|
||||
let new_events = {
|
||||
let pending = std::cell::RefCell::new(&mut pending);
|
||||
let mobs = std::cell::RefCell::new(&mut new_mobs);
|
||||
crowd_tick(
|
||||
n,
|
||||
tick,
|
||||
|e, from| take_mob_pushes(e, from, &mut pending.borrow_mut()),
|
||||
|i| {
|
||||
apply_mob_pushes(
|
||||
&mut mobs.borrow_mut()[i as usize],
|
||||
&mut pending.borrow_mut(),
|
||||
)
|
||||
},
|
||||
)
|
||||
};
|
||||
let old_events = {
|
||||
let pending = std::cell::RefCell::new(&mut old_pending);
|
||||
let v = std::cell::RefCell::new(&mut old_v);
|
||||
crowd_tick(
|
||||
n,
|
||||
tick,
|
||||
|e, from| take_old(e, from, &mut pending.borrow_mut()),
|
||||
|i| {
|
||||
apply_old(
|
||||
&mut v.borrow_mut()[i as usize],
|
||||
i,
|
||||
&mut pending.borrow_mut(),
|
||||
)
|
||||
},
|
||||
)
|
||||
};
|
||||
assert_eq!(format!("{new_events:?}"), format!("{old_events:?}"));
|
||||
for i in 0..n as usize {
|
||||
let (a, b) = (new_mobs[i].velocity, old_v[i]);
|
||||
assert_eq!(
|
||||
(a.x.to_bits(), a.y.to_bits(), a.z.to_bits()),
|
||||
(b.x.to_bits(), b.y.to_bits(), b.z.to_bits()),
|
||||
"{n} mobs, tick {tick}, mob {i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One tick of a pen of `n` mobs pushing each other.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn push_cost() {
|
||||
for n in [10u32, 30, 100, 200] {
|
||||
let mut ms = mobs(n);
|
||||
let mut v = vec![Vec3::ZERO; n as usize];
|
||||
let t = std::time::Instant::now();
|
||||
{
|
||||
let pending = std::cell::RefCell::new(Vec::new());
|
||||
let v = std::cell::RefCell::new(&mut v);
|
||||
crowd_tick(
|
||||
n,
|
||||
0,
|
||||
|e, from| take_old(e, from, &mut pending.borrow_mut()),
|
||||
|i| {
|
||||
apply_old(
|
||||
&mut v.borrow_mut()[i as usize],
|
||||
i,
|
||||
&mut pending.borrow_mut(),
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
let before = t.elapsed().as_secs_f64() * 1e3;
|
||||
let t = std::time::Instant::now();
|
||||
{
|
||||
let pending = std::cell::RefCell::new(PendingPushes::default());
|
||||
let ms = std::cell::RefCell::new(&mut ms);
|
||||
crowd_tick(
|
||||
n,
|
||||
0,
|
||||
|e, from| take_mob_pushes(e, from, &mut pending.borrow_mut()),
|
||||
|i| {
|
||||
apply_mob_pushes(
|
||||
&mut ms.borrow_mut()[i as usize],
|
||||
&mut pending.borrow_mut(),
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
let after = t.elapsed().as_secs_f64() * 1e3;
|
||||
println!("{n} mobs pushing each other: {before:.3} ms -> {after:.3} ms");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,15 +338,21 @@ pub fn ridden_step(m: &mut Mob) {
|
||||
// Pig/Strider: always forward along the rider's look, at a fraction
|
||||
// of the movement speed, boosted by the stick.
|
||||
m.head_pitch = r.pitch * 0.5;
|
||||
m.ai.xxa = 0.0;
|
||||
m.ai.zza = 1.0;
|
||||
// Strider.getRiddenSpeed: slower while it shivers out of the warmth.
|
||||
let factor = if m.species() == Species::Pig {
|
||||
0.225
|
||||
} else if super::strider::suffocating(m) {
|
||||
0.35
|
||||
} else {
|
||||
0.55
|
||||
};
|
||||
let boost = boost_factor(m);
|
||||
m.set_speed((m.attrs.speed * factor) as f32 * boost);
|
||||
// travelRidden: setSpeed(getRiddenSpeed), then travel(getRiddenInput);
|
||||
// the input is set after the speed (Mob.setSpeed also sets zza).
|
||||
// getAttributeValue(MOVEMENT_SPEED): with the cold strider's modifier.
|
||||
m.set_speed((m.movement_speed() * factor) as f32 * boost);
|
||||
m.ai.xxa = 0.0;
|
||||
m.ai.zza = 1.0;
|
||||
return;
|
||||
}
|
||||
if super::camel::is_camel(m.species()) {
|
||||
@@ -366,14 +372,14 @@ pub fn ridden_step(m: &mut Mob) {
|
||||
} else {
|
||||
r.forward
|
||||
};
|
||||
m.ai.xxa = r.strafe * 0.5;
|
||||
m.ai.zza = forward;
|
||||
let bonus = if r.sprint && m.extra.anim_ticks == 0 {
|
||||
0.1
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
m.set_speed(m.attrs.speed as f32 + bonus);
|
||||
m.set_speed(m.movement_speed() as f32 + bonus);
|
||||
m.ai.xxa = r.strafe * 0.5;
|
||||
m.ai.zza = forward;
|
||||
if r.jump > 0.0 {
|
||||
let mut ev = Vec::new();
|
||||
super::camel::dash(m, r.jump, &mut ev);
|
||||
@@ -394,10 +400,10 @@ pub fn ridden_step(m: &mut Mob) {
|
||||
} else {
|
||||
r.forward
|
||||
};
|
||||
let speed = m.movement_speed() as f32;
|
||||
m.set_speed(speed);
|
||||
m.ai.xxa = r.strafe * 0.5;
|
||||
m.ai.zza = forward;
|
||||
let speed = m.attrs.speed as f32;
|
||||
m.set_speed(speed);
|
||||
if m.on_ground && r.jump > 0.0 {
|
||||
// executeRidersJump
|
||||
let impulse = m.extra.vector[0] as f32 * r.jump;
|
||||
|
||||
@@ -538,6 +538,37 @@ impl<'a> Plan<'a> {
|
||||
}
|
||||
}
|
||||
"items.json" => self.items(doc, true),
|
||||
"registries.json" => {
|
||||
// Network ids: the game and its server map items and blocks through
|
||||
// this report, so new ones get the ids after vanilla's, in plan order.
|
||||
let new_items = self.items.iter().map(|i| i.rename.to.clone());
|
||||
let new_blocks = self.blocks.iter().map(|b| b.decl.id.clone());
|
||||
for (registry, names) in [
|
||||
("minecraft:item", new_items.collect::<Vec<_>>()),
|
||||
("minecraft:block", new_blocks.collect()),
|
||||
] {
|
||||
let Some(J::Obj(entries)) =
|
||||
doc.get_mut(registry).and_then(|r| r.get_mut("entries"))
|
||||
else {
|
||||
return Err(format!("no {registry} entries").into());
|
||||
};
|
||||
let next = entries
|
||||
.iter()
|
||||
.filter_map(|(_, e)| match e {
|
||||
J::Obj(o) => o.iter().find(|(k, _)| k == "protocol_id")?.1.as_u32(),
|
||||
_ => None,
|
||||
})
|
||||
.max()
|
||||
.map_or(0, |m| m + 1);
|
||||
for (i, name) in names.into_iter().enumerate() {
|
||||
if entries.iter().any(|(k, _)| *k == name) {
|
||||
continue;
|
||||
}
|
||||
let id = J::Num((next + i as u32).into());
|
||||
entries.push((name, J::Obj(vec![("protocol_id".into(), id)])));
|
||||
}
|
||||
}
|
||||
}
|
||||
"command-registries.json" => {
|
||||
self.names(doc.at("blocks").ok_or("no blocks")?, false);
|
||||
let new_items = || self.items.iter().map(|i| J::Str(i.rename.to.clone()));
|
||||
@@ -618,8 +649,9 @@ impl<'a> Plan<'a> {
|
||||
}
|
||||
|
||||
/// The JSON and NBT tables rewritten for new blocks and items.
|
||||
const JSON_TABLES: [&str; 13] = [
|
||||
const JSON_TABLES: [&str; 14] = [
|
||||
"facts.json",
|
||||
"registries.json",
|
||||
"gameplay-facts.json",
|
||||
"block-behaviours.json",
|
||||
"model-states.json",
|
||||
|
||||
@@ -148,6 +148,35 @@ fn content_root_loads_with_every_table() {
|
||||
new.default_state("ruby:ruby_glass"),
|
||||
Some(BlockStateId(n + 65))
|
||||
);
|
||||
// Network ids: the new items and blocks follow vanilla's in the registries report, which
|
||||
// the game and its server both read (a missing one travels as air).
|
||||
let report = |root: &Path| {
|
||||
horizon_protocol::registry::Builtin::load(&root.join("registries.json")).unwrap()
|
||||
};
|
||||
let (vanilla_ids, ids) = (report(&base), report(&root));
|
||||
let item = |b: &horizon_protocol::registry::Builtin, name: &str| {
|
||||
b.get("minecraft:item").and_then(|r| r.id(name))
|
||||
};
|
||||
let vanilla_items = (0..)
|
||||
.take_while(|&i| vanilla_ids.get("minecraft:item").unwrap().name(i).is_some())
|
||||
.count() as i32;
|
||||
assert_eq!(
|
||||
item(&ids, "minecraft:stone"),
|
||||
item(&vanilla_ids, "minecraft:stone")
|
||||
);
|
||||
let ruby_item = item(&ids, "ruby:ruby_block").unwrap();
|
||||
assert!(ruby_item >= vanilla_items, "{ruby_item} < {vanilla_items}");
|
||||
assert_eq!(
|
||||
ids.get("minecraft:item").unwrap().name(ruby_item),
|
||||
Some("ruby:ruby_block")
|
||||
);
|
||||
assert!(item(&ids, "ruby:ruby_glass").is_none(), "no item declared");
|
||||
assert!(
|
||||
ids.get("minecraft:block")
|
||||
.unwrap()
|
||||
.id("ruby:ruby_glass")
|
||||
.is_some()
|
||||
);
|
||||
|
||||
let old_facts = BlockFacts::load(&base, old).unwrap();
|
||||
let facts = BlockFacts::load(&root, new).unwrap();
|
||||
|
||||
@@ -716,7 +716,8 @@ impl MotionWorld<'_, '_, '_> {
|
||||
supporting_block: self.player.ground.supporting_block,
|
||||
}
|
||||
}
|
||||
fn climbable(&mut self) -> Result<bool> {
|
||||
/// `LivingEntity.onClimbable` at the player's feet (it remembers the block).
|
||||
pub fn climbable(&mut self) -> Result<bool> {
|
||||
if self.player.spectator {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@@ -78,8 +78,8 @@ pub enum Screen {
|
||||
name: String,
|
||||
lines: std::cell::Cell<usize>,
|
||||
},
|
||||
/// Join a friend's world with its invite code (Horizon's own, reached
|
||||
/// from Horizon's multiplayer page).
|
||||
/// Join a friend's world with its invite code (Horizon's own, behind the
|
||||
/// title screen's Friends button).
|
||||
Friend {
|
||||
code: String,
|
||||
/// The relay for short codes (optional; saved on Join).
|
||||
@@ -373,13 +373,6 @@ impl Screen {
|
||||
}
|
||||
}
|
||||
|
||||
/// The address of list row `row` (saved servers, then LAN games).
|
||||
pub fn address_of(&self, row: usize) -> Option<String> {
|
||||
match self {
|
||||
Self::List { servers, lan, .. } => entry_address(servers, lan, row),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn list(saves: &Path) -> Self {
|
||||
let servers = servers::load(&servers_file(saves));
|
||||
let pings: Pings = Arc::default();
|
||||
@@ -1162,7 +1155,7 @@ impl Screen {
|
||||
) => *self = Self::list(saves),
|
||||
(Self::Disconnected { retry, .. }, Some(55)) => *retry = None,
|
||||
(Self::Direct { address }, Some(52)) => {
|
||||
return Outcome::Connect(address.trim().to_owned());
|
||||
return Outcome::Connect(direct_address(address));
|
||||
}
|
||||
(Self::Friend { code, relay, .. }, Some(56)) => {
|
||||
if horizon_friends::invite::parse(code).is_some() {
|
||||
@@ -1326,6 +1319,19 @@ impl Screen {
|
||||
}
|
||||
}
|
||||
|
||||
/// Direct Connection's address; a full invite code pasted there joins the
|
||||
/// friend (a short relay code could be a host name, so it needs Join a Friend).
|
||||
fn direct_address(address: &str) -> String {
|
||||
let code: String = address.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
if matches!(
|
||||
horizon_friends::invite::parse(&code),
|
||||
Some(horizon_friends::invite::Parsed::Long(_))
|
||||
) {
|
||||
format!("{}{code}", crate::net::FRIEND)
|
||||
} else {
|
||||
address.trim().to_owned()
|
||||
}
|
||||
}
|
||||
/// Greedy word wrap to a pixel width.
|
||||
pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
@@ -1353,6 +1359,24 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn direct_connection_joins_a_pasted_invite_and_keeps_host_names() {
|
||||
let invite = horizon_friends::invite::Invite {
|
||||
secret: *b"0123456789",
|
||||
port: 25580,
|
||||
endpoints: vec!["192.168.1.20:25580".parse().unwrap()],
|
||||
relay: None,
|
||||
}
|
||||
.encode();
|
||||
assert_eq!(
|
||||
direct_address(&format!(" {invite} ")),
|
||||
format!("{}{invite}", crate::net::FRIEND)
|
||||
);
|
||||
for host in ["localhost", "example.org:25566", "abcdefgh", "[::1]:25568"] {
|
||||
assert_eq!(direct_address(host), host);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ping_tooltip_follows_only_visible_status_bars_and_current_ping() {
|
||||
let servers: Vec<_> = (0..6)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -130,7 +130,7 @@ pub(crate) enum Kind {
|
||||
Slider(f32),
|
||||
Cycle,
|
||||
}
|
||||
/// Options shared by the Classic page and Horizon's Accessibility section.
|
||||
/// The Accessibility Settings page:
|
||||
/// `AccessibilityOptionsScreen.options`, with the Controls link inserted separately.
|
||||
pub(crate) const ACCESSIBILITY_OPTIONS: &[Opt] = &[
|
||||
Opt::Narrator,
|
||||
@@ -871,6 +871,9 @@ pub enum Page {
|
||||
Controller,
|
||||
PadBinds,
|
||||
Extras,
|
||||
/// Horizon Settings: every page Horizon adds, as a mod's settings
|
||||
/// screen hangs off vanilla's Options.
|
||||
Horizon,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Act {
|
||||
@@ -886,8 +889,6 @@ enum Act {
|
||||
PadKey(&'static str),
|
||||
ResetPadKey(&'static str),
|
||||
ResetPadKeys,
|
||||
/// Back to Horizon's own menus (Horizon only, see `list_rows`).
|
||||
HorizonMenus,
|
||||
ToggleMod(usize),
|
||||
OpenModFolder,
|
||||
/// Pick shader pack `i` of `OptionsUi::shader_packs` (again: off).
|
||||
@@ -968,15 +969,8 @@ pub struct OptionsUi {
|
||||
/// when it last moved: the handle follows the pointer while the option
|
||||
/// keeps its stepped value, then snaps to it (`resetValue`).
|
||||
slider_value: Option<(Opt, f32, Instant)>,
|
||||
/// The pointer's last y while a Classic or Horizon scrollbar is held.
|
||||
/// The pointer's last y while a scrollbar is held.
|
||||
pub(crate) scrollbar_drag_y: Option<f32>,
|
||||
/// Horizon style: the selected sidebar section, the one last drawn and
|
||||
/// the rows' scroll in dp (`options_horizon`).
|
||||
pub section: usize,
|
||||
pub(crate) section_shown: Option<usize>,
|
||||
pub(crate) hscroll: f32,
|
||||
/// The slider being dragged on the Horizon options shell.
|
||||
pub(crate) hdragging: Option<crate::graphics_ui::Item>,
|
||||
/// Key Binds: the mapping waiting for a key.
|
||||
pub selected_key: Option<&'static str>,
|
||||
/// Controller Binds: the action waiting for a pad button.
|
||||
@@ -1017,10 +1011,6 @@ impl Default for OptionsUi {
|
||||
dragging: None,
|
||||
slider_value: None,
|
||||
scrollbar_drag_y: None,
|
||||
section: 0,
|
||||
section_shown: None,
|
||||
hscroll: 0.0,
|
||||
hdragging: None,
|
||||
selected_key: None,
|
||||
selected_pad_action: None,
|
||||
pad_style: GlyphStyle::Xbox,
|
||||
@@ -1081,6 +1071,27 @@ fn option_widget(s: &Settings, opt: Opt, x: f32, y: f32, w: f32) -> Widget {
|
||||
Kind::Cycle => button(x, y, w, opt.label(s), Act::Cycle(opt)),
|
||||
}
|
||||
}
|
||||
/// What a button opening one of Horizon's pages says on hover.
|
||||
fn horizon_page_tooltip(page: Page) -> Option<&'static str> {
|
||||
Some(match page {
|
||||
Page::Horizon => {
|
||||
"Horizon's own settings: graphics, shader packs, controllers, extras and mods."
|
||||
}
|
||||
Page::Graphics => "Graphics, simply: each setting says what it costs.",
|
||||
Page::GraphicsAdvanced => {
|
||||
"Every graphics setting, Horizon's included, with what each costs."
|
||||
}
|
||||
Page::ShaderPacks => "Packs that redraw the world. Off is the vanilla look.",
|
||||
Page::Controller => "Controllers: their buttons, sticks, vibration and menu navigation.",
|
||||
Page::Extras => {
|
||||
"Optional additions, all off by default: the game stays vanilla until you turn one on."
|
||||
}
|
||||
Page::Mods => {
|
||||
"Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on."
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// Rows of an OptionsList: (big?, options) or a header.
|
||||
enum Row {
|
||||
Big(Opt),
|
||||
@@ -1098,10 +1109,7 @@ fn pairs(opts: &[Opt]) -> Vec<Row> {
|
||||
impl OptionsUi {
|
||||
fn settings_search_active(&self) -> bool {
|
||||
self.settings_search.focused
|
||||
&& (matches!(self.page(), Page::Video | Page::Controls | Page::KeyBinds)
|
||||
|| (crate::ui_theme::horizon()
|
||||
&& self.page() == Page::Main
|
||||
&& crate::options_horizon::searchable_section(self.section)))
|
||||
&& matches!(self.page(), Page::Video | Page::Controls | Page::KeyBinds)
|
||||
}
|
||||
pub fn page(&self) -> Page {
|
||||
*self.stack.last().unwrap_or(&Page::Main)
|
||||
@@ -1122,10 +1130,6 @@ impl OptionsUi {
|
||||
self.in_world = in_world;
|
||||
self.selected_key = None;
|
||||
}
|
||||
/// Open one of vanilla's pages over the current one.
|
||||
pub(crate) fn open_page(&mut self, page: Page) {
|
||||
self.push(page);
|
||||
}
|
||||
fn push(&mut self, page: Page) {
|
||||
self.stack.push(page);
|
||||
self.scroll = 0.0;
|
||||
@@ -1164,14 +1168,9 @@ impl OptionsUi {
|
||||
.as_ref()
|
||||
.is_some_and(|(e, _)| e == id)
|
||||
}
|
||||
/// Whether the Shader Packs page (or the Horizon menus' section) shows.
|
||||
/// Whether the Shader Packs page shows.
|
||||
fn shader_packs_shown(&self) -> bool {
|
||||
self.page() == Page::ShaderPacks
|
||||
|| crate::ui_theme::horizon()
|
||||
&& self.page() == Page::Main
|
||||
&& crate::options_horizon::SECTIONS
|
||||
.get(self.section)
|
||||
.is_some_and(|s| s.name == crate::options_horizon::SHADER_PACKS)
|
||||
}
|
||||
/// The graphics screen level of `page`, if it is one.
|
||||
fn graphics_level(page: Page) -> Option<crate::graphics_ui::Level> {
|
||||
@@ -1200,6 +1199,7 @@ impl OptionsUi {
|
||||
Page::Controller => "Controller Settings",
|
||||
Page::PadBinds => "Controller Binds",
|
||||
Page::Extras => "Horizon Extras",
|
||||
Page::Horizon => "Horizon Settings",
|
||||
}
|
||||
}
|
||||
fn scrollbar_x(&self, width: f32) -> f32 {
|
||||
@@ -1263,7 +1263,17 @@ impl OptionsUi {
|
||||
} else {
|
||||
Text::literal(value)
|
||||
};
|
||||
button(0.0, 0.0, 150.0, label, Act::Extra(item))
|
||||
let widget = button(0.0, 0.0, 150.0, label, Act::Extra(item));
|
||||
// A setting of a switch that is off does nothing: inactive,
|
||||
// as vanilla greys out an option that can't apply.
|
||||
if item
|
||||
.parent()
|
||||
.is_some_and(|parent| parent.switch(&s.extras) == Some(false))
|
||||
{
|
||||
inactive(widget)
|
||||
} else {
|
||||
widget
|
||||
}
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
let mut section = Vec::new();
|
||||
@@ -1287,6 +1297,27 @@ impl OptionsUi {
|
||||
flush(&mut rows, &mut section);
|
||||
rows
|
||||
}
|
||||
Page::Horizon => {
|
||||
// Two to a row, as vanilla's OptionsList.addSmall lays out
|
||||
// buttons; each opens a page built from vanilla's widgets.
|
||||
let open = |label: &str, page: Page| {
|
||||
button(0.0, 0.0, 150.0, Text::literal(label), Act::Push(page))
|
||||
};
|
||||
vec![
|
||||
Row::Buttons(
|
||||
open("Graphics...", Page::Graphics),
|
||||
Some(open("Advanced Graphics...", Page::GraphicsAdvanced)),
|
||||
),
|
||||
Row::Buttons(
|
||||
open("Shader Packs...", Page::ShaderPacks),
|
||||
Some(open("Controller Settings...", Page::Controller)),
|
||||
),
|
||||
Row::Buttons(
|
||||
open("Extras...", Page::Extras),
|
||||
Some(open("Mods...", Page::Mods)),
|
||||
),
|
||||
]
|
||||
}
|
||||
Page::Video => {
|
||||
// Horizon's graphics screens, Simple and Advanced.
|
||||
let mut rows = vec![Row::Buttons(
|
||||
@@ -1315,22 +1346,6 @@ impl OptionsUi {
|
||||
),
|
||||
None,
|
||||
));
|
||||
// The way back from Classic menus. Horizon-only like the row
|
||||
// above, here rather than on the main Options screen so that
|
||||
// one keeps vanilla's exact layout; vanilla's interface
|
||||
// settings (GUI Scale) are on this page too.
|
||||
if !crate::ui_theme::horizon() {
|
||||
rows.push(Row::Buttons(
|
||||
button(
|
||||
0.0,
|
||||
0.0,
|
||||
310.0,
|
||||
Text::literal("Menu Style: Classic"),
|
||||
Act::HorizonMenus,
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
rows.push(Row::Header("options.video.display.header"));
|
||||
rows.extend(pairs(&[
|
||||
Opt::MaxFps,
|
||||
@@ -1578,8 +1593,10 @@ impl OptionsUi {
|
||||
("options.chat", Some(Page::Chat)),
|
||||
("options.resourcepack", Some(Page::Packs)),
|
||||
("options.accessibility", Some(Page::Accessibility)),
|
||||
// Vanilla's Telemetry Data and Credits slots: Horizon's
|
||||
// settings and its mods, as a mod adds its button here.
|
||||
("Horizon Settings...", Some(Page::Horizon)),
|
||||
("Mods...", Some(Page::Mods)),
|
||||
("Horizon Extras...", Some(Page::Extras)),
|
||||
];
|
||||
let gy = (61.0 + 30.0f32).min(h - 33.0 - 120.0);
|
||||
for (i, (key, page)) in entries.iter().enumerate() {
|
||||
@@ -2052,10 +2069,6 @@ impl OptionsUi {
|
||||
);
|
||||
return;
|
||||
}
|
||||
if crate::ui_theme::horizon() && self.page() == Page::Main {
|
||||
self.draw_horizon(s, batch, atlas, cursor);
|
||||
return;
|
||||
}
|
||||
if let Some(level) = Self::graphics_level(self.page()) {
|
||||
self.graphics
|
||||
.draw(level, s, batch, atlas, cursor, self.in_world);
|
||||
@@ -2094,6 +2107,14 @@ impl OptionsUi {
|
||||
{
|
||||
tooltip = Some(atlas.font.split(&Text::literal(item.description()), 170.0));
|
||||
}
|
||||
if let WKind::Button {
|
||||
act: Act::Push(page),
|
||||
..
|
||||
} = &wd.kind
|
||||
&& let Some(text) = horizon_page_tooltip(*page)
|
||||
{
|
||||
tooltip = Some(atlas.font.split(&Text::literal(text), 170.0));
|
||||
}
|
||||
let key = match &wd.kind {
|
||||
WKind::Button {
|
||||
act: Act::Cycle(opt),
|
||||
@@ -2300,9 +2321,6 @@ impl OptionsUi {
|
||||
}
|
||||
return Vec::new();
|
||||
}
|
||||
if crate::ui_theme::horizon() && self.page() == Page::Main {
|
||||
return self.click_horizon(s, atlas, x, y, framebuffer, drag, right);
|
||||
}
|
||||
if let Some(level) = Self::graphics_level(self.page()) {
|
||||
use crate::graphics_ui::Action;
|
||||
let mut events = Vec::new();
|
||||
@@ -2471,12 +2489,6 @@ impl OptionsUi {
|
||||
s.controller.reset_bindings();
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Act::HorizonMenus => {
|
||||
self.horizon_menus();
|
||||
if let Ok(dir) = std::env::current_dir() {
|
||||
crate::ui_theme::save_preferences(&dir);
|
||||
}
|
||||
}
|
||||
Act::ToggleMod(i) => {
|
||||
s.mods.toggle(i);
|
||||
events.push(Event::Changed);
|
||||
@@ -2510,20 +2522,6 @@ impl OptionsUi {
|
||||
}
|
||||
events
|
||||
}
|
||||
/// Switch to Horizon's menus and show where the choice lives there
|
||||
/// (Options, Interface, Menu style).
|
||||
fn horizon_menus(&mut self) {
|
||||
crate::ui_theme::set_style(crate::ui_theme::MenuStyle::Horizon);
|
||||
self.stack.truncate(1);
|
||||
self.scroll = 0.0;
|
||||
self.scrollbar_drag_y = None;
|
||||
self.section = crate::options_horizon::SECTIONS
|
||||
.iter()
|
||||
.position(|section| section.name == "Interface")
|
||||
.unwrap_or(0);
|
||||
self.section_shown = None;
|
||||
self.hscroll = 0.0;
|
||||
}
|
||||
/// Where a slider's handle sits: its own position while held (or until
|
||||
/// a delayed one applies), else the option's stepped value.
|
||||
fn slider_shown(&self, opt: Opt, value: f32) -> f32 {
|
||||
@@ -2540,7 +2538,6 @@ impl OptionsUi {
|
||||
// AbstractSliderButton suppresses the press sound and plays once on
|
||||
// release, even if the pointer has left the widget or its value stayed.
|
||||
let slider = self.dragging.take().is_some();
|
||||
self.hdragging = None;
|
||||
let graphics_slider = self.graphics.release();
|
||||
if slider || graphics_slider {
|
||||
vec![Event::ButtonClick]
|
||||
@@ -2558,10 +2555,6 @@ impl OptionsUi {
|
||||
if self.resource_error.is_some() {
|
||||
return;
|
||||
}
|
||||
if crate::ui_theme::horizon() && self.page() == Page::Main {
|
||||
self.scroll_horizon(amount);
|
||||
return;
|
||||
}
|
||||
if let Some(level) = Self::graphics_level(self.page()) {
|
||||
self.graphics.scroll(level, size.1, amount);
|
||||
return;
|
||||
@@ -2783,7 +2776,6 @@ impl OptionsUi {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ui_theme::{MenuStyle, set_style, style};
|
||||
|
||||
#[test]
|
||||
fn accessibility_sliders_and_toggles_survive_options_round_trip() {
|
||||
@@ -3337,9 +3329,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_extras_entry_edits_shared_settings_and_returns_without_changing_style() {
|
||||
let previous_style = style();
|
||||
set_style(MenuStyle::Classic);
|
||||
fn extras_from_horizon_settings_edit_shared_settings_and_return() {
|
||||
let atlas = atlas();
|
||||
let mut s = Settings::default();
|
||||
let mut ui = OptionsUi::default();
|
||||
@@ -3363,11 +3353,13 @@ mod tests {
|
||||
false,
|
||||
)
|
||||
};
|
||||
assert_eq!(
|
||||
click(&mut ui, &mut s, Act::Push(Page::Extras)),
|
||||
vec![Event::ButtonClick]
|
||||
);
|
||||
assert_eq!(ui.page(), Page::Extras);
|
||||
for page in [Page::Horizon, Page::Extras] {
|
||||
assert_eq!(
|
||||
click(&mut ui, &mut s, Act::Push(page)),
|
||||
vec![Event::ButtonClick]
|
||||
);
|
||||
assert_eq!(ui.page(), page);
|
||||
}
|
||||
let (widgets, _, _, _) = ui.layout(&s, size.0, size.1);
|
||||
assert_eq!(
|
||||
widgets
|
||||
@@ -3408,9 +3400,7 @@ mod tests {
|
||||
ui.key(&mut s, &atlas, winit::keyboard::KeyCode::Escape, None),
|
||||
vec![Event::Changed]
|
||||
);
|
||||
assert_eq!(ui.page(), Page::Main);
|
||||
assert_eq!(style(), MenuStyle::Classic);
|
||||
set_style(previous_style);
|
||||
assert_eq!(ui.page(), Page::Horizon);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3994,15 +3984,25 @@ mod tests {
|
||||
let atlas = atlas();
|
||||
let mut s = Settings::default();
|
||||
let mut ui = OptionsUi::default();
|
||||
ui.show(Page::Extras);
|
||||
for (right, expected) in [(false, "key.mouse.left"), (true, "key.mouse.right")] {
|
||||
ui.selected_key = Some(crate::extras::SORT_KEY);
|
||||
assert_eq!(
|
||||
ui.click_horizon(&mut s, &atlas, 2.0, 2.0, [960, 480], false, right),
|
||||
ui.click(
|
||||
&mut s,
|
||||
&atlas,
|
||||
2.0,
|
||||
2.0,
|
||||
(480.0, 240.0),
|
||||
[960, 480],
|
||||
false,
|
||||
right
|
||||
),
|
||||
vec![Event::Changed]
|
||||
);
|
||||
assert_eq!(s.extras.sort_key, expected);
|
||||
assert_eq!(ui.selected_key, None);
|
||||
assert_eq!(ui.section, 0);
|
||||
assert_eq!(ui.page(), Page::Extras);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4116,30 +4116,45 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_video_settings_lead_back_to_horizon_menus() {
|
||||
let previous_style = style();
|
||||
set_style(MenuStyle::Horizon);
|
||||
fn horizon_settings_hang_off_options_and_reach_every_horizon_page() {
|
||||
let s = Settings::default();
|
||||
let mut ui = OptionsUi::default();
|
||||
ui.push(Page::Video);
|
||||
let way_back = |ui: &OptionsUi| {
|
||||
ui.list_rows(&s).iter().any(|row| {
|
||||
matches!(row, Row::Buttons(w, _)
|
||||
if matches!(&w.kind, WKind::Button { act: Act::HorizonMenus, .. }))
|
||||
})
|
||||
let pushes = |ui: &mut OptionsUi| -> Vec<Page> {
|
||||
let (widgets, _, _, _) = ui.layout(&s, 427.0, 240.0);
|
||||
widgets
|
||||
.iter()
|
||||
.filter_map(|w| match &w.kind {
|
||||
WKind::Button {
|
||||
act: Act::Push(page),
|
||||
active: true,
|
||||
..
|
||||
} => Some(*page),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// Horizon's own menus have the choice on their Interface page.
|
||||
assert!(!way_back(&ui));
|
||||
set_style(MenuStyle::Classic);
|
||||
let classic = way_back(&ui);
|
||||
ui.horizon_menus();
|
||||
assert!(classic, "Classic Video Settings offer Menu Style");
|
||||
assert_eq!(style(), MenuStyle::Horizon);
|
||||
assert_eq!(ui.stack, vec![Page::Main]);
|
||||
// Vanilla's ten Options buttons, the last two Horizon's.
|
||||
let main = pushes(&mut ui);
|
||||
assert_eq!(&main[main.len() - 2..], [Page::Horizon, Page::Mods]);
|
||||
ui.push(Page::Horizon);
|
||||
assert_eq!(
|
||||
crate::options_horizon::SECTIONS[ui.section].name,
|
||||
"Interface"
|
||||
pushes(&mut ui),
|
||||
[
|
||||
Page::Graphics,
|
||||
Page::GraphicsAdvanced,
|
||||
Page::ShaderPacks,
|
||||
Page::Controller,
|
||||
Page::Extras,
|
||||
Page::Mods,
|
||||
]
|
||||
);
|
||||
set_style(previous_style);
|
||||
// Vanilla's own pages keep the Horizon pages they had.
|
||||
ui.stack = vec![Page::Main, Page::Video];
|
||||
let video = pushes(&mut ui);
|
||||
for page in [Page::Graphics, Page::GraphicsAdvanced, Page::ShaderPacks] {
|
||||
assert!(video.contains(&page), "{page:?}");
|
||||
}
|
||||
ui.stack = vec![Page::Main, Page::Controls];
|
||||
assert!(pushes(&mut ui).contains(&Page::Controller));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,273 +0,0 @@
|
||||
//! The menus' backdrop treatment (`ui_theme`'s Horizon style): the finished
|
||||
//! world frame is blurred (dual Kawase: three halvings down, back up) and
|
||||
//! colour graded before the HUD is drawn over it. Needs a swapchain that can
|
||||
//! be copied from; without one the frame is left as it is.
|
||||
|
||||
/// How the frame under a Horizon-style menu is treated.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PostGrade {
|
||||
/// Colour multiplier and lift (`c * tint + lift`).
|
||||
pub tint: [f32; 3],
|
||||
pub lift: [f32; 3],
|
||||
/// Toward grey, 0..1.
|
||||
pub desaturate: f32,
|
||||
/// Darkening toward the corners, 0..1.
|
||||
pub vignette: f32,
|
||||
}
|
||||
impl PostGrade {
|
||||
/// The title backdrop: icy, slightly lifted shadows.
|
||||
pub const FROST: Self = Self {
|
||||
tint: [0.62, 0.78, 1.0],
|
||||
lift: [0.0, 0.01, 0.035],
|
||||
desaturate: 0.45,
|
||||
vignette: 0.5,
|
||||
};
|
||||
/// Behind the pause menu: the world stays recognisable.
|
||||
pub const PAUSE: Self = Self {
|
||||
tint: [0.8, 0.86, 0.98],
|
||||
lift: [0.0, 0.004, 0.012],
|
||||
desaturate: 0.25,
|
||||
vignette: 0.3,
|
||||
};
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Uniform {
|
||||
texel: [f32; 4],
|
||||
tint: [f32; 4],
|
||||
lift: [f32; 4],
|
||||
params: [f32; 4],
|
||||
}
|
||||
const LEVELS: usize = 3;
|
||||
pub struct Post {
|
||||
layout: wgpu::BindGroupLayout,
|
||||
down: wgpu::RenderPipeline,
|
||||
up: wgpu::RenderPipeline,
|
||||
finish: wgpu::RenderPipeline,
|
||||
sampler: wgpu::Sampler,
|
||||
/// The copied frame, then the halvings.
|
||||
levels: Vec<(wgpu::Texture, wgpu::TextureView, [u32; 2])>,
|
||||
uniforms: Vec<wgpu::Buffer>,
|
||||
size: [u32; 2],
|
||||
format: wgpu::TextureFormat,
|
||||
}
|
||||
impl Post {
|
||||
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Menu backdrop"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("post.wgsl").into()),
|
||||
});
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Menu backdrop bindings"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Menu backdrop"),
|
||||
bind_group_layouts: &[Some(&layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let pipeline = |entry: &str| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Menu backdrop pass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some(entry),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
primitive: Default::default(),
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Menu backdrop"),
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
..Default::default()
|
||||
});
|
||||
let uniforms = (0..LEVELS * 2 + 1)
|
||||
.map(|_| {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Menu backdrop pass"),
|
||||
size: std::mem::size_of::<Uniform>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
down: pipeline("fs_down"),
|
||||
up: pipeline("fs_up"),
|
||||
finish: pipeline("fs_final"),
|
||||
layout,
|
||||
sampler,
|
||||
levels: Vec::new(),
|
||||
uniforms,
|
||||
size: [0, 0],
|
||||
format,
|
||||
}
|
||||
}
|
||||
fn ensure(&mut self, device: &wgpu::Device, size: [u32; 2]) {
|
||||
if self.size == size && !self.levels.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.size = size;
|
||||
self.levels = (0..=LEVELS)
|
||||
.map(|i| {
|
||||
let s = [(size[0] >> i).max(1), (size[1] >> i).max(1)];
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Menu backdrop level"),
|
||||
size: wgpu::Extent3d {
|
||||
width: s[0],
|
||||
height: s[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: self.format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&Default::default());
|
||||
(texture, view, s)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
fn pass(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
pipeline: &wgpu::RenderPipeline,
|
||||
(from, uniform): (usize, usize),
|
||||
target: &wgpu::TextureView,
|
||||
data: Uniform,
|
||||
) {
|
||||
let (_, view, s) = &self.levels[from];
|
||||
let mut data = data;
|
||||
data.texel = [0.5 / s[0] as f32, 0.5 / s[1] as f32, 0.0, 0.0];
|
||||
queue.write_buffer(&self.uniforms[uniform], 0, bytemuck::bytes_of(&data));
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Menu backdrop pass"),
|
||||
layout: &self.layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(&self.sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.uniforms[uniform].as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: target,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Menu backdrop pass"),
|
||||
color_attachments: &attachments,
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
/// Blur and grade `frame` (the swapchain texture) into `target`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn apply(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
frame: &wgpu::Texture,
|
||||
target: &wgpu::TextureView,
|
||||
size: [u32; 2],
|
||||
grade: &PostGrade,
|
||||
) {
|
||||
self.ensure(device, size);
|
||||
encoder.copy_texture_to_texture(
|
||||
frame.as_image_copy(),
|
||||
self.levels[0].0.as_image_copy(),
|
||||
wgpu::Extent3d {
|
||||
width: size[0],
|
||||
height: size[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
let data = Uniform {
|
||||
texel: [0.0; 4],
|
||||
tint: [grade.tint[0], grade.tint[1], grade.tint[2], 1.0],
|
||||
lift: [grade.lift[0], grade.lift[1], grade.lift[2], 0.0],
|
||||
params: [grade.desaturate, grade.vignette, 0.0, 0.0],
|
||||
};
|
||||
let mut u = 0;
|
||||
for i in 1..=LEVELS {
|
||||
let target = &self.levels[i].1;
|
||||
self.pass(device, queue, encoder, &self.down, (i - 1, u), target, data);
|
||||
u += 1;
|
||||
}
|
||||
for i in (1..LEVELS).rev() {
|
||||
let target = &self.levels[i].1;
|
||||
self.pass(device, queue, encoder, &self.up, (i + 1, u), target, data);
|
||||
u += 1;
|
||||
}
|
||||
self.pass(device, queue, encoder, &self.finish, (1, u), target, data);
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
// Menu backdrop: dual-Kawase blur (down and up passes) and a cold colour grade.
|
||||
struct Post {
|
||||
// Half a source texel (u, v), unused, unused.
|
||||
texel: vec4<f32>,
|
||||
// Multiplier and lift of the grade.
|
||||
tint: vec4<f32>,
|
||||
lift: vec4<f32>,
|
||||
// Desaturation, vignette, unused, unused.
|
||||
params: vec4<f32>,
|
||||
}
|
||||
@group(0) @binding(0) var src: texture_2d<f32>;
|
||||
@group(0) @binding(1) var samp: sampler;
|
||||
@group(0) @binding(2) var<uniform> post: Post;
|
||||
struct Out {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
}
|
||||
@vertex fn vs_main(@builtin(vertex_index) i: u32) -> Out {
|
||||
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
|
||||
var out: Out;
|
||||
out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
|
||||
out.uv = vec2(p.x, 1.0 - p.y);
|
||||
return out;
|
||||
}
|
||||
fn s(uv: vec2<f32>) -> vec3<f32> {
|
||||
return textureSampleLevel(src, samp, uv, 0.0).rgb;
|
||||
}
|
||||
@fragment fn fs_down(in: Out) -> @location(0) vec4<f32> {
|
||||
let h = post.texel.xy;
|
||||
let c = s(in.uv) * 4.0 + s(in.uv - h) + s(in.uv + h) + s(in.uv + vec2(h.x, -h.y)) + s(in.uv - vec2(h.x, -h.y));
|
||||
return vec4(c / 8.0, 1.0);
|
||||
}
|
||||
fn up(uv: vec2<f32>) -> vec3<f32> {
|
||||
let h = post.texel.xy;
|
||||
var c = s(uv + vec2(-h.x * 2.0, 0.0)) + s(uv + vec2(h.x * 2.0, 0.0));
|
||||
c += s(uv + vec2(0.0, -h.y * 2.0)) + s(uv + vec2(0.0, h.y * 2.0));
|
||||
c += (s(uv + vec2(-h.x, h.y)) + s(uv + vec2(h.x, h.y)) + s(uv + vec2(-h.x, -h.y)) + s(uv + vec2(h.x, -h.y))) * 2.0;
|
||||
return c / 12.0;
|
||||
}
|
||||
@fragment fn fs_up(in: Out) -> @location(0) vec4<f32> {
|
||||
return vec4(up(in.uv), 1.0);
|
||||
}
|
||||
@fragment fn fs_final(in: Out) -> @location(0) vec4<f32> {
|
||||
var c = up(in.uv);
|
||||
let l = dot(c, vec3(0.2126, 0.7152, 0.0722));
|
||||
c = mix(c, vec3(l), post.params.x);
|
||||
c = c * post.tint.rgb + post.lift.rgb;
|
||||
let d = length((in.uv - 0.5) * vec2(1.25, 1.0));
|
||||
c *= 1.0 - post.params.y * smoothstep(0.35, 0.95, d);
|
||||
return vec4(clamp(c, vec3(0.0), vec3(1.0)), 1.0);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use horizon_telemetry::payload::{Crash, Perf, Settings, System, Timings};
|
||||
use horizon_telemetry::payload::{Crash, Display, Perf, Settings, System, Timings};
|
||||
use horizon_telemetry::scrub::Scrubber;
|
||||
use horizon_telemetry::{Item, Payload, Source, outbox};
|
||||
|
||||
@@ -25,15 +25,28 @@ static STARTED: OnceLock<Instant> = OnceLock::new();
|
||||
static UI_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX);
|
||||
static CORE_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX);
|
||||
static REST_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX);
|
||||
/// The GPU's name, driver and backend, once the renderer has its adapter.
|
||||
static GPU: Mutex<Option<(String, String, String)>> = Mutex::new(None);
|
||||
/// The GPU, once the renderer has its adapter: name, maker, kind, driver, backend, its own memory.
|
||||
static GPU: Mutex<Option<Gpu>> = Mutex::new(None);
|
||||
/// The screen the window opened on.
|
||||
static DISPLAY: Mutex<Option<Display>> = Mutex::new(None);
|
||||
|
||||
/// The adapter as the renderer found it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Gpu {
|
||||
pub name: String,
|
||||
pub vendor: String,
|
||||
/// `integrated`, `discrete`, `virtual`, `cpu` or `other`.
|
||||
pub kind: String,
|
||||
pub driver: String,
|
||||
pub backend: String,
|
||||
}
|
||||
|
||||
/// When the game started, for the time to the title screen. Call first thing in `main`.
|
||||
pub fn mark_start() {
|
||||
STARTED.get_or_init(Instant::now);
|
||||
}
|
||||
|
||||
/// The menu bundle is ready: the title backdrop can draw. The first writer wins.
|
||||
/// The menu bundle is ready: the title screen can draw. The first writer wins.
|
||||
pub fn mark_ui_ready() {
|
||||
if let Some(started) = STARTED.get() {
|
||||
let ms = started.elapsed().as_millis() as u32;
|
||||
@@ -61,18 +74,73 @@ fn readiness_ms(mark: &AtomicU32) -> Option<u32> {
|
||||
(ms != u32::MAX).then_some(ms)
|
||||
}
|
||||
|
||||
pub fn set_gpu(name: &str, driver: String, backend: String) {
|
||||
*GPU.lock().unwrap_or_else(|e| e.into_inner()) = Some((name.to_owned(), driver, backend));
|
||||
pub fn set_gpu(gpu: Gpu) {
|
||||
*GPU.lock().unwrap_or_else(|e| e.into_inner()) = Some(gpu);
|
||||
}
|
||||
|
||||
/// This machine, with the GPU once the renderer knows it.
|
||||
pub fn system() -> System {
|
||||
let mut system = System::detect();
|
||||
if let Some((gpu, driver, backend)) = GPU.lock().unwrap_or_else(|e| e.into_inner()).clone() {
|
||||
system.gpu = gpu;
|
||||
system.driver = driver;
|
||||
system.backend = backend;
|
||||
/// The screen the window is on: size in physical pixels, refresh rate, scale.
|
||||
pub fn set_display(width: u32, height: u32, refresh_hz: u32, scale: f64) {
|
||||
*DISPLAY.lock().unwrap_or_else(|e| e.into_inner()) = Some(Display {
|
||||
width,
|
||||
height,
|
||||
refresh_hz,
|
||||
scale: scale as f32,
|
||||
});
|
||||
}
|
||||
|
||||
/// The screen `window` is on, else the primary one, else the only one: right after the window
|
||||
/// is made, Wayland doesn't say yet which screen it is on.
|
||||
pub fn monitor(window: &winit::window::Window) -> Option<winit::monitor::MonitorHandle> {
|
||||
let only = || {
|
||||
let mut all = window.available_monitors();
|
||||
all.next().filter(|_| all.next().is_none())
|
||||
};
|
||||
window
|
||||
.current_monitor()
|
||||
.or_else(|| window.primary_monitor())
|
||||
.or_else(only)
|
||||
}
|
||||
|
||||
/// Keeps [`monitor`]'s size, refresh rate and scale for the items' `system.display`.
|
||||
pub fn note_display(window: &winit::window::Window) {
|
||||
if let Some(m) = monitor(window) {
|
||||
set_display(
|
||||
m.size().width,
|
||||
m.size().height,
|
||||
m.refresh_rate_millihertz().map_or(0, |r| r.div_ceil(1000)),
|
||||
m.scale_factor(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// wgpu's device type in the words items use.
|
||||
pub fn gpu_kind(device_type: &str) -> &'static str {
|
||||
match device_type {
|
||||
"IntegratedGpu" => "integrated",
|
||||
"DiscreteGpu" => "discrete",
|
||||
"VirtualGpu" => "virtual",
|
||||
"Cpu" => "cpu",
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
|
||||
/// This machine, with the GPU and the screen once the renderer knows them. The drive is the one
|
||||
/// under the game folder (the current folder).
|
||||
pub fn system() -> System {
|
||||
let home = std::env::current_dir().ok();
|
||||
let mut system = System::detect_in(home.as_deref());
|
||||
if let Some(gpu) = GPU.lock().unwrap_or_else(|e| e.into_inner()).clone() {
|
||||
system.vram_mb = match gpu.kind.as_str() {
|
||||
"discrete" => horizon_telemetry::system::vram_mb(&gpu.vendor).unwrap_or(0),
|
||||
_ => 0,
|
||||
};
|
||||
system.gpu = gpu.name;
|
||||
system.gpu_vendor = gpu.vendor;
|
||||
system.gpu_kind = gpu.kind;
|
||||
system.driver = gpu.driver;
|
||||
system.backend = gpu.backend;
|
||||
}
|
||||
system.display = DISPLAY.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
system
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ use std::{
|
||||
mod create_world;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod world_management;
|
||||
pub mod world_management;
|
||||
pub use create_world::{DIFFICULTIES, WorldOptions};
|
||||
|
||||
/// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`.
|
||||
@@ -142,10 +142,6 @@ pub struct Title {
|
||||
toast: Option<(crate::toasts::Slide, BackupToast)>,
|
||||
icons: RefCell<std::collections::HashMap<PathBuf, (std::time::SystemTime, Option<Vec<u8>>)>>,
|
||||
splash: Option<String>,
|
||||
/// The mode last drawn and when it appeared (Horizon's screen fades).
|
||||
shown: std::cell::Cell<(std::mem::Discriminant<Mode>, std::time::Instant)>,
|
||||
/// The launcher-style opening (Horizon style, first title of the session).
|
||||
pub opening: std::cell::Cell<Option<crate::front::Opening>>,
|
||||
/// The saves listed for Home, re-read every couple of seconds.
|
||||
recent: std::cell::RefCell<Option<(std::time::Instant, Vec<WorldEntry>)>>,
|
||||
}
|
||||
@@ -232,7 +228,6 @@ impl Title {
|
||||
let mode = Mode::Main;
|
||||
let now = std::time::Instant::now();
|
||||
Self {
|
||||
shown: std::cell::Cell::new((std::mem::discriminant(&mode), now)),
|
||||
mode,
|
||||
last_server: String::new(),
|
||||
saves,
|
||||
@@ -256,7 +251,6 @@ impl Title {
|
||||
.subsec_nanos() as usize,
|
||||
(today.month(), today.day()),
|
||||
),
|
||||
opening: std::cell::Cell::new(None),
|
||||
recent: std::cell::RefCell::new(None),
|
||||
}
|
||||
}
|
||||
@@ -506,6 +500,14 @@ impl Title {
|
||||
}
|
||||
}
|
||||
/// The worlds, newest first, cached for two seconds (drawn every frame).
|
||||
/// Saves changed behind the screens' back (agent control renamed or deleted a world): the
|
||||
/// list shows them again.
|
||||
pub fn worlds_changed(&mut self) {
|
||||
if matches!(self.mode, Mode::Select { .. }) {
|
||||
self.return_to_list(None);
|
||||
}
|
||||
*self.recent.borrow_mut() = None;
|
||||
}
|
||||
pub fn recent_worlds(&self) -> Vec<WorldEntry> {
|
||||
let mut recent = self.recent.borrow_mut();
|
||||
match &*recent {
|
||||
@@ -517,17 +519,6 @@ impl Title {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// When the current mode first appeared.
|
||||
pub fn entered(&self) -> std::time::Instant {
|
||||
let now = std::mem::discriminant(&self.mode);
|
||||
let (mode, at) = self.shown.get();
|
||||
if mode == now {
|
||||
return at;
|
||||
}
|
||||
let at = std::time::Instant::now();
|
||||
self.shown.set((now, at));
|
||||
at
|
||||
}
|
||||
/// Create New World: the folder name and options (FileUtil.findAvailableName).
|
||||
pub fn create_action(&self) -> Action {
|
||||
let Mode::Create {
|
||||
@@ -597,7 +588,9 @@ impl Title {
|
||||
b(cx + 2.0, y + 96.0, 98.0, "Quit Game", true, 2),
|
||||
];
|
||||
for (i, (label, enabled, id, icon, size)) in [
|
||||
("Friends", false, 5, "friends/friends", 15.0),
|
||||
// Horizon's Join a Friend (an invite code) behind
|
||||
// vanilla's Friends button.
|
||||
("Friends", true, 5, "friends/friends", 15.0),
|
||||
("Language", true, 6, "icon/language", 15.0),
|
||||
(
|
||||
"Accessibility Settings",
|
||||
@@ -1207,6 +1200,10 @@ impl Title {
|
||||
crate::multiplayer::Outcome::Connect(address) => Action::Connect { address },
|
||||
crate::multiplayer::Outcome::None => Action::None,
|
||||
},
|
||||
(Mode::Main, Some(5)) => {
|
||||
self.mode = Mode::Multiplayer(crate::multiplayer::Screen::friend());
|
||||
Action::None
|
||||
}
|
||||
(Mode::Main, Some(3)) => Action::Options,
|
||||
(Mode::Main, Some(7)) => Action::Accessibility,
|
||||
(Mode::Main, Some(6)) => Action::Language,
|
||||
@@ -1669,7 +1666,7 @@ mod classic_tests {
|
||||
let cx = (w / 2.0).floor();
|
||||
let y = (h / 4.0).floor() + 48.0;
|
||||
for (id, x, enabled, icon) in [
|
||||
(5, cx - 34.0, false, "friends/friends"),
|
||||
(5, cx - 34.0, true, "friends/friends"),
|
||||
(6, cx - 10.0, true, "icon/language"),
|
||||
(7, cx + 14.0, true, "icon/accessibility"),
|
||||
] {
|
||||
@@ -1683,9 +1680,16 @@ mod classic_tests {
|
||||
match id {
|
||||
6 => (Action::Language, true),
|
||||
7 => (Action::Accessibility, true),
|
||||
_ => (Action::None, false),
|
||||
_ => (Action::None, true),
|
||||
}
|
||||
);
|
||||
if id == 5 {
|
||||
assert!(matches!(
|
||||
title.mode,
|
||||
Mode::Multiplayer(crate::multiplayer::Screen::Friend { .. })
|
||||
));
|
||||
title.mode = Mode::Main;
|
||||
}
|
||||
}
|
||||
for id in [2, 3] {
|
||||
assert_eq!(buttons.iter().find(|b| b.id == id).unwrap().y, y + 96.0);
|
||||
|
||||
@@ -23,7 +23,7 @@ fn world_path(saves: &Path, folder: &str) -> crate::Result<PathBuf> {
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub(super) fn rename(saves: &Path, folder: &str, name: &str) -> crate::Result<()> {
|
||||
pub fn rename(saves: &Path, folder: &str, name: &str) -> crate::Result<()> {
|
||||
let path = world_path(saves, folder)?.join("level.dat");
|
||||
let mut root = read_dat(&path).ok_or("Could not read level.dat")?;
|
||||
let Some(Tag::Compound(data)) = root.get_mut("Data") else {
|
||||
@@ -38,14 +38,14 @@ pub(super) fn reset_icon(saves: &Path, folder: &str) -> crate::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `LevelStorageAccess.deleteLevel`, shared by both menu styles. The world's
|
||||
/// `LevelStorageAccess.deleteLevel`. The world's
|
||||
/// session lock is taken first, so a world open in this or another instance is
|
||||
/// refused rather than pulled from under it; everything but the lock goes,
|
||||
/// then the lock is released and removed with the folder. A failed pass (a
|
||||
/// file briefly held by a virus scanner, say) is retried up to five times,
|
||||
/// half a second apart, as vanilla does. Only the named folder directly in
|
||||
/// `saves` is touched: symbolic links inside it are removed, never followed.
|
||||
pub(super) fn delete(saves: &Path, folder: &str) -> crate::Result<()> {
|
||||
pub fn delete(saves: &Path, folder: &str) -> crate::Result<()> {
|
||||
let world = world_path(saves, folder)?;
|
||||
let lock = crate::save::SessionLock::acquire(&world)?;
|
||||
let lock_path = world.join("session.lock");
|
||||
@@ -86,7 +86,7 @@ fn remove_contents(world: &Path, lock: &Path) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn backups_path(saves: &Path) -> PathBuf {
|
||||
pub fn backups_path(saves: &Path) -> PathBuf {
|
||||
saves.parent().unwrap_or(saves).join("backups")
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ pub(super) fn open_folder(path: &Path) -> crate::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn backup(saves: &Path, folder: &str) -> crate::Result<u64> {
|
||||
pub fn backup(saves: &Path, folder: &str) -> crate::Result<u64> {
|
||||
let world = world_path(saves, folder)?;
|
||||
let backups = backups_path(saves);
|
||||
fs::create_dir_all(&backups)?;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The labelled widgets and focus targets drawn in the last frame, for the
|
||||
//! control socket: a script clicks a button by its label (`horizon-ctl
|
||||
//! click-button Respawn`) or any widget by its id in [`tree`] (`horizon-ctl
|
||||
//! click done`), whatever screen or menu style drew it.
|
||||
//! click done`), whatever screen drew it.
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// A labelled widget in GUI pixels (the coordinates screens take input in).
|
||||
@@ -21,7 +21,7 @@ pub struct Widget {
|
||||
/// navigation").
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Kind {
|
||||
/// Clicked with A (buttons, switches, segments, sidebar items).
|
||||
/// Clicked with A (buttons, icon buttons, keys).
|
||||
Button,
|
||||
/// Left and right move the value instead of focus; A does nothing (a
|
||||
/// click would jump the handle to the middle). `value` is 0..1 as drawn;
|
||||
@@ -53,9 +53,8 @@ impl Target {
|
||||
thread_local! {
|
||||
/// Buttons drawn since the last `end_frame`, and the last frame's.
|
||||
static WIDGETS: RefCell<(Vec<Widget>, Vec<Widget>, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) };
|
||||
/// Every interactive rectangle (Horizon-style menus' sidebar items,
|
||||
/// switches, sliders, segments; classic sliders, fields and list rows),
|
||||
/// labelled or not: where a controller can move focus. Drawn since
|
||||
/// Every interactive rectangle (sliders, fields, list rows, the
|
||||
/// on-screen keyboard's keys), labelled or not: where a controller can move focus. Drawn since
|
||||
/// `end_frame`, the last frame's, and how many frames rotated.
|
||||
static TARGETS: RefCell<(Vec<Target>, Vec<Target>, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) };
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod carving;
|
||||
pub mod density;
|
||||
pub mod geometry;
|
||||
pub mod jmath;
|
||||
pub mod no_ai;
|
||||
pub mod noise;
|
||||
pub mod paletted;
|
||||
pub mod position;
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! The "No AI" switch: one setting that hides and turns off every AI feature of Horizon (the
|
||||
//! companion, agent control through the control socket, `horizon-ctl`, its MCP server and the
|
||||
//! launcher's). The launcher and the game both read and write it here, so they always agree.
|
||||
//!
|
||||
//! It is the `noAi` line of the game's `horizon-extras.txt`, in the game's home (the folder
|
||||
//! with `options.txt`). Missing means off: AI features are available. See docs/agent-control.md.
|
||||
use std::{fs, io, path::Path};
|
||||
|
||||
/// The game's extras file, beside `options.txt`.
|
||||
pub const FILE: &str = "horizon-extras.txt";
|
||||
/// The key No AI is kept under there.
|
||||
pub const KEY: &str = "noAi";
|
||||
/// The one line every AI surface answers with while No AI is on.
|
||||
pub const REFUSAL: &str = "AI features are off: turn off No AI in the launcher's settings";
|
||||
|
||||
/// Whether `text` (an extras file) says No AI.
|
||||
pub fn parse(text: &str) -> bool {
|
||||
text.lines().any(|line| {
|
||||
line.split_once(':')
|
||||
.is_some_and(|(k, v)| k.trim() == KEY && v.trim() == "true")
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether No AI is on for the game whose home is `home`.
|
||||
pub fn is_on(home: &Path) -> bool {
|
||||
fs::read_to_string(home.join(FILE)).is_ok_and(|text| parse(&text))
|
||||
}
|
||||
|
||||
/// `text` with its `noAi` line set to `on`, every other line kept as it was.
|
||||
pub fn with(text: &str, on: bool) -> String {
|
||||
let mut out: String = text
|
||||
.lines()
|
||||
.filter(|line| line.split_once(':').is_none_or(|(k, _)| k.trim() != KEY))
|
||||
.flat_map(|line| [line, "\n"])
|
||||
.collect();
|
||||
out.push_str(&format!("{KEY}:{on}\n"));
|
||||
out
|
||||
}
|
||||
|
||||
/// Turns No AI on or off for the game in `home`, keeping the file's other settings. Turning it
|
||||
/// off where there is no file writes nothing (off is the default).
|
||||
pub fn set(home: &Path, on: bool) -> io::Result<()> {
|
||||
let path = home.join(FILE);
|
||||
let text = match fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
if !on {
|
||||
return Ok(());
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
fs::create_dir_all(home)?;
|
||||
fs::write(path, with(&text, on))
|
||||
}
|
||||
|
||||
/// `Err(REFUSAL)` while No AI is on in `home`.
|
||||
pub fn check(home: &Path) -> Result<(), &'static str> {
|
||||
if is_on(home) { Err(REFUSAL) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_and_writes_the_extras_line_keeping_the_others() {
|
||||
assert!(!parse(""));
|
||||
assert!(!parse("noAi:false\nzoom:true\n"));
|
||||
assert!(parse("zoom:true\nnoAi: true\n"));
|
||||
assert_eq!(
|
||||
with("zoom:true\nnoAi:false\nfps:true", true),
|
||||
"zoom:true\nfps:true\nnoAi:true\n"
|
||||
);
|
||||
assert_eq!(with("", false), "noAi:false\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_writes_only_when_needed() {
|
||||
let home = std::env::temp_dir().join(format!("horizon-no-ai-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&home);
|
||||
set(&home, false).unwrap();
|
||||
assert!(!home.join(FILE).exists(), "off needs no file");
|
||||
assert!(check(&home).is_ok());
|
||||
set(&home, true).unwrap();
|
||||
assert!(is_on(&home));
|
||||
assert_eq!(check(&home), Err(REFUSAL));
|
||||
fs::write(home.join(FILE), "fps:true\nnoAi:true\n").unwrap();
|
||||
set(&home, false).unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(home.join(FILE)).unwrap(),
|
||||
"fps:true\nnoAi:false\n"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&home);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,10 @@ pub struct Report {
|
||||
pub worldgen: usize,
|
||||
/// Recipes left as they were: custom types, NeoForge conditions.
|
||||
pub recipes_kept: Vec<String>,
|
||||
/// Recipes whose result is one of the mod's own items that isn't declared (its block was
|
||||
/// left out), moved to `outside/`: vanilla refuses a recipe for an unknown item, and the
|
||||
/// game would craft air.
|
||||
pub recipes_unregistered: Vec<String>,
|
||||
pub item_definitions_added: usize,
|
||||
/// Templates and properties came from the NeoForge oracle's facts, not
|
||||
/// from guesses.
|
||||
@@ -578,6 +582,18 @@ fn extra_namespaces(
|
||||
claimed
|
||||
}
|
||||
|
||||
/// The namespaces besides `id` the mod in `jar` would own ([`extra_namespaces`]), for the
|
||||
/// pack to find the ones several mods claim.
|
||||
pub fn namespaces_claimed(
|
||||
jar: &Path,
|
||||
id: &str,
|
||||
pack_mod: &dyn Fn(&str) -> bool,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let file = fs::File::open(jar).map_err(|e| format!("{}: {e}", jar.display()))?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", jar.display()))?;
|
||||
Ok(extra_namespaces(&mut zip, id, pack_mod))
|
||||
}
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
@@ -1083,6 +1099,9 @@ pub fn carry(
|
||||
report.items += 1;
|
||||
}
|
||||
}
|
||||
let owned: Vec<String> = owned.iter().map(|n| n.to_string()).collect();
|
||||
let owned: Vec<&str> = owned.iter().map(String::as_str).collect();
|
||||
unregistered_recipes(&inside, &outside, id, &owned, &mut report)?;
|
||||
let q = |s: &str| toml::Value::String(s.to_owned()).to_string();
|
||||
let name = if info.name.is_empty() { id } else { &info.name };
|
||||
let mut manifest = format!(
|
||||
@@ -1109,6 +1128,88 @@ pub fn carry(
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// The item a recipe makes: `result.id` (1.21 and later), `result.item` or a bare id.
|
||||
fn recipe_result(recipe: &Value) -> Option<&str> {
|
||||
let r = &recipe["result"];
|
||||
r.as_str()
|
||||
.or_else(|| r["id"].as_str())
|
||||
.or_else(|| r["item"].as_str())
|
||||
}
|
||||
|
||||
/// Moves the recipes whose result is an undeclared item of the mod's own namespaces from
|
||||
/// `inside` to `outside` ([`Report::recipes_unregistered`]). The declared items are the blocks
|
||||
/// with their item and the items under `data/<id>/horizon/`.
|
||||
fn unregistered_recipes(
|
||||
inside: &Path,
|
||||
outside: &Path,
|
||||
id: &str,
|
||||
owned: &[&str],
|
||||
report: &mut Report,
|
||||
) -> Result<(), String> {
|
||||
let decl = inside.join(format!("data/{id}/horizon"));
|
||||
let mut declared = BTreeSet::new();
|
||||
for kind in ["block", "item"] {
|
||||
for f in fs::read_dir(decl.join(kind))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
{
|
||||
let path = f.path();
|
||||
let Some(name) = path.file_stem().and_then(|n| n.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
let has_item = kind == "item"
|
||||
|| fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
|
||||
.is_none_or(|v| v["item"] != json!(false));
|
||||
if has_item {
|
||||
declared.insert(format!("{id}:{name}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for ns in owned {
|
||||
let dir = inside.join(format!("data/{ns}/recipe"));
|
||||
let mut stack = vec![dir.clone()];
|
||||
while let Some(d) = stack.pop() {
|
||||
for f in fs::read_dir(&d).into_iter().flatten().flatten() {
|
||||
let path = f.path();
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
continue;
|
||||
}
|
||||
let Some(recipe) = fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(result) = recipe_result(&recipe) else {
|
||||
continue;
|
||||
};
|
||||
let unknown = result
|
||||
.split_once(':')
|
||||
.is_some_and(|(n, _)| owned.contains(&n) && !declared.contains(result));
|
||||
if !unknown {
|
||||
continue;
|
||||
}
|
||||
let rel = path.strip_prefix(inside).map_err(|e| e.to_string())?;
|
||||
let to = outside.join(rel);
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
||||
}
|
||||
fs::rename(&path, &to).map_err(|e| format!("{}: {e}", to.display()))?;
|
||||
report.copied = report.copied.saturating_sub(1);
|
||||
report
|
||||
.recipes_unregistered
|
||||
.push(rel.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
report.recipes_unregistered.sort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The tags a recipe's ingredients name (`#ns:path` or `{"tag": ...}`).
|
||||
fn tags_used(v: &Value, out: &mut BTreeSet<String>) {
|
||||
match v {
|
||||
|
||||
@@ -0,0 +1,411 @@
|
||||
//! One mod jar on its own, as the launcher's mod browser installs it: what
|
||||
//! of it Horizon runs, said before install (Works, Partly, Doesn't run),
|
||||
//! from the jar itself. The jar is carried over ([`crate::carry`]) into a
|
||||
//! folder content mod, and its classes are read ([`crate::classes`]) for
|
||||
//! what the carry can't take: block entities, entities, Mixins, behaviour.
|
||||
//!
|
||||
//! - **Works**: content only. Its blocks, items, recipes, loot, tags and
|
||||
//! worldgen port, and its code only registers them.
|
||||
//! - **Partly**: the content ports; the code features listed don't.
|
||||
//! - **Doesn't run**: nothing to port (everything it does is Java code), or
|
||||
//! the jar can't be carried at all.
|
||||
use crate::{carry, classes, jar};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, fs, io::Read, path::Path};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Verdict {
|
||||
Works,
|
||||
Partly,
|
||||
No,
|
||||
}
|
||||
|
||||
impl Verdict {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Verdict::Works => "Works",
|
||||
Verdict::Partly => "Partly",
|
||||
Verdict::No => "Doesn't run",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What checking a jar found. Written as `check.json` beside the carry.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Check {
|
||||
pub mod_id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
/// `neoforge`, `forge`, `fabric`, `quilt`, or `` for a plain zip.
|
||||
pub loader: String,
|
||||
pub license: String,
|
||||
pub verdict: Verdict,
|
||||
/// One line: why this verdict.
|
||||
pub summary: String,
|
||||
/// What ports: "12 blocks", "40 recipes"...
|
||||
pub ports: Vec<String>,
|
||||
/// What doesn't, with why.
|
||||
pub skipped: Vec<String>,
|
||||
/// Required mods, by id.
|
||||
pub depends: Vec<String>,
|
||||
/// The folder mod's namespaces (its id first): two mods on at once may
|
||||
/// not share one.
|
||||
pub namespaces: Vec<String>,
|
||||
pub code: classes::Code,
|
||||
}
|
||||
|
||||
/// The loader a jar is made for, from its metadata file.
|
||||
fn loader(names: &[String]) -> &'static str {
|
||||
let has = |n: &str| names.iter().any(|x| x == n);
|
||||
if has("META-INF/neoforge.mods.toml") {
|
||||
"neoforge"
|
||||
} else if has("META-INF/mods.toml") {
|
||||
"forge"
|
||||
} else if has("fabric.mod.json") {
|
||||
"fabric"
|
||||
} else if has("quilt.mod.json") {
|
||||
"quilt"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// Data folders named as before 1.21 (`recipes/`, `loot_tables/`) and none
|
||||
/// as 1.21 names them: the game doesn't read them, and the carry upgrades
|
||||
/// from 1.21.1 on. (Some jars keep a stale plural folder beside the new one.)
|
||||
fn old_layout(names: &[String]) -> bool {
|
||||
let has = |kinds: [&str; 2]| {
|
||||
names.iter().any(|n| {
|
||||
let p: Vec<&str> = n.split('/').collect();
|
||||
p.len() > 3 && p[0] == "data" && kinds.contains(&p[2]) && n.ends_with(".json")
|
||||
})
|
||||
};
|
||||
has(["recipes", "loot_tables"]) && !has(["recipe", "loot_table"])
|
||||
}
|
||||
|
||||
fn plural(n: usize, one: &str, many: &str) -> String {
|
||||
format!("{n} {}", if n == 1 { one } else { many })
|
||||
}
|
||||
|
||||
/// Checks `jar` and carries it over into `out/carry/` (`out/check.json`,
|
||||
/// `out/carry-report.json` beside it). The carry is the folder mod an
|
||||
/// install copies.
|
||||
pub fn check(jar_path: &Path, out: &Path) -> Result<Check, String> {
|
||||
let info = jar::read(jar_path)?;
|
||||
let file = fs::File::open(jar_path).map_err(|e| format!("{}: {e}", jar_path.display()))?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", jar_path.display()))?;
|
||||
let names: Vec<String> = zip.file_names().map(str::to_owned).collect();
|
||||
let mut bytes = Vec::new();
|
||||
for n in names.iter().filter(|n| n.ends_with(".class")) {
|
||||
let mut b = Vec::new();
|
||||
if let Ok(mut e) = zip.by_name(n)
|
||||
&& e.size() < 1 << 24
|
||||
&& e.read_to_end(&mut b).is_ok()
|
||||
{
|
||||
bytes.push(b);
|
||||
}
|
||||
}
|
||||
let code = classes::census(bytes.iter().map(Vec::as_slice));
|
||||
let mut check = Check {
|
||||
mod_id: info.mod_id.clone(),
|
||||
name: info.name.clone(),
|
||||
version: info.version.clone(),
|
||||
loader: loader(&names).to_owned(),
|
||||
license: info.license.clone(),
|
||||
verdict: Verdict::No,
|
||||
summary: String::new(),
|
||||
ports: Vec::new(),
|
||||
skipped: Vec::new(),
|
||||
depends: info.depends.clone(),
|
||||
namespaces: Vec::new(),
|
||||
code,
|
||||
};
|
||||
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let done = |check: Check| -> Result<Check, String> {
|
||||
crate::pipeline::write_json(&out.join("check.json"), &check)?;
|
||||
Ok(check)
|
||||
};
|
||||
if old_layout(&names) {
|
||||
check.summary = "Made for Minecraft 1.20 or older: Horizon ports mods made for 1.21 \
|
||||
and later."
|
||||
.into();
|
||||
return done(check);
|
||||
}
|
||||
let alone = |m: &str| m == info.mod_id || m == "minecraft";
|
||||
let pack = carry::Pack {
|
||||
loaded: &alone,
|
||||
mods: &alone,
|
||||
};
|
||||
let report = match carry::carry(
|
||||
jar_path,
|
||||
&info,
|
||||
out,
|
||||
None,
|
||||
&|_| true,
|
||||
&pack,
|
||||
&BTreeMap::new(),
|
||||
) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
check.summary = format!("Can't be carried over: {e}");
|
||||
return done(check);
|
||||
}
|
||||
};
|
||||
check.namespaces = std::iter::once(info.mod_id.clone())
|
||||
.chain(report.namespaces.iter().cloned())
|
||||
.collect();
|
||||
let c = &info.census;
|
||||
let recipes = report
|
||||
.recipes_upgraded
|
||||
.saturating_sub(report.recipes_unregistered.len());
|
||||
let loot = c.loot_tables + report.loot_tables_added;
|
||||
let content =
|
||||
report.blocks.len() + report.items + recipes + loot + report.worldgen + c.structures;
|
||||
for (n, one, many) in [
|
||||
(report.blocks.len(), "block", "blocks"),
|
||||
(report.items, "item", "items"),
|
||||
(recipes, "recipe", "recipes"),
|
||||
(loot, "loot table", "loot tables"),
|
||||
(report.worldgen, "worldgen file", "worldgen files"),
|
||||
(c.textures, "texture", "textures"),
|
||||
] {
|
||||
if n > 0 {
|
||||
check.ports.push(plural(n, one, many));
|
||||
}
|
||||
}
|
||||
if !report.blocks.is_empty() {
|
||||
check
|
||||
.ports
|
||||
.push("blocks take the closest vanilla block's shape, hardness and sounds".into());
|
||||
}
|
||||
let mut skipped = Vec::new();
|
||||
if !report.blocks_unknown.is_empty() {
|
||||
skipped.push(plural(
|
||||
report.blocks_unknown.len(),
|
||||
"block with no vanilla block to copy (left out)",
|
||||
"blocks with no vanilla block to copy (left out)",
|
||||
));
|
||||
}
|
||||
if !report.recipes_unregistered.is_empty() {
|
||||
skipped.push(plural(
|
||||
report.recipes_unregistered.len(),
|
||||
"recipe for a left-out block",
|
||||
"recipes for left-out blocks",
|
||||
));
|
||||
}
|
||||
if !report.recipes_kept.is_empty() {
|
||||
skipped.push(plural(
|
||||
report.recipes_kept.len(),
|
||||
"recipe of a type Horizon doesn't have",
|
||||
"recipes of types Horizon doesn't have",
|
||||
));
|
||||
}
|
||||
if !report.unreadable.is_empty() {
|
||||
skipped.push(plural(
|
||||
report.unreadable.len(),
|
||||
"file the game can't read",
|
||||
"files the game can't read",
|
||||
));
|
||||
}
|
||||
let wg = &report.worldgen_types;
|
||||
let dropped = wg.processors_dropped.values().sum::<usize>();
|
||||
if dropped > 0 {
|
||||
skipped.push(plural(
|
||||
dropped,
|
||||
"structure processor written in Java",
|
||||
"structure processors written in Java",
|
||||
));
|
||||
}
|
||||
let unsupported = wg.unsupported.values().sum::<usize>();
|
||||
if unsupported > 0 {
|
||||
skipped.push(plural(
|
||||
unsupported,
|
||||
"worldgen file of a type written in Java",
|
||||
"worldgen files of types written in Java",
|
||||
));
|
||||
}
|
||||
for (f, n) in &check.code.features {
|
||||
let mut line = f.describe(*n);
|
||||
if *f == classes::Feature::Events {
|
||||
let names: Vec<&str> = check
|
||||
.code
|
||||
.events
|
||||
.iter()
|
||||
.take(3)
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
line.push_str(&format!(" ({}", names.join(", ")));
|
||||
if check.code.events.len() > 3 {
|
||||
line.push_str(", ...");
|
||||
}
|
||||
line.push(')');
|
||||
}
|
||||
skipped.push(line);
|
||||
}
|
||||
check.skipped = skipped;
|
||||
let behaviour = check.code.behaviour();
|
||||
(check.verdict, check.summary) = if content == 0 {
|
||||
let what = if behaviour || check.code.classes > 0 {
|
||||
"everything it does is Java code, which Horizon doesn't run"
|
||||
} else {
|
||||
"it has no blocks, items, recipes or worldgen"
|
||||
};
|
||||
(Verdict::No, format!("Nothing to port: {what}."))
|
||||
} else if check.skipped.is_empty() {
|
||||
(
|
||||
Verdict::Works,
|
||||
format!(
|
||||
"Content only: {} port.",
|
||||
check.ports[..check.ports.len().min(3)].join(", ")
|
||||
),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
Verdict::Partly,
|
||||
format!(
|
||||
"{} port; not {}.",
|
||||
check.ports[..check.ports.len().min(2)].join(", "),
|
||||
check.skipped[..check.skipped.len().min(2)].join(", ")
|
||||
),
|
||||
)
|
||||
};
|
||||
done(check)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn jar(dir: &Path, files: &[(&str, &[u8])]) -> std::path::PathBuf {
|
||||
let path = dir.join("m.jar");
|
||||
let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap());
|
||||
for (name, bytes) in files {
|
||||
zip.start_file(*name, zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
const TOML: &[u8] = br#"modLoader = "javafml"
|
||||
license = "MIT"
|
||||
[[mods]]
|
||||
modId = "ruby"
|
||||
version = "1.0"
|
||||
displayName = "Ruby"
|
||||
"#;
|
||||
|
||||
fn temp(name: &str) -> std::path::PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("port-pack-check-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_only_works_and_code_makes_it_partly() {
|
||||
let dir = temp("content");
|
||||
let blockstate = br#"{"variants": {"": {"model": "ruby:block/ruby_block"}}}"#;
|
||||
let recipe = br#"{"type": "minecraft:crafting_shapeless", "ingredients": ["minecraft:red_dye"], "result": {"id": "ruby:ruby"}}"#;
|
||||
let plain = [
|
||||
("META-INF/neoforge.mods.toml", TOML),
|
||||
("assets/ruby/blockstates/ruby_block.json", blockstate),
|
||||
("assets/ruby/models/item/ruby.json", b"{}"),
|
||||
("data/ruby/recipe/ruby.json", recipe),
|
||||
];
|
||||
let c = check(&jar(&dir, &plain), &dir.join("out")).unwrap();
|
||||
assert_eq!(c.verdict, Verdict::Works, "{c:?}");
|
||||
assert_eq!(c.loader, "neoforge");
|
||||
assert_eq!(&c.ports[..3], ["1 block", "1 item", "1 recipe"]);
|
||||
assert!(dir.join("out/carry/horizon-mod.toml").is_file());
|
||||
assert!(dir.join("out/check.json").is_file());
|
||||
|
||||
let tile = crate::classes::tests_support::class_file(
|
||||
"ruby/Tile",
|
||||
"net/minecraft/world/level/block/entity/BlockEntity",
|
||||
);
|
||||
let mut coded = plain.to_vec();
|
||||
coded.push(("ruby/Tile.class", &tile));
|
||||
let c = check(&jar(&dir, &coded), &dir.join("out")).unwrap();
|
||||
assert_eq!(c.verdict, Verdict::Partly);
|
||||
assert!(
|
||||
c.skipped[0].starts_with("1 block entity"),
|
||||
"{:?}",
|
||||
c.skipped
|
||||
);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipes_for_left_out_blocks_are_left_out_too() {
|
||||
let dir = temp("left-out");
|
||||
let odd = br#"{"variants": {"wobble=1": {"model": "ruby:block/odd"}}}"#;
|
||||
let plain = br#"{"variants": {"": {"model": "ruby:block/ruby_block"}}}"#;
|
||||
let recipe = |result: &str| {
|
||||
format!(
|
||||
r#"{{"type": "minecraft:crafting_shapeless", "ingredients": ["minecraft:red_dye"], "result": {{"id": "{result}"}}}}"#
|
||||
)
|
||||
};
|
||||
let (odd_recipe, block_recipe) = (recipe("ruby:odd"), recipe("ruby:ruby_block"));
|
||||
let files = [
|
||||
("META-INF/neoforge.mods.toml", TOML),
|
||||
("assets/ruby/blockstates/odd.json", odd.as_slice()),
|
||||
("assets/ruby/blockstates/ruby_block.json", plain.as_slice()),
|
||||
("data/ruby/recipe/odd.json", odd_recipe.as_bytes()),
|
||||
("data/ruby/recipe/ruby_block.json", block_recipe.as_bytes()),
|
||||
];
|
||||
let c = check(&jar(&dir, &files), &dir.join("out")).unwrap();
|
||||
assert_eq!(c.verdict, Verdict::Partly);
|
||||
assert!(c.ports.contains(&"1 recipe".to_string()), "{:?}", c.ports);
|
||||
assert!(
|
||||
c.skipped
|
||||
.contains(&"1 recipe for a left-out block".to_string()),
|
||||
"{:?}",
|
||||
c.skipped
|
||||
);
|
||||
assert!(!dir.join("out/carry/data/ruby/recipe/odd.json").exists());
|
||||
assert!(dir.join("out/outside/data/ruby/recipe/odd.json").exists());
|
||||
assert!(
|
||||
dir.join("out/carry/data/ruby/recipe/ruby_block.json")
|
||||
.exists()
|
||||
);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_only_and_old_layouts_dont_run() {
|
||||
let dir = temp("code");
|
||||
let tile = crate::classes::tests_support::class_file("ruby/Mixin", "java/lang/Object");
|
||||
let c = check(
|
||||
&jar(
|
||||
&dir,
|
||||
&[
|
||||
("META-INF/neoforge.mods.toml", TOML),
|
||||
("ruby/A.class", &tile),
|
||||
],
|
||||
),
|
||||
&dir.join("out"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(c.verdict, Verdict::No);
|
||||
assert!(c.summary.starts_with("Nothing to port"), "{}", c.summary);
|
||||
let c = check(
|
||||
&jar(
|
||||
&dir,
|
||||
&[
|
||||
("META-INF/mods.toml", TOML),
|
||||
("data/ruby/recipes/ruby.json", b"{}"),
|
||||
],
|
||||
),
|
||||
&dir.join("out"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(c.verdict, Verdict::No);
|
||||
assert!(c.summary.contains("1.20 or older"));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
//! What a mod's Java code does, read from its class files without running
|
||||
//! or decompiling them: each class's superclass, interfaces, declared
|
||||
//! methods and the classes and annotations its constant pool names. The
|
||||
//! mod's own classes are followed up to the first game class they extend,
|
||||
//! and that class says what the code is: a block entity, a menu, an entity,
|
||||
//! a block or item with behaviour of its own, a worldgen feature...
|
||||
//!
|
||||
//! Since 26.1 the game ships unobfuscated, and NeoForge has run on Mojang's
|
||||
//! names since 1.20.5, so game classes and methods are read by name. Fabric
|
||||
//! jars before 26.1 name them in intermediary (`net/minecraft/class_2248`)
|
||||
//! and Forge's methods are SRG (`m_60503_`): a class extending such a game
|
||||
//! class is counted as code of its own, whatever it overrides.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
|
||||
/// One class file, as much as this module reads.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Class {
|
||||
pub name: String,
|
||||
pub superclass: String,
|
||||
pub interfaces: Vec<String>,
|
||||
/// Declared methods, by name (constructors and lambdas left out).
|
||||
pub methods: Vec<String>,
|
||||
/// Every class the constant pool names (`net/minecraft/...`).
|
||||
pub refs: BTreeSet<String>,
|
||||
/// Annotation and descriptor strings (`Lorg/spongepowered/asm/mixin/Mixin;`).
|
||||
pub mixin: bool,
|
||||
}
|
||||
|
||||
/// Reads a class file's header, constant pool and declared methods.
|
||||
pub fn parse(bytes: &[u8]) -> Option<Class> {
|
||||
let mut r = Reader { bytes, at: 0 };
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
r.skip(4)?; // minor, major
|
||||
let count = r.u2()? as usize;
|
||||
let mut utf8: HashMap<usize, String> = HashMap::new();
|
||||
let mut class_of: HashMap<usize, usize> = HashMap::new();
|
||||
let mut i = 1;
|
||||
while i < count {
|
||||
let tag = r.u1()?;
|
||||
match tag {
|
||||
1 => {
|
||||
let len = r.u2()? as usize;
|
||||
let s = r.take(len)?;
|
||||
utf8.insert(i, String::from_utf8_lossy(s).into_owned());
|
||||
}
|
||||
7 => {
|
||||
class_of.insert(i, r.u2()? as usize);
|
||||
}
|
||||
8 | 16 | 19 | 20 => r.skip(2)?,
|
||||
3 | 4 | 9..=12 | 17 | 18 => r.skip(4)?,
|
||||
15 => r.skip(3)?,
|
||||
5 | 6 => {
|
||||
r.skip(8)?;
|
||||
i += 1;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let class_name = |idx: usize| -> String {
|
||||
class_of
|
||||
.get(&idx)
|
||||
.and_then(|u| utf8.get(u))
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
};
|
||||
r.skip(2)?; // access flags
|
||||
let name = class_name(r.u2()? as usize);
|
||||
let superclass = class_name(r.u2()? as usize);
|
||||
let n = r.u2()? as usize;
|
||||
let mut interfaces = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
interfaces.push(class_name(r.u2()? as usize));
|
||||
}
|
||||
// Fields, then methods: flags, name, descriptor, attributes.
|
||||
let mut methods = Vec::new();
|
||||
for member in 0..2 {
|
||||
let n = r.u2()?;
|
||||
for _ in 0..n {
|
||||
r.skip(2)?;
|
||||
let name = r.u2()? as usize;
|
||||
r.skip(2)?;
|
||||
let attributes = r.u2()?;
|
||||
for _ in 0..attributes {
|
||||
r.skip(2)?;
|
||||
let len = r.u4()? as usize;
|
||||
r.skip(len)?;
|
||||
}
|
||||
if member == 1
|
||||
&& let Some(m) = utf8.get(&name)
|
||||
&& !m.starts_with('<')
|
||||
&& !m.starts_with("lambda$")
|
||||
{
|
||||
methods.push(m.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let refs = class_of
|
||||
.values()
|
||||
.filter_map(|u| utf8.get(u))
|
||||
.filter(|s| !s.starts_with('['))
|
||||
.cloned()
|
||||
.collect();
|
||||
let mixin = utf8
|
||||
.values()
|
||||
.any(|s| s == "Lorg/spongepowered/asm/mixin/Mixin;");
|
||||
Some(Class {
|
||||
name,
|
||||
superclass,
|
||||
interfaces,
|
||||
methods,
|
||||
refs,
|
||||
mixin,
|
||||
})
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
bytes: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let s = self.bytes.get(self.at..self.at.checked_add(n)?)?;
|
||||
self.at += n;
|
||||
Some(s)
|
||||
}
|
||||
fn skip(&mut self, n: usize) -> Option<()> {
|
||||
self.take(n).map(drop)
|
||||
}
|
||||
fn u1(&mut self) -> Option<u8> {
|
||||
Some(self.take(1)?[0])
|
||||
}
|
||||
fn u2(&mut self) -> Option<u16> {
|
||||
let b = self.take(2)?;
|
||||
Some(u16::from_be_bytes([b[0], b[1]]))
|
||||
}
|
||||
fn u4(&mut self) -> Option<u32> {
|
||||
let b = self.take(4)?;
|
||||
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a class does, as the port sees it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Feature {
|
||||
/// A block with behaviour of its own (use, ticks, collisions...).
|
||||
BlockBehaviour,
|
||||
/// A block with a shape of its own: it ports with its template's.
|
||||
BlockShape,
|
||||
/// An item with behaviour of its own (use, on hit...).
|
||||
ItemBehaviour,
|
||||
BlockEntity,
|
||||
Menu,
|
||||
Entity,
|
||||
Screen,
|
||||
Renderer,
|
||||
/// A worldgen feature, placement or structure type written in Java.
|
||||
Worldgen,
|
||||
/// A recipe type (its recipes don't craft) or ingredient type.
|
||||
Recipe,
|
||||
Effect,
|
||||
Enchantment,
|
||||
Particle,
|
||||
Command,
|
||||
Network,
|
||||
/// Reacts to game events (NeoForge's bus, Fabric's callbacks).
|
||||
Events,
|
||||
/// A Mixin: a patch to the game's own code.
|
||||
Mixin,
|
||||
/// Extends a game class under obfuscated names (Fabric before 26.1,
|
||||
/// Forge's methods): what it does can't be read.
|
||||
Unread,
|
||||
}
|
||||
|
||||
impl Feature {
|
||||
/// How the coverage line names `n` of them.
|
||||
pub fn describe(self, n: usize) -> String {
|
||||
let (one, many) = match self {
|
||||
Feature::BlockBehaviour => (
|
||||
"block with behaviour of its own (use, ticks, collisions)",
|
||||
"blocks with behaviour of their own (use, ticks, collisions)",
|
||||
),
|
||||
Feature::BlockShape => (
|
||||
"block with a shape of its own: it ports with its template's",
|
||||
"blocks with shapes of their own: they port with their templates'",
|
||||
),
|
||||
Feature::ItemBehaviour => (
|
||||
"item with behaviour of its own (use, on hit)",
|
||||
"items with behaviour of their own (use, on hit)",
|
||||
),
|
||||
Feature::BlockEntity => (
|
||||
"block entity (machine, container or animated block)",
|
||||
"block entities (machines, containers, animated blocks)",
|
||||
),
|
||||
Feature::Menu => ("menu (a container screen)", "menus (container screens)"),
|
||||
Feature::Entity => ("mob or entity", "mobs or entities"),
|
||||
Feature::Screen => ("screen of its own", "screens of its own"),
|
||||
Feature::Renderer => ("renderer or model in code", "renderers or models in code"),
|
||||
Feature::Worldgen => (
|
||||
"worldgen feature or structure type in code",
|
||||
"worldgen features or structure types in code",
|
||||
),
|
||||
Feature::Recipe => (
|
||||
"recipe type of its own (its recipes don't craft)",
|
||||
"recipe types of its own (their recipes don't craft)",
|
||||
),
|
||||
Feature::Effect => ("status effect", "status effects"),
|
||||
Feature::Enchantment => ("enchantment effect in code", "enchantment effects in code"),
|
||||
Feature::Particle => ("particle type", "particle types"),
|
||||
Feature::Command => ("command", "commands"),
|
||||
Feature::Network => ("network message", "network messages"),
|
||||
Feature::Events => ("game event it reacts to", "game events it reacts to"),
|
||||
Feature::Mixin => (
|
||||
"Mixin (a patch to the game's code)",
|
||||
"Mixins (patches to the game's code)",
|
||||
),
|
||||
Feature::Unread => (
|
||||
"class extending the game under obfuscated names",
|
||||
"classes extending the game under obfuscated names",
|
||||
),
|
||||
};
|
||||
format!("{n} {}", if n == 1 { one } else { many })
|
||||
}
|
||||
}
|
||||
|
||||
/// Block methods that only say how it looks or is placed: the template's
|
||||
/// do the same for the states a blockstate file lists.
|
||||
const BLOCK_LOOKS: [&str; 18] = [
|
||||
"codec",
|
||||
"createBlockStateDefinition",
|
||||
"getStateForPlacement",
|
||||
"rotate",
|
||||
"mirror",
|
||||
"getRenderShape",
|
||||
"skipRendering",
|
||||
"getShadeBrightness",
|
||||
"propagatesSkylightDown",
|
||||
"getCloneItemStack",
|
||||
"isPathfindable",
|
||||
"getFluidState",
|
||||
"updateShape",
|
||||
"canBeReplaced",
|
||||
"getLightBlock",
|
||||
"useShapeForLightOcclusion",
|
||||
"getDescriptionId",
|
||||
"animateTick",
|
||||
];
|
||||
/// Block methods that only change its outline or collision.
|
||||
const BLOCK_SHAPES: [&str; 6] = [
|
||||
"getShape",
|
||||
"getCollisionShape",
|
||||
"getVisualShape",
|
||||
"getOcclusionShape",
|
||||
"getInteractionShape",
|
||||
"getBlockSupportShape",
|
||||
];
|
||||
/// Item methods that only say how it looks or is named.
|
||||
const ITEM_LOOKS: [&str; 6] = [
|
||||
"appendHoverText",
|
||||
"getName",
|
||||
"isFoil",
|
||||
"getDescriptionId",
|
||||
"getBarColor",
|
||||
"getBarWidth",
|
||||
];
|
||||
|
||||
/// The game's own, loader and library classes: the first of these a mod's
|
||||
/// class chain reaches is what it extends.
|
||||
fn external(name: &str, own: &BTreeMap<String, Class>) -> bool {
|
||||
!own.contains_key(name)
|
||||
}
|
||||
|
||||
fn obfuscated_method(m: &str) -> bool {
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
m.strip_prefix("method_").is_some_and(digits)
|
||||
|| m.strip_prefix("m_")
|
||||
.and_then(|s| s.strip_suffix('_'))
|
||||
.is_some_and(digits)
|
||||
}
|
||||
|
||||
/// What a game class (Mojang's names) is, by its package and name.
|
||||
fn kind_of_game_class(name: &str) -> Option<Feature> {
|
||||
let rest = name.strip_prefix("net/minecraft/")?;
|
||||
if rest.starts_with("class_") {
|
||||
return Some(Feature::Unread);
|
||||
}
|
||||
let (package, simple) = rest.rsplit_once('/').unwrap_or(("", rest));
|
||||
Some(match package {
|
||||
"world/level/block/entity" => Feature::BlockEntity,
|
||||
p if p.starts_with("world/level/block") => Feature::BlockBehaviour,
|
||||
"world/inventory" if simple.ends_with("Menu") => Feature::Menu,
|
||||
p if p.starts_with("world/entity") => Feature::Entity,
|
||||
p if p.starts_with("world/item/crafting") => Feature::Recipe,
|
||||
p if p.starts_with("world/item/enchantment") => Feature::Enchantment,
|
||||
p if p.starts_with("world/item") => Feature::ItemBehaviour,
|
||||
p if p.starts_with("world/level/levelgen") => Feature::Worldgen,
|
||||
"world/effect" => Feature::Effect,
|
||||
p if p.starts_with("client/gui/screens") || p.starts_with("client/gui/components") => {
|
||||
Feature::Screen
|
||||
}
|
||||
p if p.starts_with("client/renderer") || p.starts_with("client/model") => Feature::Renderer,
|
||||
p if p.starts_with("client/particle") || p.starts_with("core/particles") => {
|
||||
Feature::Particle
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Events a content mod uses to register what it has: not behaviour.
|
||||
fn registration_event(name: &str) -> bool {
|
||||
[
|
||||
"BuildCreativeModeTabContentsEvent",
|
||||
"RegisterEvent",
|
||||
"Register",
|
||||
"Lifecycle",
|
||||
"ModConfigEvent",
|
||||
"AddPackFindersEvent",
|
||||
"ItemGroupEvents",
|
||||
"ClientLifecycleEvents",
|
||||
"ServerLifecycleEvents",
|
||||
]
|
||||
.iter()
|
||||
.any(|k| name.rsplit('/').next().unwrap_or(name).contains(k))
|
||||
|| name.contains("/lifecycle/")
|
||||
|| name.contains("/registries/")
|
||||
|| name.contains("/registry/")
|
||||
}
|
||||
|
||||
/// The code census: how many of each feature, and examples.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Code {
|
||||
pub classes: usize,
|
||||
pub features: BTreeMap<Feature, usize>,
|
||||
/// The game events it subscribes to, by simple name.
|
||||
pub events: BTreeSet<String>,
|
||||
/// Blocks and items with behaviour, and the methods they override.
|
||||
pub examples: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Code {
|
||||
/// Whether it does anything beyond registering blocks and items.
|
||||
pub fn behaviour(&self) -> bool {
|
||||
self.features
|
||||
.keys()
|
||||
.any(|f| *f != Feature::BlockShape && *f != Feature::Particle)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads every class of a jar. `classes` are the class files' bytes.
|
||||
pub fn census<'a>(classes: impl IntoIterator<Item = &'a [u8]>) -> Code {
|
||||
let own: BTreeMap<String, Class> = classes
|
||||
.into_iter()
|
||||
.filter_map(parse)
|
||||
.map(|c| (c.name.clone(), c))
|
||||
.collect();
|
||||
let mut code = Code {
|
||||
classes: own.len(),
|
||||
..Code::default()
|
||||
};
|
||||
let mut count = |f: Feature| *code.features.entry(f).or_default() += 1;
|
||||
for c in own.values() {
|
||||
if c.mixin {
|
||||
count(Feature::Mixin);
|
||||
continue;
|
||||
}
|
||||
// The first class outside the jar the chain reaches, and the
|
||||
// methods declared along the way.
|
||||
let mut methods: BTreeSet<&str> = c.methods.iter().map(String::as_str).collect();
|
||||
let mut at = c;
|
||||
let mut seen = 0;
|
||||
while !external(&at.superclass, &own) && seen < 64 {
|
||||
at = &own[&at.superclass];
|
||||
methods.extend(at.methods.iter().map(String::as_str));
|
||||
seen += 1;
|
||||
}
|
||||
let base = at.superclass.as_str();
|
||||
let kind = kind_of_game_class(base).or_else(|| {
|
||||
c.interfaces.iter().find_map(|i| match i.as_str() {
|
||||
"net/minecraft/network/protocol/common/custom/CustomPacketPayload" => {
|
||||
Some(Feature::Network)
|
||||
}
|
||||
"net/minecraft/world/MenuProvider" => Some(Feature::Menu),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
let Some(kind) = kind else {
|
||||
continue;
|
||||
};
|
||||
let feature = match kind {
|
||||
Feature::BlockBehaviour => {
|
||||
let behaviour: Vec<&str> = methods
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|m| !BLOCK_LOOKS.contains(m) && !BLOCK_SHAPES.contains(m))
|
||||
.collect();
|
||||
if !behaviour.is_empty() {
|
||||
code.examples.insert(
|
||||
c.name.rsplit('/').next().unwrap_or("").to_owned(),
|
||||
behaviour.iter().map(|m| m.to_string()).collect(),
|
||||
);
|
||||
if behaviour.iter().any(|m| obfuscated_method(m)) {
|
||||
Some(Feature::Unread)
|
||||
} else {
|
||||
Some(Feature::BlockBehaviour)
|
||||
}
|
||||
} else if methods.iter().any(|m| BLOCK_SHAPES.contains(m)) {
|
||||
Some(Feature::BlockShape)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Feature::ItemBehaviour => {
|
||||
let behaviour: Vec<&str> = methods
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|m| !ITEM_LOOKS.contains(m))
|
||||
.collect();
|
||||
if behaviour.is_empty() {
|
||||
None
|
||||
} else {
|
||||
code.examples.insert(
|
||||
c.name.rsplit('/').next().unwrap_or("").to_owned(),
|
||||
behaviour.iter().map(|m| m.to_string()).collect(),
|
||||
);
|
||||
Some(Feature::ItemBehaviour)
|
||||
}
|
||||
}
|
||||
// A class extending an obfuscated game class without declaring
|
||||
// anything adds nothing to read.
|
||||
Feature::Unread if methods.is_empty() => None,
|
||||
k => Some(k),
|
||||
};
|
||||
if let Some(f) = feature {
|
||||
count(f);
|
||||
}
|
||||
}
|
||||
for c in own.values() {
|
||||
for r in &c.refs {
|
||||
let event = (r.starts_with("net/neoforged/neoforge/event/")
|
||||
|| r.starts_with("net/minecraftforge/event/")
|
||||
|| r.starts_with("net/fabricmc/fabric/api/event/")
|
||||
|| r.starts_with("net/fabricmc/fabric/api/entity/event/"))
|
||||
&& !registration_event(r);
|
||||
if event {
|
||||
let simple = r.rsplit('/').next().unwrap_or(r);
|
||||
code.events
|
||||
.insert(simple.split('$').next().unwrap_or(simple).to_owned());
|
||||
}
|
||||
if r.starts_with("com/mojang/brigadier/")
|
||||
&& !code.features.contains_key(&Feature::Command)
|
||||
{
|
||||
code.features.insert(Feature::Command, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !code.events.is_empty() {
|
||||
code.features.insert(Feature::Events, code.events.len());
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests_support {
|
||||
/// A class file with `name` extending `superclass`, declaring `methods`
|
||||
/// and naming `refs` in its constant pool.
|
||||
pub fn class_with(
|
||||
name: &str,
|
||||
superclass: &str,
|
||||
methods: &[&str],
|
||||
refs: &[&str],
|
||||
mixin: bool,
|
||||
) -> Vec<u8> {
|
||||
let mut pool: Vec<Vec<u8>> = Vec::new();
|
||||
let utf = |pool: &mut Vec<Vec<u8>>, s: &str| -> u16 {
|
||||
let mut e = vec![1];
|
||||
e.extend((s.len() as u16).to_be_bytes());
|
||||
e.extend(s.as_bytes());
|
||||
pool.push(e);
|
||||
pool.len() as u16
|
||||
};
|
||||
let class = |pool: &mut Vec<Vec<u8>>, s: &str| -> u16 {
|
||||
let u = utf(pool, s);
|
||||
let mut e = vec![7];
|
||||
e.extend(u.to_be_bytes());
|
||||
pool.push(e);
|
||||
pool.len() as u16
|
||||
};
|
||||
let this = class(&mut pool, name);
|
||||
let sup = class(&mut pool, superclass);
|
||||
for r in refs {
|
||||
class(&mut pool, r);
|
||||
}
|
||||
// A long takes two slots.
|
||||
pool.push(vec![5, 0, 0, 0, 0, 0, 0, 0, 1]);
|
||||
pool.push(Vec::new());
|
||||
if mixin {
|
||||
utf(&mut pool, "Lorg/spongepowered/asm/mixin/Mixin;");
|
||||
}
|
||||
let desc = utf(&mut pool, "()V");
|
||||
let names: Vec<u16> = methods.iter().map(|m| utf(&mut pool, m)).collect();
|
||||
let mut out = vec![0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 65];
|
||||
out.extend(((pool.len() + 1) as u16).to_be_bytes());
|
||||
for e in &pool {
|
||||
out.extend(e);
|
||||
}
|
||||
out.extend([0, 0x21]);
|
||||
out.extend(this.to_be_bytes());
|
||||
out.extend(sup.to_be_bytes());
|
||||
out.extend([0, 0]); // interfaces
|
||||
out.extend([0, 0]); // fields
|
||||
out.extend((names.len() as u16).to_be_bytes());
|
||||
for n in names {
|
||||
out.extend([0, 1]);
|
||||
out.extend(n.to_be_bytes());
|
||||
out.extend(desc.to_be_bytes());
|
||||
// One attribute, to be skipped.
|
||||
out.extend([0, 1, 0, 1, 0, 0, 0, 2, 0, 0]);
|
||||
}
|
||||
out.extend([0, 0]); // class attributes
|
||||
out
|
||||
}
|
||||
|
||||
/// A class extending `superclass` and declaring nothing.
|
||||
pub fn class_file(name: &str, superclass: &str) -> Vec<u8> {
|
||||
class_with(name, superclass, &[], &[], false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::tests_support::class_with as class_file;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_the_header_methods_and_pool() {
|
||||
let bytes = class_file(
|
||||
"a/Lamp",
|
||||
"net/minecraft/world/level/block/Block",
|
||||
&["<init>", "useWithoutItem", "lambda$x$0"],
|
||||
&["net/minecraft/world/item/Item"],
|
||||
false,
|
||||
);
|
||||
let c = parse(&bytes).unwrap();
|
||||
assert_eq!(c.name, "a/Lamp");
|
||||
assert_eq!(c.superclass, "net/minecraft/world/level/block/Block");
|
||||
assert_eq!(c.methods, ["useWithoutItem"]);
|
||||
assert!(c.refs.contains("net/minecraft/world/item/Item"));
|
||||
assert!(!c.mixin);
|
||||
assert!(parse(&bytes[..bytes.len() - 3]).is_none());
|
||||
assert!(parse(b"not a class").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_own_classes_to_the_game() {
|
||||
let block = "net/minecraft/world/level/block/Block";
|
||||
let files = [
|
||||
// Looks only: a template covers it.
|
||||
class_file("m/Plain", block, &["getStateForPlacement"], &[], false),
|
||||
class_file("m/Round", block, &["getShape"], &[], false),
|
||||
// Behaviour two levels down.
|
||||
class_file("m/Base", block, &["randomTick"], &[], false),
|
||||
class_file("m/Lamp", "m/Base", &[], &[], false),
|
||||
class_file(
|
||||
"m/Tile",
|
||||
"net/minecraft/world/level/block/entity/BlockEntity",
|
||||
&[],
|
||||
&[],
|
||||
false,
|
||||
),
|
||||
class_file("m/Mix", "java/lang/Object", &[], &[], true),
|
||||
class_file(
|
||||
"m/Old",
|
||||
"net/minecraft/class_2248",
|
||||
&["method_9534"],
|
||||
&[],
|
||||
false,
|
||||
),
|
||||
class_file(
|
||||
"m/Events",
|
||||
"java/lang/Object",
|
||||
&[],
|
||||
&[
|
||||
"net/neoforged/neoforge/event/entity/player/PlayerInteractEvent$RightClickBlock",
|
||||
"net/neoforged/neoforge/event/BuildCreativeModeTabContentsEvent",
|
||||
"net/neoforged/neoforge/registries/DeferredRegister",
|
||||
],
|
||||
false,
|
||||
),
|
||||
class_file(
|
||||
"m/Gem",
|
||||
"net/minecraft/world/item/Item",
|
||||
&["appendHoverText"],
|
||||
&[],
|
||||
false,
|
||||
),
|
||||
];
|
||||
let code = census(files.iter().map(Vec::as_slice));
|
||||
assert_eq!(code.classes, 9);
|
||||
let n = |f| code.features.get(&f).copied().unwrap_or(0);
|
||||
assert_eq!(n(Feature::BlockBehaviour), 2, "{code:?}");
|
||||
assert_eq!(n(Feature::BlockShape), 1);
|
||||
assert_eq!(n(Feature::BlockEntity), 1);
|
||||
assert_eq!(n(Feature::Mixin), 1);
|
||||
assert_eq!(n(Feature::Unread), 1);
|
||||
assert_eq!(n(Feature::ItemBehaviour), 0);
|
||||
assert_eq!(
|
||||
code.events.iter().collect::<Vec<_>>(),
|
||||
["PlayerInteractEvent"]
|
||||
);
|
||||
assert!(code.behaviour());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registration_only_is_not_behaviour() {
|
||||
let files = [
|
||||
class_file(
|
||||
"m/Mod",
|
||||
"java/lang/Object",
|
||||
&["register"],
|
||||
&[
|
||||
"net/neoforged/neoforge/registries/DeferredRegister",
|
||||
"net/minecraft/world/level/block/Block",
|
||||
],
|
||||
false,
|
||||
),
|
||||
class_file(
|
||||
"m/Pillar",
|
||||
"net/minecraft/world/level/block/RotatedPillarBlock",
|
||||
&[],
|
||||
&[],
|
||||
false,
|
||||
),
|
||||
];
|
||||
let code = census(files.iter().map(Vec::as_slice));
|
||||
assert!(!code.behaviour(), "{code:?}");
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ pub enum How {
|
||||
Downloaded,
|
||||
/// Copied from the player's folder.
|
||||
Local,
|
||||
/// Only on CurseForge, whose downloads need an API key.
|
||||
/// Only on CurseForge, whose downloads are coming soon (its API needs a paid key).
|
||||
NeedsKey,
|
||||
NotFound,
|
||||
Failed,
|
||||
@@ -52,7 +52,7 @@ impl How {
|
||||
How::Present => "already here",
|
||||
How::Downloaded => "downloaded",
|
||||
How::Local => "copied from your folder",
|
||||
How::NeedsKey => "needs a CurseForge key",
|
||||
How::NeedsKey => "CurseForge downloads coming soon",
|
||||
How::NotFound => "not found",
|
||||
How::Failed => "failed",
|
||||
}
|
||||
@@ -163,7 +163,7 @@ pub fn fetch(
|
||||
}
|
||||
write_json(&work.join("fetch.json"), &fetched)?;
|
||||
log(format!(
|
||||
"jars: {} downloaded, {} copied, {} already here, {} need a CurseForge key, {} not found, {} failed",
|
||||
"jars: {} downloaded, {} copied, {} already here, {} on CurseForge only (CurseForge downloads coming soon), {} not found, {} failed",
|
||||
fetched.count(How::Downloaded),
|
||||
fetched.count(How::Local),
|
||||
fetched.count(How::Present),
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
//! jars they downloaded and what is carried over from them stay there and
|
||||
//! are never uploaded or committed.
|
||||
pub mod carry;
|
||||
pub mod check;
|
||||
pub mod classes;
|
||||
pub mod classify;
|
||||
pub mod fetch;
|
||||
pub mod import;
|
||||
|
||||
@@ -19,6 +19,10 @@
|
||||
//! - `report <work>`: the coverage report, per mod ported, partial, not yet
|
||||
//! or not needed with the reason, in `<work>/coverage.json` and
|
||||
//! `coverage.md`.
|
||||
//! - `check <jar> <out>`: one mod jar on its own, as the launcher's mod
|
||||
//! browser installs it: carried over into `<out>/carry/`, its classes
|
||||
//! read, and the verdict (Works, Partly, Doesn't run) in
|
||||
//! `<out>/check.json`.
|
||||
//! - `port <pack> <work> [--from <folder>] [--resources <prepared>]`: every
|
||||
//! step for the portable mods, as the launcher's "Import modpack" runs it.
|
||||
//!
|
||||
@@ -30,7 +34,7 @@ use std::{
|
||||
process::ExitCode,
|
||||
};
|
||||
|
||||
const USAGE: &str = "usage: horizon-port-pack import <pack> <work> | inventory <work> [--offline] | fetch <work> [--from <folder>] [<mod id>...] | carry <work> [--resources <prepared>] [<mod id>...] | report <work> | port <pack> <work> [--from <folder>] [--resources <prepared>]";
|
||||
const USAGE: &str = "usage: horizon-port-pack import <pack> <work> | inventory <work> [--offline] | fetch <work> [--from <folder>] [<mod id>...] | carry <work> [--resources <prepared>] [<mod id>...] | report <work> | check <jar> <out> | port <pack> <work> [--from <folder>] [--resources <prepared>]";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
@@ -66,6 +70,17 @@ fn main() -> ExitCode {
|
||||
println!("{}", work.join("coverage.md").display());
|
||||
Ok(())
|
||||
}
|
||||
Some("check") => {
|
||||
let c = horizon_port_pack::check::check(path(1)?, path(2)?)?;
|
||||
println!("{}: {}. {}", c.mod_id, c.verdict.label(), c.summary);
|
||||
for p in &c.ports {
|
||||
println!(" ports: {p}");
|
||||
}
|
||||
for s in &c.skipped {
|
||||
println!(" skipped: {s}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some("port") => {
|
||||
let work = path(2)?;
|
||||
pipeline::import(path(1)?, work, log)?;
|
||||
|
||||
@@ -150,7 +150,16 @@ pub fn carry(
|
||||
})
|
||||
.flatten()
|
||||
.collect();
|
||||
let in_pack = |m: &str| in_pack.contains(m);
|
||||
// A namespace two carried mods both claim (a library's they both use, such as YUNG's API's
|
||||
// `yungsapi`, whose own jar isn't read) is neither's: either would refuse the other in the
|
||||
// game. Its files stay outside both.
|
||||
let claims = records.iter().filter(|r| chosen(r)).filter_map(|r| {
|
||||
let (jar, info) = (r.jar.as_ref()?, r.info.as_ref()?);
|
||||
let owned = carry::namespaces_claimed(jar, &info.mod_id, &|m| in_pack.contains(m)).ok()?;
|
||||
Some((r.key.as_str(), owned))
|
||||
});
|
||||
let shared = shared_namespaces(claims, log);
|
||||
let in_pack = |m: &str| in_pack.contains(m) || shared.contains(m);
|
||||
let pack = carry::Pack {
|
||||
loaded: &loaded,
|
||||
mods: &in_pack,
|
||||
@@ -219,6 +228,61 @@ pub fn carry(
|
||||
Ok(done)
|
||||
}
|
||||
|
||||
/// Which carried-over mods (`mods/<key>/carry` folders) the game loads together, in the order
|
||||
/// given: as the game does, the first of two owning one namespace stays on. Returns the ones on,
|
||||
/// and a line for each one left off.
|
||||
pub fn loadable(mods: &[std::path::PathBuf]) -> (Vec<std::path::PathBuf>, Vec<String>) {
|
||||
let mut on: Vec<(std::path::PathBuf, String, Vec<String>)> = Vec::new();
|
||||
let mut off = Vec::new();
|
||||
for path in mods {
|
||||
let manifest = fs::read_to_string(path.join(horizon_mods::manifest::MANIFEST))
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|t| horizon_mods::Manifest::parse(&t));
|
||||
let m = match manifest {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
off.push(format!("{}: {e}", path.display()));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let owned: Vec<String> = std::iter::once(m.id.clone())
|
||||
.chain(m.namespaces.iter().cloned())
|
||||
.collect();
|
||||
let clash = on
|
||||
.iter()
|
||||
.find_map(|(_, id, ns)| horizon_mods::content::clash((id, ns), (&m.id, &owned)));
|
||||
match clash {
|
||||
Some(why) => off.push(format!("{} not loaded: {why}", m.id)),
|
||||
None => on.push((path.clone(), m.id, owned)),
|
||||
}
|
||||
}
|
||||
(on.into_iter().map(|(p, _, _)| p).collect(), off)
|
||||
}
|
||||
|
||||
/// The namespaces more than one mod claims, from each mod's (key, claimed namespaces).
|
||||
fn shared_namespaces<'a>(
|
||||
claims: impl Iterator<Item = (&'a str, Vec<String>)>,
|
||||
log: Log,
|
||||
) -> BTreeSet<String> {
|
||||
let mut by_namespace: BTreeMap<String, Vec<&str>> = BTreeMap::new();
|
||||
for (key, owned) in claims {
|
||||
for ns in owned {
|
||||
by_namespace.entry(ns).or_default().push(key);
|
||||
}
|
||||
}
|
||||
by_namespace
|
||||
.into_iter()
|
||||
.filter(|(_, mods)| mods.len() > 1)
|
||||
.map(|(ns, mods)| {
|
||||
log(format!(
|
||||
"namespace {ns} is claimed by {}: left to none of them",
|
||||
mods.join(", ")
|
||||
));
|
||||
ns
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The pack's title as the report heads it.
|
||||
pub fn title(pack: &import::Pack) -> String {
|
||||
format!(
|
||||
@@ -279,3 +343,51 @@ pub fn port(
|
||||
}
|
||||
Ok((fetched, report(work, log)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_namespace_two_mods_claim_is_neither_s() {
|
||||
let claims = [
|
||||
("betterdungeons", vec!["yungsapi".to_owned()]),
|
||||
("betterfortresses", vec!["yungsapi".to_owned()]),
|
||||
(
|
||||
"towns_and_towers",
|
||||
vec!["kaisyn".to_owned(), "towns_and_towers".to_owned()],
|
||||
),
|
||||
];
|
||||
let shared = shared_namespaces(claims.into_iter(), &|_| {});
|
||||
assert_eq!(shared.into_iter().collect::<Vec<_>>(), ["yungsapi"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_of_two_mods_owning_a_namespace_loads() {
|
||||
let root = std::env::temp_dir().join(format!("port-pack-loadable-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let carry = |key: &str, namespaces: &str| {
|
||||
let dir = root.join(key).join("carry");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(
|
||||
dir.join("horizon-mod.toml"),
|
||||
format!(
|
||||
"id = \"{key}\"\nname = \"{key}\"\nversion = \"1\"\napi = \"0.2\"\n\
|
||||
capabilities = [\"registries\"]\nnamespaces = [{namespaces}]\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
dir
|
||||
};
|
||||
let mods = [
|
||||
carry("betterdungeons", "\"yungsapi\""),
|
||||
carry("betterfortresses", "\"yungsapi\""),
|
||||
carry("ruby", ""),
|
||||
];
|
||||
let (on, off) = loadable(&mods);
|
||||
assert_eq!(on, [mods[0].clone(), mods[2].clone()]);
|
||||
assert_eq!(off.len(), 1);
|
||||
assert!(off[0].starts_with("betterfortresses not loaded"), "{off:?}");
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,6 +458,9 @@ move_entity!(MoveEntityPos, pos: true, rot: false);
|
||||
move_entity!(MoveEntityPosRot, pos: true, rot: true);
|
||||
move_entity!(MoveEntityRot, pos: false, rot: true);
|
||||
packet!(OpenScreen { container: i32 => VarInt, menu: i32 => VarInt, title: Tag => Nbt });
|
||||
// ClientboundMountScreenOpenPacket: a horse's or llama's inventory, with its
|
||||
// chest's columns (`getInventoryColumns`).
|
||||
packet!(MountScreenOpen { container: i32 => VarInt, columns: i32 => VarInt, entity: i32 => Int });
|
||||
packet!(PlayerAbilities { flags: i8 => Byte, flying_speed: f32 => Float, walking_speed: f32 => Float });
|
||||
/// MessageSignature.Packed: an index into the last-seen cache or a full signature.
|
||||
pub struct PackedSignature;
|
||||
@@ -672,6 +675,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 {
|
||||
@@ -1492,6 +1500,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
MoveEntityPosRot(MoveEntityPosRot) = MOVE_ENTITY_POS_ROT,
|
||||
MoveEntityRot(MoveEntityRot) = MOVE_ENTITY_ROT,
|
||||
MerchantOffers(MerchantOffers) = MERCHANT_OFFERS,
|
||||
MountScreenOpen(MountScreenOpen) = MOUNT_SCREEN_OPEN,
|
||||
OpenScreen(OpenScreen) = OPEN_SCREEN,
|
||||
Ping(Ping) = PING,
|
||||
PongResponse(crate::packets::status::Ping) = PONG_RESPONSE,
|
||||
@@ -1529,6 +1538,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 +1812,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 +1888,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,
|
||||
@@ -2162,6 +2183,11 @@ mod tests {
|
||||
menu: 2,
|
||||
title: literal("Chest"),
|
||||
}),
|
||||
Clientbound::MountScreenOpen(MountScreenOpen {
|
||||
container: 4,
|
||||
columns: 5,
|
||||
entity: 300,
|
||||
}),
|
||||
Clientbound::MerchantOffers(MerchantOffers {
|
||||
container: 3,
|
||||
offers: vec![NetOffer {
|
||||
|
||||
@@ -5,7 +5,7 @@ This server receives what players choose to send (performance summaries, crash a
|
||||
cargo run --release # in this folder: its own workspace, like the launcher's
|
||||
PORT=8080 HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3 horizon-telemetry-server
|
||||
|
||||
The launcher sends to it when `HORIZON_TELEMETRY_URL` is set (and to `DEFAULT_ENDPOINT` in `crates/horizon-telemetry` once there is one).
|
||||
It runs at **https://telemetry.playhorizon.dev** (`DEFAULT_ENDPOINT` in `crates/horizon-telemetry`). The game and the launcher use it unless `HORIZON_TELEMETRY_URL` names another server, or is `off` (tests and automated runs send nothing).
|
||||
|
||||
## Endpoints
|
||||
|
||||
@@ -14,11 +14,34 @@ The launcher sends to it when `HORIZON_TELEMETRY_URL` is set (and to `DEFAULT_EN
|
||||
| `POST /v1/batch` | A zstd batch (`Content-Encoding: zstd`, at most 256 KiB, 1 MiB inflated, 64 items). Returns 204. Returns 400 for a bad batch, 413 for one too large, 415 if it is not zstd, 429 when over a limit. |
|
||||
| `DELETE /v1/installs/<id>` | Deletes everything that install sent. Its share of the daily totals is rebuilt at once. |
|
||||
| `GET /v1/aggregate?days=30` | The totals the website reads. Cached 10 minutes, with `Access-Control-Allow-Origin` set to the website. |
|
||||
| `GET /v1/benchmarks/summary` | Players' benchmark uploads grouped by GPU, CPU, render distance and game, for the website's Benchmarks page (below). Cached 10 minutes, same `Access-Control-Allow-Origin`. |
|
||||
| `POST /v1/live` | A game's "I'm playing" ping (JSON, at most 512 bytes). Returns 204. Returns 400 for a bad ping, 413 for one too large, 429 over the address's limit, 503 when it holds `LIVE_MAX_SESSIONS` already. |
|
||||
| `GET /v1/live` | How many play now, rounded: `playing`, `lan`, `versions`, `platforms`. Made again at most every 15 seconds, with the same `Access-Control-Allow-Origin`. |
|
||||
| `GET /healthz` | `ok` |
|
||||
|
||||
The totals are grouped per version, OS, GPU vendor and render distance. Each group has its sessions, install-days, hours played, the 14 frame-time buckets summed, and the mean p50 and p99 frame times. Groups with fewer than 5 install-days are left out. The totals also list crash counts per version and the newest 50 benchmark uploads.
|
||||
The totals are grouped per version, OS, GPU vendor and render distance. Each group has its sessions, install-days, hours played, the 14 frame-time buckets summed, and the mean p50 and p99 frame times. Groups with fewer than 5 install-days are left out. The totals also list crash counts per version. Benchmark uploads are published only through the summary below, never one by one.
|
||||
|
||||
## Benchmarks summary
|
||||
|
||||
`src/summary.rs` makes it with the same rules as `website/scripts/benchmarks.mjs`, which bakes the page's fallback copy; both are tested against the same fixtures (`website/scripts/fixtures/benchmarks/`).
|
||||
|
||||
- Only reports that compare: a version 1 `horizon-benchmark-report` of the standard flight over the four scenes, VSync off, no frame cap, on screen, from Horizon or plain vanilla, naming its GPU and CPU.
|
||||
- A group (GPU, CPU, render distance, game) is published only with **at least 3 different installs**. Each install counts once: the median of its runs, then the median across installs.
|
||||
- Out go the names, the counts, the newest three versions and the medians. Never an install ID, a day, an OS version, a driver, a memory size or a screen.
|
||||
|
||||
```json
|
||||
{
|
||||
"format": "horizon-benchmark-summary", "version": 1, "generated": "2026-10-22T20:00:00Z", "min_installs": 3,
|
||||
"groups": [{
|
||||
"gpu": "NVIDIA GeForce RTX 4080", "cpu": "13th Gen Intel Core i7-13700KF", "render_distance": 12,
|
||||
"game": "horizon", "source": "players", "installs": 3, "reports": 4, "versions": ["v0.2.1", "v0.2.0"],
|
||||
"medians": { "avg_fps": 515, "low_1pct_fps": 120, "p95_ms": 3.5, "world_ms": 4500,
|
||||
"chunk_load_ms": 1400, "rss_peak_mb": 1450, "rss_steady_mb": 1250 }
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Frame rates are whole numbers, milliseconds have one decimal under 10, megabytes are whole. Groups come most installs first. A deleted install leaves its groups at once.
|
||||
|
||||
## Storage
|
||||
|
||||
@@ -45,7 +68,7 @@ All are environment variables:
|
||||
- `HORIZON_TELEMETRY_MIN_INSTALL_DAYS` (5)
|
||||
- `HORIZON_TELEMETRY_REQUESTS_PER_HOUR` per address (60, bursts of 6)
|
||||
- `HORIZON_TELEMETRY_ITEMS_PER_DAY` per install (100)
|
||||
- `HORIZON_TELEMETRY_TRUST_PROXY=1` behind a proxy (the client's address is then the first of `X-Forwarded-For`)
|
||||
- `HORIZON_TELEMETRY_TRUST_PROXY=1` behind a proxy (the client's address is then the proxy's `X-Real-IP`, else the last `X-Forwarded-For` entry; it is used only for the rate limits, in memory, and never stored or logged)
|
||||
- `HORIZON_TELEMETRY_ALLOW_ORIGIN` (`https://playhorizon.dev`)
|
||||
- `HORIZON_TELEMETRY_LIVE_PER_HOUR` per address, pings and reads (600, bursts of 60: ten players behind one address)
|
||||
- `HORIZON_TELEMETRY_LIVE_WINDOW_SECONDS` (120)
|
||||
@@ -55,6 +78,14 @@ All are environment variables:
|
||||
|
||||
`Dockerfile` builds it from the repository root (`docker build -f crates/horizon-telemetry-server/Dockerfile .`). The database goes on a volume mounted at `/data`.
|
||||
|
||||
On Railway it is a service of the same project as the website:
|
||||
|
||||
- Source: this repository, root directory `/` (the Dockerfile needs the shared crate), config file `/crates/horizon-telemetry-server/railway.json` (Dockerfile build, health check `/healthz`, one replica in `europe-west4`, Amsterdam: one SQLite file can't be shared).
|
||||
- A volume mounted at `/data`. The Dockerfile already sets `HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3` and `HORIZON_TELEMETRY_TRUST_PROXY=1`; Railway sets `PORT`.
|
||||
- The custom domain `telemetry.playhorizon.dev`: a `CNAME` at Porkbun to the target Railway gives.
|
||||
|
||||
Check it with `curl https://telemetry.playhorizon.dev/healthz`.
|
||||
|
||||
At Railway's prices (RAM $10/GB-month, CPU $20/vCPU-month, volumes $0.15/GB-month, egress $0.05/GB), one more service with a 1 GB volume uses about $0.35 a month:
|
||||
|
||||
- RAM about 15 MB: $0.15
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://railway.com/railway.schema.json",
|
||||
"build": {
|
||||
"builder": "DOCKERFILE",
|
||||
"dockerfilePath": "crates/horizon-telemetry-server/Dockerfile",
|
||||
"watchPatterns": [
|
||||
"/crates/horizon-telemetry/**",
|
||||
"/crates/horizon-telemetry-server/**",
|
||||
"/Cargo.toml"
|
||||
]
|
||||
},
|
||||
"deploy": {
|
||||
"healthcheckPath": "/healthz",
|
||||
"healthcheckTimeout": 60,
|
||||
"restartPolicyType": "ON_FAILURE",
|
||||
"restartPolicyMaxRetries": 5,
|
||||
"multiRegionConfig": {
|
||||
"europe-west4-drams3a": { "numReplicas": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! The hardware classes the public output breaks results down by. Coarse on purpose: a class
|
||||
//! holds many machines, and a published cell still needs `MIN_INSTALLS` different installs.
|
||||
//! `website/scripts/benchmarks.mjs` has the same functions, tested on the same fixtures.
|
||||
//!
|
||||
//! The raw values (the exact memory, the driver, the screen) stay in the database for the
|
||||
//! retention period and are never published.
|
||||
use horizon_telemetry::payload::System;
|
||||
use serde_json::Value;
|
||||
|
||||
/// The dimensions, in the order [`of_report`] and [`of_system`] return them.
|
||||
pub const DIMENSIONS: [&str; 5] = ["ram", "vram", "storage", "os", "gpu_kind"];
|
||||
|
||||
pub type Classes = [Option<&'static str>; 5];
|
||||
|
||||
/// Installed memory in GB (a little under the size on the box: some is reserved).
|
||||
pub fn ram(gb: f64) -> Option<&'static str> {
|
||||
Some(match gb {
|
||||
g if g.is_nan() || g <= 0.0 => return None,
|
||||
g if g <= 5.0 => "4 GB or less",
|
||||
g if g <= 10.0 => "8 GB",
|
||||
g if g <= 20.0 => "16 GB",
|
||||
g if g <= 40.0 => "32 GB",
|
||||
_ => "64 GB or more",
|
||||
})
|
||||
}
|
||||
|
||||
/// A GPU's own memory in MiB; an integrated GPU shares the system's.
|
||||
pub fn vram(mb: f64, kind: &str) -> Option<&'static str> {
|
||||
if gpu_kind(kind) == Some("integrated") {
|
||||
return Some("shared");
|
||||
}
|
||||
Some(match mb {
|
||||
m if m.is_nan() || m <= 0.0 => return None,
|
||||
m if m <= 2560.0 => "2 GB or less",
|
||||
m if m <= 4608.0 => "4 GB",
|
||||
m if m <= 6656.0 => "6 GB",
|
||||
m if m <= 8704.0 => "8 GB",
|
||||
m if m <= 12800.0 => "12 GB",
|
||||
m if m <= 16896.0 => "16 GB",
|
||||
_ => "more than 16 GB",
|
||||
})
|
||||
}
|
||||
|
||||
pub fn storage(s: &str) -> Option<&'static str> {
|
||||
["nvme", "ssd", "hdd"].into_iter().find(|k| *k == s)
|
||||
}
|
||||
|
||||
pub fn os(s: &str) -> Option<&'static str> {
|
||||
["linux", "macos", "windows"].into_iter().find(|k| *k == s)
|
||||
}
|
||||
|
||||
/// `integrated` or `discrete`, from either wording (`IntegratedGpu`, as wgpu says it, too).
|
||||
pub fn gpu_kind(s: &str) -> Option<&'static str> {
|
||||
match s {
|
||||
"integrated" | "IntegratedGpu" => Some("integrated"),
|
||||
"discrete" | "DiscreteGpu" => Some("discrete"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A benchmark report's classes (`docs/benchmark-report.md`'s `hardware`).
|
||||
pub fn of_report(report: &Value) -> Classes {
|
||||
let hw = &report["hardware"];
|
||||
let kind = hw["gpu"]["kind"].as_str().unwrap_or("");
|
||||
[
|
||||
hw["ram_mb"].as_f64().and_then(|mb| ram(mb / 1024.0)),
|
||||
vram(hw["gpu"]["vram_mb"].as_f64().unwrap_or(0.0), kind),
|
||||
storage(hw["storage"].as_str().unwrap_or("")),
|
||||
os(hw["os"].as_str().unwrap_or("")),
|
||||
gpu_kind(kind),
|
||||
]
|
||||
}
|
||||
|
||||
/// A telemetry item's machine's classes.
|
||||
pub fn of_system(s: &System) -> Classes {
|
||||
[
|
||||
ram(f64::from(s.ram_gb)),
|
||||
vram(f64::from(s.vram_mb), &s.gpu_kind),
|
||||
storage(&s.storage),
|
||||
os(&s.os),
|
||||
gpu_kind(&s.gpu_kind),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn classes_are_coarse() {
|
||||
assert_eq!(ram(15.6), Some("16 GB"));
|
||||
assert_eq!(ram(31.0), Some("32 GB"));
|
||||
assert_eq!(ram(64.0), Some("64 GB or more"));
|
||||
assert_eq!(ram(0.0), None);
|
||||
assert_eq!(vram(16376.0, "discrete"), Some("16 GB"));
|
||||
assert_eq!(vram(8192.0, "DiscreteGpu"), Some("8 GB"));
|
||||
assert_eq!(vram(0.0, "integrated"), Some("shared"));
|
||||
assert_eq!(vram(0.0, ""), None);
|
||||
assert_eq!(storage("nvme"), Some("nvme"));
|
||||
assert_eq!(storage("tape"), None);
|
||||
assert_eq!(gpu_kind("virtual"), None);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
//! - `POST /v1/batch`: a zstd batch from the launcher, checked by `horizon_telemetry::batch`.
|
||||
//! - `DELETE /v1/installs/<id>`: everything an install sent goes.
|
||||
//! - `GET /v1/aggregate?days=30`: the anonymous totals the website reads, cached.
|
||||
//! - `GET /v1/benchmarks/summary`: players' benchmark results grouped by GPU and CPU, groups of at
|
||||
//! least 3 installs only (`summary`), cached; the website's Benchmarks page reads it.
|
||||
//! - `POST /v1/live`: a game's anonymous "I'm playing" ping (`live`, in memory only).
|
||||
//! - `GET /v1/live`: how many play now, rounded, cached briefly.
|
||||
//! - `GET /healthz`.
|
||||
@@ -24,8 +26,10 @@ use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post};
|
||||
use horizon_telemetry::batch;
|
||||
|
||||
pub mod classes;
|
||||
pub mod live;
|
||||
pub mod store;
|
||||
pub mod summary;
|
||||
|
||||
use horizon_telemetry::live::{MAX_PING_BYTES, Ping};
|
||||
use live::Live;
|
||||
@@ -40,7 +44,8 @@ pub struct Config {
|
||||
pub requests_per_hour: f64,
|
||||
/// Items one install may send a day.
|
||||
pub items_per_day: u32,
|
||||
/// Behind a proxy (Railway, Fly…): the client's address is the first of X-Forwarded-For.
|
||||
/// Behind a proxy (Railway, Fly…): the client's address is the proxy's `X-Real-IP`, else the
|
||||
/// last `X-Forwarded-For` entry.
|
||||
pub trust_proxy: bool,
|
||||
/// The website allowed to read the totals from a browser.
|
||||
pub allow_origin: String,
|
||||
@@ -117,6 +122,8 @@ pub struct App {
|
||||
live_cache: Mutex<Option<(Instant, String)>>,
|
||||
/// `/v1/aggregate` answers by `days`, with when they were made.
|
||||
cache: Mutex<HashMap<u32, (Instant, String)>>,
|
||||
/// `/v1/benchmarks/summary`'s answer and when it was made.
|
||||
summary_cache: Mutex<Option<(Instant, String)>>,
|
||||
/// Today, in days since 1970 (a test moves it).
|
||||
today: Box<dyn Fn() -> u32 + Send + Sync>,
|
||||
}
|
||||
@@ -148,6 +155,7 @@ impl App {
|
||||
live: Mutex::new(live),
|
||||
live_cache: Mutex::default(),
|
||||
cache: Mutex::default(),
|
||||
summary_cache: Mutex::default(),
|
||||
today,
|
||||
})
|
||||
}
|
||||
@@ -170,20 +178,26 @@ impl App {
|
||||
self.live.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// The address requests are counted under, for the rate limits only: kept in memory, never
|
||||
/// stored or logged. Behind a proxy (Railway) the TCP peer is the proxy, so it is the proxy's
|
||||
/// `X-Real-IP`, else the last `X-Forwarded-For` entry: the one the proxy added, which a client
|
||||
/// can't choose (the first one it can).
|
||||
fn client(&self, headers: &HeaderMap, peer: Option<SocketAddr>) -> IpAddr {
|
||||
let header = |name: &str| headers.get(name)?.to_str().ok();
|
||||
let forwarded = self
|
||||
.config
|
||||
.trust_proxy
|
||||
.then(|| {
|
||||
headers
|
||||
.get("x-forwarded-for")?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.split(',')
|
||||
.next()?
|
||||
.trim()
|
||||
.parse()
|
||||
.ok()
|
||||
header("x-real-ip")
|
||||
.and_then(|ip| ip.trim().parse().ok())
|
||||
.or_else(|| {
|
||||
header("x-forwarded-for")?
|
||||
.rsplit(',')
|
||||
.next()?
|
||||
.trim()
|
||||
.parse()
|
||||
.ok()
|
||||
})
|
||||
})
|
||||
.flatten();
|
||||
forwarded
|
||||
@@ -196,6 +210,12 @@ impl App {
|
||||
self.store().newest_day(install).ok().flatten()
|
||||
}
|
||||
|
||||
/// Drops the cached public answers (after a deletion or expiry).
|
||||
fn forget_cached(&self) {
|
||||
self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
*self.summary_cache.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
|
||||
/// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries and live
|
||||
/// sessions forgotten.
|
||||
pub fn maintain(&self) -> rusqlite::Result<usize> {
|
||||
@@ -209,7 +229,7 @@ impl App {
|
||||
}
|
||||
self.live().forget_expired(Instant::now());
|
||||
if removed > 0 {
|
||||
self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
self.forget_cached();
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
@@ -288,7 +308,7 @@ async fn forget(State(app): State<Arc<App>>, Path(id): Path<String>, req: Reques
|
||||
};
|
||||
match app.store().delete_install(&install) {
|
||||
Ok(_) => {
|
||||
app.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
app.forget_cached();
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -338,6 +358,60 @@ async fn aggregate(State(app): State<Arc<App>>, Query(window): Query<Window>) ->
|
||||
json_response(&app, json, CACHE_FOR.as_secs())
|
||||
}
|
||||
|
||||
/// `GET /v1/benchmarks/summary`: players' benchmark groups (`summary`), made again at most every
|
||||
/// ten minutes.
|
||||
async fn benchmarks(State(app): State<Arc<App>>) -> Response {
|
||||
let cached = app
|
||||
.summary_cache
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.as_ref()
|
||||
.filter(|(at, _)| at.elapsed() < CACHE_FOR)
|
||||
.map(|(_, json)| json.clone());
|
||||
let json = match cached {
|
||||
Some(json) => json,
|
||||
None => {
|
||||
let oldest = (app.today)().saturating_sub(app.config.retention_days);
|
||||
let uploads = match app.store().benchmark_uploads(oldest) {
|
||||
Ok(uploads) => uploads,
|
||||
Err(e) => {
|
||||
eprintln!("horizon-telemetry-server: could not read the benchmarks: {e}");
|
||||
return status(StatusCode::SERVICE_UNAVAILABLE, "try again later");
|
||||
}
|
||||
};
|
||||
let json = summary::summary(&uploads, summary::MIN_INSTALLS, &utc_now()).to_string();
|
||||
*app.summary_cache.lock().unwrap_or_else(|e| e.into_inner()) =
|
||||
Some((Instant::now(), json.clone()));
|
||||
json
|
||||
}
|
||||
};
|
||||
json_response(&app, json, CACHE_FOR.as_secs())
|
||||
}
|
||||
|
||||
/// Now as `YYYY-MM-DDTHH:MM:SSZ`.
|
||||
fn utc_now() -> String {
|
||||
let secs = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
let (days, rest) = (secs / 86_400, secs % 86_400);
|
||||
// Days since 1970 to a civil date (Howard Hinnant's algorithm).
|
||||
let z = days as i64 + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||
format!(
|
||||
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
|
||||
rest / 3600,
|
||||
rest / 60 % 60,
|
||||
rest % 60
|
||||
)
|
||||
}
|
||||
|
||||
/// `POST /v1/live`: one "I'm playing". 204, or 400 for a bad ping, 413 for one too large, 429
|
||||
/// over the address's limit, 503 when the table is full.
|
||||
async fn ping(State(app): State<Arc<App>>, req: Request) -> Response {
|
||||
@@ -407,6 +481,7 @@ pub fn router(app: Arc<App>) -> Router {
|
||||
.route("/v1/live", post(ping).get(playing))
|
||||
.route("/v1/installs/{id}", delete(forget))
|
||||
.route("/v1/aggregate", get(aggregate))
|
||||
.route("/v1/benchmarks/summary", get(benchmarks))
|
||||
.route("/healthz", get(|| async { "ok" }))
|
||||
.with_state(app)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The database: one SQLite file, kept small.
|
||||
//!
|
||||
//! - `systems`: each distinct machine description once. Rows point at it, so a CPU and GPU
|
||||
//! name isn't stored again with every session.
|
||||
//! name isn't stored again with every session. `extra` holds the later hardware fields
|
||||
//! (cores, clocks, GPU maker and kind, VRAM, drive, screen, power, form) as JSON.
|
||||
//! - `perf`: one row per play session, in columns. A frame or tick summary is an 80-byte blob
|
||||
//! ([`pack`]), not JSON.
|
||||
//! - `reports`: crash and bug reports and benchmark uploads, their `data` zstd-compressed.
|
||||
@@ -17,6 +18,7 @@ use horizon_telemetry::Kind;
|
||||
use horizon_telemetry::batch::Batch;
|
||||
use horizon_telemetry::payload::{BUCKET_EDGES_MS, Payload, Summary, System};
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const BUCKETS: usize = BUCKET_EDGES_MS.len() + 1;
|
||||
|
||||
@@ -27,8 +29,8 @@ CREATE TABLE IF NOT EXISTS systems (
|
||||
id INTEGER PRIMARY KEY,
|
||||
os TEXT NOT NULL, os_version TEXT NOT NULL, arch TEXT NOT NULL, cpu TEXT NOT NULL,
|
||||
threads INTEGER NOT NULL, ram_gb INTEGER NOT NULL,
|
||||
gpu TEXT NOT NULL, driver TEXT NOT NULL, backend TEXT NOT NULL,
|
||||
UNIQUE (os, os_version, arch, cpu, threads, ram_gb, gpu, driver, backend)
|
||||
gpu TEXT NOT NULL, driver TEXT NOT NULL, backend TEXT NOT NULL, extra TEXT NOT NULL DEFAULT '{}',
|
||||
UNIQUE (os, os_version, arch, cpu, threads, ram_gb, gpu, driver, backend, extra)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS perf (
|
||||
install BLOB NOT NULL, day INTEGER NOT NULL, version TEXT NOT NULL, system INTEGER NOT NULL,
|
||||
@@ -126,8 +128,9 @@ pub struct Store {
|
||||
|
||||
impl Store {
|
||||
pub fn open(path: &str) -> rusqlite::Result<Self> {
|
||||
let db = Connection::open(path)?;
|
||||
let mut db = Connection::open(path)?;
|
||||
db.execute_batch(SCHEMA)?;
|
||||
migrate(&mut db)?;
|
||||
Ok(Self { db })
|
||||
}
|
||||
|
||||
@@ -357,27 +360,110 @@ impl Store {
|
||||
})?
|
||||
.collect::<Result<_, _>>()?
|
||||
};
|
||||
let benchmarks: Vec<serde_json::Value> = {
|
||||
let mut q = self.db.prepare(
|
||||
"SELECT day, version, body FROM reports WHERE kind = ?1 AND day BETWEEN ?2 AND ?3
|
||||
ORDER BY rowid DESC LIMIT 50",
|
||||
)?;
|
||||
q.query_map(params![kind_code(Kind::Benchmark), from, to], |r| {
|
||||
let body: Vec<u8> = r.get(2)?;
|
||||
Ok(serde_json::json!({
|
||||
"day": r.get::<_, u32>(0)?, "version": r.get::<_, String>(1)?, "report": inflate(&body),
|
||||
}))
|
||||
})?
|
||||
.collect::<Result<_, _>>()?
|
||||
};
|
||||
let breakdowns = self.breakdowns(from, to)?;
|
||||
Ok(serde_json::json!({
|
||||
"from_day": from, "to_day": to, "min_install_days": k,
|
||||
"bucket_edges_ms": BUCKET_EDGES_MS.map(|e| (f64::from(e) * 10.0).round() / 10.0),
|
||||
"totals": { "sessions": sessions, "hours": (hours * 10.0).round() / 10.0 },
|
||||
"groups": out, "crashes_by_version": crashes, "benchmarks": benchmarks,
|
||||
"groups": out, "crashes_by_version": crashes, "breakdowns": breakdowns,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Play sessions in `from..=to` per hardware class (`classes`): for each RAM, VRAM, drive,
|
||||
/// OS and GPU kind class with at least `MIN_INSTALLS` different installs, its installs,
|
||||
/// sessions, hours and mean p50 and p99 frame times. From the raw rows, so only within the
|
||||
/// retention period.
|
||||
fn breakdowns(&self, from: u32, to: u32) -> rusqlite::Result<serde_json::Value> {
|
||||
#[derive(Default)]
|
||||
struct Cell {
|
||||
installs: HashSet<Vec<u8>>,
|
||||
sessions: u64,
|
||||
seconds: u64,
|
||||
p50_sum: f64,
|
||||
p99_sum: f64,
|
||||
}
|
||||
let mut cells: [HashMap<&'static str, Cell>; 5] = Default::default();
|
||||
let mut q = self.db.prepare(
|
||||
"SELECT perf.install, perf.seconds, perf.frames, systems.os, systems.ram_gb, systems.extra
|
||||
FROM perf JOIN systems ON systems.id = perf.system WHERE perf.day BETWEEN ?1 AND ?2",
|
||||
)?;
|
||||
let mut rows = q.query([from, to])?;
|
||||
while let Some(r) = rows.next()? {
|
||||
let Some(frames) = unpack(&r.get::<_, Vec<u8>>(2)?) else {
|
||||
continue;
|
||||
};
|
||||
let extra: Extra = serde_json::from_str(&r.get::<_, String>(5)?).unwrap_or_default();
|
||||
let system = System {
|
||||
os: r.get(3)?,
|
||||
ram_gb: r.get(4)?,
|
||||
gpu_kind: extra.gpu_kind,
|
||||
vram_mb: extra.vram_mb,
|
||||
storage: extra.storage,
|
||||
..System::default()
|
||||
};
|
||||
let install: Vec<u8> = r.get(0)?;
|
||||
let seconds: u64 = r.get(1)?;
|
||||
for (dim, class) in crate::classes::of_system(&system).into_iter().enumerate() {
|
||||
let Some(class) = class else { continue };
|
||||
let c = cells[dim].entry(class).or_default();
|
||||
c.installs.insert(install.clone());
|
||||
c.sessions += 1;
|
||||
c.seconds += seconds;
|
||||
c.p50_sum += f64::from(frames.p50_ms);
|
||||
c.p99_sum += f64::from(frames.p99_ms);
|
||||
}
|
||||
}
|
||||
let mut out = serde_json::Map::new();
|
||||
for (dim, by_class) in crate::classes::DIMENSIONS.iter().zip(cells) {
|
||||
let mut list: Vec<(&str, Cell)> = by_class
|
||||
.into_iter()
|
||||
.filter(|(_, c)| c.installs.len() >= crate::summary::MIN_INSTALLS)
|
||||
.collect();
|
||||
list.sort_by(|a, b| {
|
||||
b.1.installs
|
||||
.len()
|
||||
.cmp(&a.1.installs.len())
|
||||
.then(a.0.cmp(b.0))
|
||||
});
|
||||
if list.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let avg = |sum: f64, n: u64| (sum / n as f64 * 10.0).round() / 10.0;
|
||||
out.insert(
|
||||
dim.to_string(),
|
||||
list.into_iter()
|
||||
.map(|(class, c)| {
|
||||
serde_json::json!({
|
||||
"class": class, "installs": c.installs.len(), "sessions": c.sessions,
|
||||
"hours": (c.seconds as f64 / 360.0).round() / 10.0,
|
||||
"p50_ms": avg(c.p50_sum, c.sessions), "p99_ms": avg(c.p99_sum, c.sessions),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
Ok(serde_json::Value::Object(out))
|
||||
}
|
||||
|
||||
/// Every benchmark upload received since `from_day`, with its install (to count installs, never shown)
|
||||
/// and release, for `summary`.
|
||||
pub fn benchmark_uploads(
|
||||
&self,
|
||||
from_day: u32,
|
||||
) -> rusqlite::Result<Vec<crate::summary::Upload>> {
|
||||
let mut q = self
|
||||
.db
|
||||
.prepare("SELECT install, version, body FROM reports WHERE kind = ?1 AND day >= ?2")?;
|
||||
q.query_map(params![kind_code(Kind::Benchmark), from_day], |r| {
|
||||
Ok(crate::summary::Upload {
|
||||
install: r.get(0)?,
|
||||
version: r.get(1)?,
|
||||
report: inflate(&r.get::<_, Vec<u8>>(2)?),
|
||||
})
|
||||
})?
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The day an install's newest row came in, if any (tests, and checking a deletion).
|
||||
pub fn newest_day(&self, install: &[u8]) -> rusqlite::Result<Option<u32>> {
|
||||
self.db
|
||||
@@ -392,15 +478,74 @@ impl Store {
|
||||
}
|
||||
}
|
||||
|
||||
/// The hardware fields after the first nine, as `systems.extra` keeps them.
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Extra {
|
||||
pub cores: u16,
|
||||
pub cpu_base_mhz: u32,
|
||||
pub cpu_boost_mhz: u32,
|
||||
pub gpu_vendor: String,
|
||||
pub gpu_kind: String,
|
||||
pub vram_mb: u32,
|
||||
pub storage: String,
|
||||
pub display: Option<horizon_telemetry::payload::Display>,
|
||||
pub power: String,
|
||||
pub form: String,
|
||||
}
|
||||
|
||||
impl Extra {
|
||||
fn of(s: &System) -> Self {
|
||||
Self {
|
||||
cores: s.cores,
|
||||
cpu_base_mhz: s.cpu_base_mhz,
|
||||
cpu_boost_mhz: s.cpu_boost_mhz,
|
||||
gpu_vendor: s.gpu_vendor.clone(),
|
||||
gpu_kind: s.gpu_kind.clone(),
|
||||
vram_mb: s.vram_mb,
|
||||
storage: s.storage.clone(),
|
||||
display: s.display.clone(),
|
||||
power: s.power.clone(),
|
||||
form: s.form.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Databases from before `systems.extra`: the table rebuilt with it (ids kept), once.
|
||||
fn migrate(db: &mut Connection) -> rusqlite::Result<()> {
|
||||
let has_extra = db
|
||||
.prepare("SELECT 1 FROM pragma_table_info('systems') WHERE name = 'extra'")?
|
||||
.exists([])?;
|
||||
if has_extra {
|
||||
return Ok(());
|
||||
}
|
||||
let tx = db.transaction()?;
|
||||
tx.execute_batch(
|
||||
"CREATE TABLE systems_new (
|
||||
id INTEGER PRIMARY KEY,
|
||||
os TEXT NOT NULL, os_version TEXT NOT NULL, arch TEXT NOT NULL, cpu TEXT NOT NULL,
|
||||
threads INTEGER NOT NULL, ram_gb INTEGER NOT NULL,
|
||||
gpu TEXT NOT NULL, driver TEXT NOT NULL, backend TEXT NOT NULL, extra TEXT NOT NULL DEFAULT '{}',
|
||||
UNIQUE (os, os_version, arch, cpu, threads, ram_gb, gpu, driver, backend, extra)
|
||||
);
|
||||
INSERT INTO systems_new (id, os, os_version, arch, cpu, threads, ram_gb, gpu, driver, backend)
|
||||
SELECT id, os, os_version, arch, cpu, threads, ram_gb, gpu, driver, backend FROM systems;
|
||||
DROP TABLE systems;
|
||||
ALTER TABLE systems_new RENAME TO systems;",
|
||||
)?;
|
||||
tx.commit()
|
||||
}
|
||||
|
||||
fn system_id(tx: &rusqlite::Transaction, s: &System) -> rusqlite::Result<i64> {
|
||||
let extra = serde_json::to_string(&Extra::of(s)).unwrap_or_else(|_| "{}".into());
|
||||
tx.execute(
|
||||
"INSERT OR IGNORE INTO systems (os, os_version, arch, cpu, threads, ram_gb, gpu, driver, backend)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
params![s.os, s.os_version, s.arch, s.cpu, s.threads, s.ram_gb, s.gpu, s.driver, s.backend],
|
||||
"INSERT OR IGNORE INTO systems (os, os_version, arch, cpu, threads, ram_gb, gpu, driver, backend, extra)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
params![s.os, s.os_version, s.arch, s.cpu, s.threads, s.ram_gb, s.gpu, s.driver, s.backend, extra],
|
||||
)?;
|
||||
tx.query_row(
|
||||
"SELECT id FROM systems WHERE os = ?1 AND os_version = ?2 AND arch = ?3 AND cpu = ?4
|
||||
AND threads = ?5 AND ram_gb = ?6 AND gpu = ?7 AND driver = ?8 AND backend = ?9",
|
||||
AND threads = ?5 AND ram_gb = ?6 AND gpu = ?7 AND driver = ?8 AND backend = ?9 AND extra = ?10",
|
||||
params![
|
||||
s.os,
|
||||
s.os_version,
|
||||
@@ -410,7 +555,8 @@ fn system_id(tx: &rusqlite::Transaction, s: &System) -> rusqlite::Result<i64> {
|
||||
s.ram_gb,
|
||||
s.gpu,
|
||||
s.driver,
|
||||
s.backend
|
||||
s.backend,
|
||||
extra
|
||||
],
|
||||
|r| r.get(0),
|
||||
)
|
||||
@@ -426,3 +572,65 @@ pub fn inflate(body: &[u8]) -> serde_json::Value {
|
||||
.and_then(|_| serde_json::from_slice(&json).ok())
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A database from before `systems.extra` opens, keeps its machines' ids and takes new ones.
|
||||
#[test]
|
||||
fn systems_from_before_extra_are_kept() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"horizon-telemetry-migrate-{}.sqlite",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
{
|
||||
let db = Connection::open(&path).unwrap();
|
||||
db.execute_batch(
|
||||
"CREATE TABLE systems (
|
||||
id INTEGER PRIMARY KEY,
|
||||
os TEXT NOT NULL, os_version TEXT NOT NULL, arch TEXT NOT NULL, cpu TEXT NOT NULL,
|
||||
threads INTEGER NOT NULL, ram_gb INTEGER NOT NULL,
|
||||
gpu TEXT NOT NULL, driver TEXT NOT NULL, backend TEXT NOT NULL,
|
||||
UNIQUE (os, os_version, arch, cpu, threads, ram_gb, gpu, driver, backend)
|
||||
);
|
||||
INSERT INTO systems VALUES (7, 'linux', 'Fedora 43', 'x86_64', 'Ryzen', 32, 32, 'RTX 4070', '570', 'Vulkan');",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let path_str = path.to_str().unwrap();
|
||||
let mut store = Store::open(path_str).unwrap();
|
||||
let old: (String, String) = store
|
||||
.db
|
||||
.query_row("SELECT gpu, extra FROM systems WHERE id = 7", [], |r| {
|
||||
Ok((r.get(0)?, r.get(1)?))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(old, ("RTX 4070".to_owned(), "{}".to_owned()));
|
||||
let s = System {
|
||||
os: "linux".into(),
|
||||
gpu: "RTX 4070".into(),
|
||||
vram_mb: 12288,
|
||||
gpu_kind: "discrete".into(),
|
||||
storage: "nvme".into(),
|
||||
..System::default()
|
||||
};
|
||||
let tx = store.db.transaction().unwrap();
|
||||
let id = system_id(&tx, &s).unwrap();
|
||||
assert_eq!(system_id(&tx, &s).unwrap(), id, "the same machine once");
|
||||
let extra: String = tx
|
||||
.query_row("SELECT extra FROM systems WHERE id = ?1", [id], |r| {
|
||||
r.get(0)
|
||||
})
|
||||
.unwrap();
|
||||
tx.commit().unwrap();
|
||||
let back: Extra = serde_json::from_str(&extra).unwrap();
|
||||
assert_eq!((back.vram_mb, back.storage.as_str()), (12288, "nvme"));
|
||||
drop(store);
|
||||
Store::open(path_str).unwrap(); // a second open doesn't rebuild again
|
||||
for suffix in ["", "-wal", "-shm"] {
|
||||
let _ = std::fs::remove_file(format!("{path_str}{suffix}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user