Merge origin/main into perf/linux-helpers-behind (game.rs: helpers behind on every run, plus main's live-count ping)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -45,6 +45,7 @@ jobs:
|
||||
outputs:
|
||||
release: ${{ steps.decide.outputs.release }}
|
||||
tag: ${{ steps.decide.outputs.tag }}
|
||||
version: ${{ steps.decide.outputs.version }}
|
||||
head: ${{ steps.decide.outputs.head }}
|
||||
dry_run: ${{ steps.mode.outputs.dry_run }}
|
||||
steps:
|
||||
@@ -65,6 +66,9 @@ jobs:
|
||||
run: |
|
||||
python3 tools/release_train.py decide --kind game ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json
|
||||
echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY"
|
||||
# The version the programs are built with (docs/versioning.md): the tag without its v.
|
||||
tag=$(jq -r '.tag' decision.json)
|
||||
echo "version=${tag#v}" >> "$GITHUB_OUTPUT"
|
||||
# A dry run builds whatever the decision, to test the builds.
|
||||
if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi
|
||||
|
||||
@@ -99,6 +103,9 @@ jobs:
|
||||
timeout-minutes: ${{ matrix.mac && 60 || 40 }}
|
||||
env:
|
||||
RUSTFLAGS: ${{ matrix.rustflags }}
|
||||
# The release's version, built in (horizon_core::release): --version, user agents, crash reports and
|
||||
# telemetry say it. No version-bump commits.
|
||||
HORIZON_VERSION: ${{ needs.decide.outputs.version }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
@@ -162,9 +169,13 @@ jobs:
|
||||
bin=target/release
|
||||
"$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources'
|
||||
"$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null
|
||||
"$bin/horizon-prepare${{ matrix.exe }}" --version
|
||||
"$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir'
|
||||
"$bin/horizon-server${{ matrix.exe }}" --version
|
||||
# The version is the release's.
|
||||
for binary in horizon-prepare horizon-server; do
|
||||
out=$("$bin/$binary${{ matrix.exe }}" --version | tr -d '\r')
|
||||
echo "$out"
|
||||
[[ "$out" == "$binary $HORIZON_VERSION" ]] || { echo "::error::expected $binary $HORIZON_VERSION"; exit 1; }
|
||||
done
|
||||
- name: Tools from the runner
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: bash tools/ci/runner-env.sh
|
||||
@@ -245,7 +256,7 @@ jobs:
|
||||
folder="dist/${{ matrix.server_dir }}"
|
||||
python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare"
|
||||
"$folder/horizon-engine" --help | grep -q -- '--resources'
|
||||
"$folder/horizon-server" --version
|
||||
[[ "$("$folder/horizon-server" --version)" == "horizon-server $HORIZON_VERSION" ]]
|
||||
cd dist
|
||||
rm -f "${{ matrix.server_asset }}"
|
||||
tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}"
|
||||
|
||||
@@ -42,8 +42,9 @@ log = "0.4"
|
||||
chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] }
|
||||
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
|
||||
horizon-theme = { path = "../horizon-theme" }
|
||||
# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md).
|
||||
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
|
||||
# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md); `live` is
|
||||
# the anonymous "I'm playing" ping the game sends itself (`heartbeat.rs`).
|
||||
horizon-telemetry = { path = "../horizon-telemetry", default-features = false, features = ["live"] }
|
||||
horizon-bench = { path = "../horizon-bench" }
|
||||
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
|
||||
@@ -174,7 +174,7 @@ pub fn discovery_url() -> String {
|
||||
fn agent() -> ureq::Agent {
|
||||
ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(15))
|
||||
.user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION")))
|
||||
.user_agent(&format!("Horizon/{}", horizon_core::release::VERSION))
|
||||
.build()
|
||||
}
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ impl Session {
|
||||
"initialize" => Ok(json!({
|
||||
"protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL),
|
||||
"capabilities": { "tools": {} },
|
||||
"serverInfo": { "name": "horizon-ctl", "version": env!("CARGO_PKG_VERSION") },
|
||||
"serverInfo": { "name": "horizon-ctl", "version": horizon_core::release::VERSION },
|
||||
"instructions": "Play Horizon, a Rust reimplementation of Minecraft Java Edition. Start with launch (it finds the game installed by the Horizon launcher and opens or creates a world), then read the world with state, inventory, screen, entities and find_block, and act with goto, look_at_block, break, place, interact, click_slot and click_button. Actions block until they finish and report what happened. Coordinates are block coordinates; yaw 0 faces south (+Z).",
|
||||
})),
|
||||
"ping" => Ok(json!({})),
|
||||
|
||||
@@ -105,18 +105,23 @@ impl Report {
|
||||
}
|
||||
}
|
||||
|
||||
/// The release tag (the launcher installs each build in a folder named after it) and the client's
|
||||
/// own version, or just the latter.
|
||||
/// The release this binary is (`v0.2.3`); for a release from before 0.2, its tag and the client's
|
||||
/// crate version; for a build from source, that version alone.
|
||||
pub fn version() -> String {
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
match release_tag() {
|
||||
Some(tag) => format!("{tag} (client {version})"),
|
||||
None => version.to_owned(),
|
||||
match (horizon_core::release::RELEASE, release_tag()) {
|
||||
(Some(_), Some(tag)) => tag,
|
||||
(None, Some(tag)) => format!("{tag} (client {version})"),
|
||||
(_, None) => version.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The release this binary came with: launcher installs live in a folder named after the tag.
|
||||
/// The release this binary came with: the version release.yml built in (docs/versioning.md), else
|
||||
/// the folder the launcher installed it in, named after the tag (releases from before 0.2).
|
||||
pub fn release_tag() -> Option<String> {
|
||||
if let Some(version) = horizon_core::release::RELEASE {
|
||||
return Some(format!("v{version}"));
|
||||
}
|
||||
let exe = std::env::current_exe().ok()?;
|
||||
let folder = exe.parent()?.file_name()?.to_str()?;
|
||||
(folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit()))
|
||||
@@ -517,6 +522,18 @@ pub fn debug_crash_after() -> Option<std::time::Duration> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_release_reports_its_built_in_version() {
|
||||
// release.yml builds with HORIZON_VERSION (docs/versioning.md): `v0.2.3`, wherever it is installed.
|
||||
match horizon_core::release::RELEASE {
|
||||
Some(version) => {
|
||||
assert_eq!(release_tag(), Some(format!("v{version}")));
|
||||
assert_eq!(super::version(), format!("v{version}"));
|
||||
}
|
||||
None => assert!(release_tag().is_none() || super::version().contains("(client ")),
|
||||
}
|
||||
}
|
||||
|
||||
fn report() -> Report {
|
||||
Report {
|
||||
time: chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap(),
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Horizon Extras' dynamic lights (docs/extras.md): a torch, lantern or other light source held by
|
||||
//! a player or mob, dropped as an item, or an entity on fire lights the blocks and entities
|
||||
//! around it. Not in vanilla; off by default.
|
||||
//!
|
||||
//! Client-only and at render time: the light engine, chunk meshes and saves never see it. Each
|
||||
//! frame the game picks the [`MAX`] sources nearest the camera; terrain.wgsl and entity.wgsl
|
||||
//! raise a vertex's block light to `level - distance` (one level per block, as block light falls
|
||||
//! off) when that is brighter. Off, the list is empty and the shaders skip the loop.
|
||||
use crate::blocks::BlockFacts;
|
||||
use glam::DVec3;
|
||||
use horizon_world::registry::BlockRegistry;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Lights the shaders read: `Globals.dynamic_lights` in gfx.rs, terrain.wgsl and entity.wgsl.
|
||||
pub const MAX: usize = 16;
|
||||
/// What an entity on fire gives off, as a lit campfire or fire block does.
|
||||
pub const BURNING: u8 = 15;
|
||||
/// Sources farther than this from the camera light nothing it can see well.
|
||||
const REACH: f64 = 96.0;
|
||||
|
||||
/// How brightly each item glows when held or dropped.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Luminance(HashMap<String, u8>);
|
||||
|
||||
impl Luminance {
|
||||
/// A block item glows like its block's default state (`getLightEmission`): torches 14,
|
||||
/// lanterns and glowstone 15, a lit redstone torch 7; a furnace's item, unlit, not at all.
|
||||
pub fn new(facts: &BlockFacts, registry: &BlockRegistry) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
for (id, state) in facts.states.iter().enumerate() {
|
||||
if state.emission == 0 || *state.item != *state.name {
|
||||
continue;
|
||||
}
|
||||
if registry.default_state(&state.name).map(|d| d.0 as usize) == Some(id) {
|
||||
map.insert(state.item.to_string(), state.emission);
|
||||
}
|
||||
}
|
||||
// A bucket of lava glows as lava does.
|
||||
map.insert("minecraft:lava_bucket".into(), 15);
|
||||
Self(map)
|
||||
}
|
||||
|
||||
pub fn of(&self, item: &str) -> u8 {
|
||||
self.0.get(item).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn from_pairs(pairs: &[(&str, u8)]) -> Self {
|
||||
Self(pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// One light this frame: where it is (world space) and its level, 1 to 15.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Source {
|
||||
pub at: DVec3,
|
||||
pub level: u8,
|
||||
}
|
||||
|
||||
/// The [`MAX`] sources nearest `camera` within reach, as the shaders read them: camera-relative
|
||||
/// position and level. Overwrites `out`.
|
||||
pub fn select(sources: &[Source], camera: DVec3, out: &mut Vec<[f32; 4]>) {
|
||||
out.clear();
|
||||
let key = |s: &Source| s.at.distance_squared(camera);
|
||||
let mut near: Vec<&Source> = sources
|
||||
.iter()
|
||||
.filter(|s| s.level > 0 && key(s) <= REACH * REACH)
|
||||
.collect();
|
||||
near.sort_by(|a, b| key(a).total_cmp(&key(b)));
|
||||
out.extend(near.into_iter().take(MAX).map(|s| {
|
||||
let p = (s.at - camera).as_vec3();
|
||||
[p.x, p.y, p.z, f32::from(s.level.min(15))]
|
||||
}));
|
||||
}
|
||||
|
||||
/// The block light a vertex at `pos` (camera-relative) gets from `lights`, 0 to 15: the WGSL
|
||||
/// `dynamic_block_light` in Rust, for tests.
|
||||
pub fn level_at(pos: [f32; 3], lights: &[[f32; 4]]) -> f32 {
|
||||
lights.iter().fold(0.0f32, |level, l| {
|
||||
let d =
|
||||
((pos[0] - l[0]).powi(2) + (pos[1] - l[1]).powi(2) + (pos[2] - l[2]).powi(2)).sqrt();
|
||||
level.max(l[3] - d)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nearest_sources_win() {
|
||||
let camera = DVec3::new(100.0, 64.0, 100.0);
|
||||
let mut sources: Vec<Source> = (0..40)
|
||||
.map(|i| Source {
|
||||
at: camera + DVec3::new(f64::from(i), 0.0, 0.0),
|
||||
level: 14,
|
||||
})
|
||||
.collect();
|
||||
sources.push(Source {
|
||||
at: camera + DVec3::new(0.5, 0.0, 0.0),
|
||||
level: 0,
|
||||
});
|
||||
sources.push(Source {
|
||||
at: camera + DVec3::new(0.0, 0.0, 200.0),
|
||||
level: 15,
|
||||
});
|
||||
let mut out = Vec::new();
|
||||
select(&sources, camera, &mut out);
|
||||
assert_eq!(out.len(), MAX);
|
||||
assert_eq!(out[0], [0.0, 0.0, 0.0, 14.0]);
|
||||
assert_eq!(out[MAX - 1][0], (MAX - 1) as f32);
|
||||
select(&[], camera, &mut out);
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light_falls_off_a_level_per_block() {
|
||||
let torch = [[0.0, 0.0, 0.0, 14.0]];
|
||||
assert_eq!(level_at([0.0, 0.0, 0.0], &torch), 14.0);
|
||||
assert_eq!(level_at([3.0, 4.0, 0.0], &torch), 9.0);
|
||||
assert_eq!(level_at([20.0, 0.0, 0.0], &torch), 0.0);
|
||||
let two = [[0.0, 0.0, 0.0, 14.0], [10.0, 0.0, 0.0, 15.0]];
|
||||
assert_eq!(level_at([8.0, 0.0, 0.0], &two), 13.0);
|
||||
assert_eq!(level_at([0.0; 3], &[]), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_luminance() {
|
||||
let l = Luminance::from_pairs(&[("minecraft:torch", 14)]);
|
||||
assert_eq!(l.of("minecraft:torch"), 14);
|
||||
assert_eq!(l.of("minecraft:stone"), 0);
|
||||
}
|
||||
}
|
||||
@@ -14,11 +14,13 @@ struct Globals {
|
||||
// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
|
||||
end_portal_sprites: array<vec4<f32>, 2>,
|
||||
// x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000)
|
||||
// y: Nether cardinal lighting.
|
||||
// y: Nether cardinal lighting, z: how many dynamic_lights are set.
|
||||
time: vec4<f32>,
|
||||
crumbling_sprite: vec4<f32>,
|
||||
// Selection outline parameters (read by terrain.wgsl).
|
||||
outline_params: vec4<f32>,
|
||||
// Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs).
|
||||
dynamic_lights: array<vec4<f32>, 16>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> globals: Globals;
|
||||
@group(0) @binding(1) var atlas: texture_2d<f32>;
|
||||
@@ -58,13 +60,25 @@ fn overlay_texel(overlay: u32) -> vec4<f32> {
|
||||
if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); }
|
||||
return vec4(1.0);
|
||||
}
|
||||
// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units
|
||||
// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one
|
||||
// level less per block. time.z of them are set: none when the extra is off, so no loop runs.
|
||||
fn dynamic_block_light(pos: vec3<f32>) -> f32 {
|
||||
let count = min(u32(globals.time.z), 16u);
|
||||
var level = 0.0;
|
||||
for (var i = 0u; i < count; i++) {
|
||||
let l = globals.dynamic_lights[i];
|
||||
level = max(level, l.w - distance(pos, l.xyz));
|
||||
}
|
||||
return level * 16.0;
|
||||
}
|
||||
fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
|
||||
overlay: u32, color: vec4<f32>, light: vec4<u32>, normal: vec4<f32>) -> Out {
|
||||
var out: Out;
|
||||
out.clip = globals.view_proj * vec4(position, 1.0);
|
||||
out.proj = vec4(out.clip.xy * 0.5 + out.clip.w * 0.5, out.clip.zw);
|
||||
out.uv = uv;
|
||||
let l = vec2(f32(light.y), f32(light.x));
|
||||
let l = vec2(max(f32(light.y), dynamic_block_light(position)), f32(light.x));
|
||||
let lm = textureSampleLevel(lightmap, lightmap_sampler,
|
||||
clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0);
|
||||
// Celestial bodies, clouds, beacon beams, End portals and breaking cracks are unlit.
|
||||
|
||||
@@ -69,6 +69,8 @@ impl Corner {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Extras {
|
||||
pub fullbright: bool,
|
||||
/// Held, dropped and burning light sources light their surroundings (`dynamic_light`).
|
||||
pub dynamic_lights: bool,
|
||||
pub zoom: bool,
|
||||
/// A vanilla key name (`key.keyboard.z`).
|
||||
pub zoom_key: String,
|
||||
@@ -110,6 +112,7 @@ impl Default for Extras {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fullbright: false,
|
||||
dynamic_lights: false,
|
||||
zoom: false,
|
||||
zoom_key: "key.keyboard.z".into(),
|
||||
zoom_level: 4,
|
||||
@@ -158,6 +161,7 @@ impl Extras {
|
||||
};
|
||||
match key.trim() {
|
||||
"fullbright" => e.fullbright = flag(e.fullbright),
|
||||
"dynamicLights" => e.dynamic_lights = flag(e.dynamic_lights),
|
||||
"zoom" => e.zoom = flag(e.zoom),
|
||||
"zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(),
|
||||
"zoomLevel" => {
|
||||
@@ -201,8 +205,9 @@ impl Extras {
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"fullbright:{}\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",
|
||||
bool_text(self.fullbright),
|
||||
bool_text(self.dynamic_lights),
|
||||
bool_text(self.zoom),
|
||||
self.zoom_key,
|
||||
self.zoom_level,
|
||||
@@ -423,6 +428,7 @@ impl Cps {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Item {
|
||||
Fullbright,
|
||||
DynamicLights,
|
||||
Zoom,
|
||||
ZoomKey,
|
||||
ZoomLevel,
|
||||
@@ -452,6 +458,7 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
|
||||
vec![
|
||||
Err("Lighting"),
|
||||
Ok(Fullbright),
|
||||
Ok(DynamicLights),
|
||||
Err("Zoom"),
|
||||
Ok(Zoom),
|
||||
Ok(ZoomKey),
|
||||
@@ -501,6 +508,7 @@ impl Item {
|
||||
pub fn caption(self) -> &'static str {
|
||||
match self {
|
||||
Item::Fullbright => "Fullbright",
|
||||
Item::DynamicLights => "Dynamic lights",
|
||||
Item::Zoom => "Zoom",
|
||||
Item::ZoomKey => "Zoom key",
|
||||
Item::ZoomLevel => "Starting zoom",
|
||||
@@ -533,7 +541,8 @@ impl Item {
|
||||
KeystrokesCorner | KeystrokesCps => Keystrokes,
|
||||
MouseTweaksWheel => MouseTweaks,
|
||||
SortKey => Sort,
|
||||
Fullbright | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort | AutoReconnect => {
|
||||
Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort
|
||||
| AutoReconnect => {
|
||||
return None;
|
||||
}
|
||||
})
|
||||
@@ -542,6 +551,9 @@ impl Item {
|
||||
pub fn description(self) -> &'static str {
|
||||
match self {
|
||||
Item::Fullbright => "Show blocks and entities at full light, even in dark areas.",
|
||||
Item::DynamicLights => {
|
||||
"Torches and other light sources held, dropped or on fire light the blocks around them."
|
||||
}
|
||||
Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.",
|
||||
Item::ZoomKey => "Click, then press a key. Escape unbinds it.",
|
||||
Item::ZoomLevel => "The zoom the key starts at.",
|
||||
@@ -581,7 +593,7 @@ impl Item {
|
||||
use crate::graphics_style::Cost;
|
||||
match self {
|
||||
Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None),
|
||||
Item::Minimap => Some(Cost::Low),
|
||||
Item::Minimap | Item::DynamicLights => Some(Cost::Low),
|
||||
Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None),
|
||||
_ => None,
|
||||
}
|
||||
@@ -590,6 +602,7 @@ impl Item {
|
||||
pub fn switch(self, e: &Extras) -> Option<bool> {
|
||||
Some(match self {
|
||||
Item::Fullbright => e.fullbright,
|
||||
Item::DynamicLights => e.dynamic_lights,
|
||||
Item::Zoom => e.zoom,
|
||||
Item::ZoomSmooth => e.zoom_smooth,
|
||||
Item::ZoomSensitivity => e.zoom_sensitivity,
|
||||
@@ -632,6 +645,7 @@ impl Item {
|
||||
pub fn cycle(self, e: &mut Extras, back: bool) {
|
||||
match self {
|
||||
Item::Fullbright => e.fullbright = !e.fullbright,
|
||||
Item::DynamicLights => e.dynamic_lights = !e.dynamic_lights,
|
||||
Item::Zoom => e.zoom = !e.zoom,
|
||||
Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth,
|
||||
Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity,
|
||||
@@ -677,7 +691,7 @@ mod tests {
|
||||
#[test]
|
||||
fn everything_is_off_by_default_and_round_trips() {
|
||||
let d = Extras::default();
|
||||
assert!(!d.fullbright);
|
||||
assert!(!d.fullbright && !d.dynamic_lights);
|
||||
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect);
|
||||
assert!(!d.mouse_tweaks && !d.sort);
|
||||
assert_eq!(Extras::parse(""), d);
|
||||
@@ -685,6 +699,9 @@ mod tests {
|
||||
let mut e = d.clone();
|
||||
Item::Fullbright.cycle(&mut e, false);
|
||||
assert_eq!(Item::Fullbright.switch(&e), Some(true));
|
||||
Item::DynamicLights.cycle(&mut e, false);
|
||||
assert_eq!(Item::DynamicLights.switch(&e), Some(true));
|
||||
assert_eq!(Extras::parse(&e.serialize()), e);
|
||||
e.zoom = true;
|
||||
e.zoom_key = "key.keyboard.c".into();
|
||||
e.zoom_level = 6;
|
||||
|
||||
@@ -21,6 +21,8 @@ pub enum ItemPose {
|
||||
Trident {
|
||||
ticks_used: f32,
|
||||
},
|
||||
/// Riptide's spin (`isAutoSpinAttack`): the item held up like a fork.
|
||||
SpinAttack,
|
||||
Bow {
|
||||
ticks_used: f32,
|
||||
},
|
||||
@@ -67,6 +69,12 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -
|
||||
if matches!(pose, ItemPose::Using) {
|
||||
return m;
|
||||
}
|
||||
if matches!(pose, ItemPose::SpinAttack) {
|
||||
return m
|
||||
* Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3))
|
||||
* Mat4::from_rotation_y((invert * 65.0f32).to_radians())
|
||||
* Mat4::from_rotation_z((invert * -85.0f32).to_radians());
|
||||
}
|
||||
let charging = match pose {
|
||||
ItemPose::Bow { ticks_used } => {
|
||||
let power = ticks_used / 20.0;
|
||||
|
||||
@@ -38,6 +38,7 @@ mod deflect;
|
||||
mod dispense_fixture;
|
||||
mod dispenser;
|
||||
mod dragon;
|
||||
mod dynamic_lights;
|
||||
mod enchant_effects;
|
||||
mod end;
|
||||
mod entity_culling;
|
||||
@@ -269,8 +270,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).
|
||||
/// 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,
|
||||
@@ -325,7 +327,10 @@ impl Options {
|
||||
dedicated: None,
|
||||
benchmark: None,
|
||||
dev_mods: Vec::new(),
|
||||
server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1"),
|
||||
// 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").map_or(true, |v| v != "0")
|
||||
&& std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(),
|
||||
integrated: false,
|
||||
};
|
||||
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
|
||||
@@ -334,7 +339,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\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);
|
||||
@@ -349,6 +354,7 @@ impl Options {
|
||||
"--offscreen" => o.offscreen = true,
|
||||
"--control" => o.control = Some(horizon_client::control::default_path()),
|
||||
"--server-thread" => o.server_thread = true,
|
||||
"--no-server-thread" => o.server_thread = false,
|
||||
_ => {
|
||||
let value = args
|
||||
.next()
|
||||
@@ -896,6 +902,8 @@ struct WorldRest {
|
||||
behaviours: Behaviours,
|
||||
player_arm: Option<horizon_client::mobs::Part>,
|
||||
player_type: Option<Arc<horizon_client::mobs::MobType>>,
|
||||
/// `SpinAttackEffectModel` (Riptide's spinning boxes).
|
||||
spin_attack: Option<horizon_client::mobs::Part>,
|
||||
stations: horizon_client::stations::StationData,
|
||||
}
|
||||
|
||||
@@ -971,6 +979,9 @@ impl Resources {
|
||||
fn player_type(&self) -> &Option<Arc<horizon_client::mobs::MobType>> {
|
||||
&self.rest().player_type
|
||||
}
|
||||
fn spin_attack(&self) -> &Option<horizon_client::mobs::Part> {
|
||||
&self.rest().spin_attack
|
||||
}
|
||||
fn stations(&self) -> &horizon_client::stations::StationData {
|
||||
&self.rest().stations
|
||||
}
|
||||
@@ -1179,6 +1190,10 @@ struct Game<'a> {
|
||||
renderer: Option<Renderer>,
|
||||
/// CPU geometry storage retained across frames, including empty/title frames.
|
||||
entity_vertices: Vec<Vertex>,
|
||||
/// Horizon Extras' dynamic lights this frame (`dynamic_lights.rs`), and how brightly each
|
||||
/// item glows (built the first time the extra is on).
|
||||
dynamic_lights: Vec<[f32; 4]>,
|
||||
luminance: Option<horizon_client::dynamic_light::Luminance>,
|
||||
/// Name tags drawn over everything (`RenderPipelines.TEXT_SEE_THROUGH`).
|
||||
see_through_vertices: Vec<Vertex>,
|
||||
started: Instant,
|
||||
@@ -3907,6 +3922,7 @@ impl Game<'_> {
|
||||
}
|
||||
let riding = self.riding.is_some();
|
||||
let ghast_collisions = self.happy_ghast_player_collisions();
|
||||
let spin_targets = self.spin_targets();
|
||||
let Some(player) = self.player.as_mut() else {
|
||||
// A dedicated server has no local player: the world still runs.
|
||||
if self.options.dedicated.is_some() {
|
||||
@@ -3984,6 +4000,7 @@ impl Game<'_> {
|
||||
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)));
|
||||
// The dimension's FAST_LAVA: the Nether's lava pushes harder.
|
||||
player.fluids.fast_lava = self.dim == Dim::Nether;
|
||||
player.spin_targets = spin_targets;
|
||||
let grounded = player.ground.on_ground;
|
||||
let before = (
|
||||
grounded,
|
||||
@@ -4006,6 +4023,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
let events = std::mem::take(&mut player.events);
|
||||
let spin_hit = player.spin_hit.take();
|
||||
let glider_wear = std::mem::take(&mut player.glider_wear);
|
||||
if glider_wear > 0
|
||||
&& !self.creative
|
||||
@@ -4024,6 +4042,7 @@ impl Game<'_> {
|
||||
self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5;
|
||||
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
|
||||
self.tick_avatar(before, riding);
|
||||
self.end_spin_attack(spin_hit);
|
||||
self.record_combat(&events);
|
||||
for event in events {
|
||||
match event {
|
||||
@@ -6751,7 +6770,13 @@ impl Game<'_> {
|
||||
/// enchantments.
|
||||
pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) {
|
||||
let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage);
|
||||
let damage = hand_damage + self.effect_attack_bonus();
|
||||
// Riptide's spin replaces the attack damage attribute.
|
||||
let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg);
|
||||
let damage = if spin > 0.0 {
|
||||
spin
|
||||
} else {
|
||||
hand_damage + self.effect_attack_bonus()
|
||||
};
|
||||
let scale = self.attack_strength_scale();
|
||||
let mut amount = damage * (0.2 + scale * scale * 0.8);
|
||||
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
|
||||
@@ -6879,6 +6904,14 @@ impl Game<'_> {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
self.attack_mob(index);
|
||||
// Minecraft.startAttack swings after the attack.
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// `Player.attack` on a mob: the damage, knockback, sweep, particles and
|
||||
/// sounds.
|
||||
pub(super) fn attack_mob(&mut self, index: usize) {
|
||||
let target_kind = self.mobs[index].kind.id.clone();
|
||||
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
|
||||
let (amount, scale, crit) = self.melee_damage(&target_kind);
|
||||
@@ -6896,7 +6929,6 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0);
|
||||
}
|
||||
self.swing_arm();
|
||||
// LivingEntity.setLastHurtMob (tamed wolves join in).
|
||||
self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time));
|
||||
let old_health = self.mobs[index].health;
|
||||
@@ -6989,7 +7021,6 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step.
|
||||
/// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the
|
||||
@@ -8489,6 +8520,10 @@ impl Game<'_> {
|
||||
}
|
||||
let shown = self.hands_to_render();
|
||||
let used_hand = self.used_hand();
|
||||
let spinning = self
|
||||
.player
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.auto_spin_attack_ticks > 0);
|
||||
for (i, (hand, item)) in Hand::BOTH
|
||||
.into_iter()
|
||||
.zip(self.visible_hand_items())
|
||||
@@ -8608,6 +8643,7 @@ impl Game<'_> {
|
||||
ItemPose::Using
|
||||
}
|
||||
}
|
||||
_ if spinning => ItemPose::SpinAttack,
|
||||
_ => ItemPose::Swing,
|
||||
};
|
||||
let m = to_world
|
||||
@@ -9660,6 +9696,11 @@ impl Game<'_> {
|
||||
.then(|| self.border_draw(camera.to_array(), alpha as f32))
|
||||
.flatten();
|
||||
let see_through = std::mem::take(&mut self.see_through_vertices);
|
||||
if title {
|
||||
self.dynamic_lights.clear();
|
||||
} else {
|
||||
self.gather_dynamic_lights(camera, alpha);
|
||||
}
|
||||
let frame = Frame {
|
||||
shader: self.shader_inputs(camera, alpha as f32),
|
||||
nether_lighting: self.dim == Dim::Nether,
|
||||
@@ -9717,6 +9758,7 @@ impl Game<'_> {
|
||||
color: sky.cloud_color,
|
||||
}),
|
||||
entities: &entities,
|
||||
dynamic_lights: &self.dynamic_lights,
|
||||
additive: &additive,
|
||||
see_through: &see_through,
|
||||
celestial: if self.settings.horizon.sky || title {
|
||||
@@ -10933,6 +10975,10 @@ impl ApplicationHandler for Game<'_> {
|
||||
WindowEvent::RedrawRequested => {
|
||||
self.observe_fullscreen();
|
||||
let now = Instant::now();
|
||||
let frame_cpu = self
|
||||
.options
|
||||
.spikes
|
||||
.and_then(|_| horizon_client::spans::thread_cpu());
|
||||
let elapsed = now.duration_since(self.previous);
|
||||
self.frame_ticks = elapsed.as_secs_f32() * 20.0;
|
||||
self.previous = now;
|
||||
@@ -10962,6 +11008,8 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
let updated = Instant::now();
|
||||
self.track_toggle_screens();
|
||||
// For the "I'm playing" ping: an atomic, sent on when it changes.
|
||||
horizon_client::heartbeat::set_lan(self.is_published());
|
||||
let steps = self.clock.advance(elapsed);
|
||||
for _ in 0..steps {
|
||||
let started = Instant::now();
|
||||
@@ -10999,15 +11047,16 @@ impl ApplicationHandler for Game<'_> {
|
||||
let cpu = now.elapsed().saturating_sub(r.last_wait).as_secs_f32() * 1000.0;
|
||||
let spans = horizon_client::spans::take();
|
||||
if cpu > threshold {
|
||||
let list: Vec<String> = spans
|
||||
.iter()
|
||||
.filter(|(_, ms)| *ms >= 0.5)
|
||||
.map(|(n, ms)| format!("{n} {ms:.1}"))
|
||||
.collect();
|
||||
// The render thread's own CPU time in the frame:
|
||||
// far below the wall time, the frame waited.
|
||||
let worked = horizon_client::spans::thread_cpu()
|
||||
.zip(frame_cpu)
|
||||
.map_or_else(String::new, |(end, start)| {
|
||||
format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0)
|
||||
});
|
||||
log::info!(
|
||||
"Horizon: slow frame {cpu:.1} ms ({} ticks): {}",
|
||||
steps,
|
||||
list.join(", ")
|
||||
"Horizon: slow frame {cpu:.1} ms{worked} ({steps} ticks): {}",
|
||||
horizon_client::spans::describe(&spans)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11307,6 +11356,8 @@ impl<'a> Game<'a> {
|
||||
window: None,
|
||||
renderer: None,
|
||||
entity_vertices: Vec::new(),
|
||||
dynamic_lights: Vec::new(),
|
||||
luminance: None,
|
||||
see_through_vertices: Vec::new(),
|
||||
health_hud: hud_layout::HealthHud::default(),
|
||||
started: now,
|
||||
@@ -12052,6 +12103,7 @@ fn load_world_rest(
|
||||
player_type: perspective::player_type(root),
|
||||
player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main")
|
||||
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
|
||||
spin_attack: horizon_client::mobs::load_model(root, "minecraft:spin_attack#main"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -12180,6 +12232,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
|
||||
hud,
|
||||
nether_lighting: false,
|
||||
entities: &[],
|
||||
dynamic_lights: &[],
|
||||
clouds: None,
|
||||
additive: &[],
|
||||
see_through: &[],
|
||||
@@ -12764,6 +12817,16 @@ pub fn run() -> Result<()> {
|
||||
// 10 to 200 ms to get one back.
|
||||
horizon_threads::favour_current();
|
||||
}
|
||||
// Someone is playing: the anonymous ping behind the launcher's "N playing now". Not for a
|
||||
// server, a benchmark or a run that quits by itself.
|
||||
if options.dedicated.is_none()
|
||||
&& options.benchmark.is_none()
|
||||
&& !options.offscreen
|
||||
&& options.frames.is_none()
|
||||
&& options.world_frames.is_none()
|
||||
{
|
||||
horizon_client::heartbeat::start();
|
||||
}
|
||||
let started = Instant::now();
|
||||
horizon_client::spans::enable(options.spikes.is_some());
|
||||
let vanilla_root = options.resources.clone();
|
||||
|
||||
@@ -1840,11 +1840,21 @@ impl Game<'_> {
|
||||
if self.ticks < *report_tick && !timed_out {
|
||||
return None;
|
||||
}
|
||||
let after = pos.map(|p| self.block_json(p));
|
||||
let changed = match (*pos, *before) {
|
||||
(Some(p), Some(b)) => self.world.block(p[0], p[1], p[2]) != b,
|
||||
_ => false,
|
||||
};
|
||||
// A client of a server (single player's server thread, a LAN
|
||||
// guest) sees the block once the server's answer comes.
|
||||
if *place
|
||||
&& !changed
|
||||
&& self.remote.is_some()
|
||||
&& self.ticks < *report_tick + 20
|
||||
&& !timed_out
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let after = pos.map(|p| self.block_json(p));
|
||||
let used = delta(inventory, &self.inventory_counts());
|
||||
let mut v = json!({
|
||||
"ok": !*place || changed,
|
||||
|
||||
@@ -879,7 +879,9 @@ impl Game<'_> {
|
||||
"tridents": self.tridents.len(),
|
||||
"rockets": self.rockets.len(),
|
||||
"fight": self.dragon_status(),
|
||||
"carts": self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::<Vec<_>>(),
|
||||
// A client of a server (single player's server thread) knows the
|
||||
// carts it was sent.
|
||||
"carts": self.remote_carts().unwrap_or_else(|| self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::<Vec<_>>()),
|
||||
"riding": self.riding,
|
||||
"using": self.using,
|
||||
"render_distance": self.streaming.radius,
|
||||
|
||||
@@ -2107,15 +2107,22 @@ impl Game<'_> {
|
||||
let from = pl.position;
|
||||
self.spawn_mob("minecraft:endermite", [from.x, from.y, from.z], false);
|
||||
}
|
||||
// To where the pearl started its last tick (oldPosition).
|
||||
let to = p.previous;
|
||||
if let Some(pl) = self.player.as_mut() {
|
||||
pl.position = at;
|
||||
pl.position = to;
|
||||
pl.velocity = Vec3::ZERO;
|
||||
pl.fall_distance = 0.0;
|
||||
pl.teleported = true;
|
||||
}
|
||||
self.previous_position = at;
|
||||
self.previous_position = to;
|
||||
self.hurt_player_by("minecraft:ender_pearl", 5.0);
|
||||
self.audio
|
||||
.play("minecraft:entity.player.teleport", Some(atp), 1.0, 1.0);
|
||||
self.audio.play(
|
||||
"minecraft:entity.player.teleport",
|
||||
Some([to.x, to.y, to.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
(ProjectileKind::SmallFireball, hit) => match hit {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Horizon Extras' dynamic lights (`horizon_client::dynamic_light`): the light sources near the
|
||||
//! camera this frame. Nothing is gathered while the extra is off.
|
||||
use super::{Game, shield};
|
||||
use glam::DVec3;
|
||||
use horizon_client::dynamic_light::{self, BURNING, Luminance, Source};
|
||||
|
||||
impl Game<'_> {
|
||||
/// Fills `dynamic_lights` for the frame: the player's and mobs' held items and fire, and
|
||||
/// glowing dropped items, the nearest [`dynamic_light::MAX`] of them.
|
||||
pub(super) fn gather_dynamic_lights(&mut self, camera: DVec3, alpha: f64) {
|
||||
let mut out = std::mem::take(&mut self.dynamic_lights);
|
||||
out.clear();
|
||||
if !self.settings.extras.dynamic_lights {
|
||||
self.dynamic_lights = out;
|
||||
return;
|
||||
}
|
||||
if self.luminance.is_none() {
|
||||
self.luminance = Some(Luminance::new(self.res.facts(), self.pack.assets.registry));
|
||||
}
|
||||
let lum = self.luminance.as_ref().expect("built above");
|
||||
let held = |item: Option<&str>| item.map_or(0, |i| lum.of(i));
|
||||
let mut sources = Vec::new();
|
||||
if let Some(p) = &self.player
|
||||
&& !p.spectator
|
||||
{
|
||||
let feet = self
|
||||
.previous_position
|
||||
.lerp(p.position, self.clock.camera_fraction());
|
||||
let level = held(self.stack_in(self.selected).map(|s| &*s.item))
|
||||
.max(held(self.stack_in(shield::OFFHAND_SLOT).map(|s| &*s.item)))
|
||||
.max(if p.fire_ticks > 0 { BURNING } else { 0 });
|
||||
// About where the hands are.
|
||||
sources.push(Source {
|
||||
at: DVec3::new(feet.x, feet.y + 1.2, feet.z),
|
||||
level,
|
||||
});
|
||||
}
|
||||
for m in self.mobs.iter().filter(|m| !m.removed) {
|
||||
let level = held(m.extra.main_hand.as_deref())
|
||||
.max(held(m.extra.off_hand.as_deref()))
|
||||
.max(if m.fire_ticks > 0 { BURNING } else { 0 });
|
||||
if level == 0 {
|
||||
continue;
|
||||
}
|
||||
let at = m.previous.lerp(m.position, alpha);
|
||||
sources.push(Source {
|
||||
at: DVec3::new(at.x, at.y + f64::from(m.height()) * 0.6, at.z),
|
||||
level,
|
||||
});
|
||||
}
|
||||
for item in &self.dropped {
|
||||
let level = lum
|
||||
.of(&item.stack.item)
|
||||
.max(if item.fire_ticks > 0 { BURNING } else { 0 });
|
||||
if level == 0 {
|
||||
continue;
|
||||
}
|
||||
let at = item.previous.lerp(item.position, alpha);
|
||||
sources.push(Source {
|
||||
at: DVec3::new(at.x, at.y + 0.25, at.z),
|
||||
level,
|
||||
});
|
||||
}
|
||||
dynamic_light::select(&sources, camera, &mut out);
|
||||
self.dynamic_lights = out;
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,9 @@
|
||||
//! the world's options) with [`Integrated::call`], as vanilla's client calls
|
||||
//! into its `IntegratedServer`.
|
||||
//!
|
||||
//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the
|
||||
//! player joins as a network player, and the server side of a network player
|
||||
//! does not do everything single player does yet.
|
||||
//! 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},
|
||||
|
||||
@@ -10,7 +10,7 @@ use horizon_client::{
|
||||
self, Lan, MAX_PLAYERS, NetConfig,
|
||||
chunks::ChunkEncoder,
|
||||
data::SyncData,
|
||||
entity::EntityState,
|
||||
entity::{EntityState, States},
|
||||
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
|
||||
playerdata,
|
||||
},
|
||||
@@ -69,6 +69,9 @@ pub(super) struct LanHost {
|
||||
/// Guests' commands waiting for the hub to be back in `self.lan`, where
|
||||
/// a command can reach every player (game/lan_actions.rs).
|
||||
pub commands: Vec<super::lan_actions::GuestCommand>,
|
||||
/// The entities the guests track, described again every tick
|
||||
/// (`lan_entities`) over last tick's states.
|
||||
states: lan::entity::States,
|
||||
}
|
||||
|
||||
/// The player who owns an integrated server's world: a guest whose state is
|
||||
@@ -136,8 +139,7 @@ fn baby_index(kind: &str) -> Option<u8> {
|
||||
/// A mob's synched data as ServerEntity sends it (only the values that differ
|
||||
/// from the defaults the client constructs), with vanilla's entry indices:
|
||||
/// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses.
|
||||
fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
|
||||
let mut meta = Vec::new();
|
||||
fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
|
||||
let kind = m.kind.id.as_str();
|
||||
if m.fire_ticks > 0 {
|
||||
meta.push((0, serializer::BYTE, Value::Byte(1)));
|
||||
@@ -280,14 +282,16 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
meta
|
||||
}
|
||||
|
||||
/// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand,
|
||||
/// off hand, feet, legs, chest, head, body, saddle).
|
||||
fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option<horizon_protocol::item::Stack>)> {
|
||||
fn mob_equipment(
|
||||
m: &Mob,
|
||||
hub: &mut Hub,
|
||||
out: &mut Vec<(u8, Option<horizon_protocol::item::Stack>)>,
|
||||
) {
|
||||
let e = &m.extra;
|
||||
let mut out = Vec::new();
|
||||
let slots = [
|
||||
(0u8, &e.main_hand),
|
||||
(1, &e.off_hand),
|
||||
@@ -316,7 +320,6 @@ fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option<horizon_protocol::it
|
||||
});
|
||||
out.push((7, hub.stack(&Some(stack))));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub const HELP: &[&str] = &[
|
||||
@@ -537,6 +540,7 @@ impl Game<'_> {
|
||||
waypoints: Default::default(),
|
||||
waypoint_dead: Default::default(),
|
||||
commands: Vec::new(),
|
||||
states: Default::default(),
|
||||
});
|
||||
self.audio.capture = Some(Vec::new());
|
||||
Ok(())
|
||||
@@ -740,77 +744,44 @@ impl Game<'_> {
|
||||
equipment,
|
||||
health: p.health.health(),
|
||||
attributes: horizon_client::lan::attributes::syncable(&p.attributes),
|
||||
living_flags: living_flags(self.using),
|
||||
// Bit 4: Riptide's spin (LivingEntity.isAutoSpinAttack).
|
||||
living_flags: living_flags(self.using)
|
||||
| if p.auto_spin_attack_ticks > 0 { 4 } else { 0 },
|
||||
bed: self.sleeping,
|
||||
})
|
||||
}
|
||||
|
||||
/// The entities guests track: mobs, items and the rest (game/lan_entities.rs).
|
||||
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub) -> Vec<EntityState> {
|
||||
let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len());
|
||||
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub, out: &mut States) {
|
||||
out.clear();
|
||||
for m in self.mobs.iter().filter(|m| !m.removed) {
|
||||
let kind = m.kind.id.as_str();
|
||||
let meta = mob_meta(m, hub);
|
||||
let equipment = mob_equipment(m, hub);
|
||||
let attributes = self.mob_attributes(m);
|
||||
let (yaw, pitch) = (m.yaw, m.head_pitch);
|
||||
out.push(EntityState {
|
||||
id: m.id as i32,
|
||||
uuid: entity_uuid(m.id),
|
||||
kind: kind.to_owned(),
|
||||
position: [m.position.x, m.position.y, m.position.z],
|
||||
yaw,
|
||||
pitch,
|
||||
head_yaw: m.head_yaw,
|
||||
on_ground: m.on_ground,
|
||||
velocity: [m.velocity.x, m.velocity.y, m.velocity.z],
|
||||
data: 0,
|
||||
meta,
|
||||
equipment,
|
||||
attributes,
|
||||
precise: false,
|
||||
});
|
||||
let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str());
|
||||
e.position = [m.position.x, m.position.y, m.position.z];
|
||||
(e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw);
|
||||
e.on_ground = m.on_ground;
|
||||
e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z];
|
||||
mob_meta(m, hub, &mut e.meta);
|
||||
mob_equipment(m, hub, &mut e.equipment);
|
||||
self.mob_attributes(m, &mut e.attributes);
|
||||
}
|
||||
for d in &self.dropped {
|
||||
let stack = hub.stack(&Some(d.stack.clone()));
|
||||
out.push(EntityState {
|
||||
id: d.id as i32,
|
||||
uuid: entity_uuid(d.id),
|
||||
kind: "minecraft:item".to_owned(),
|
||||
position: [d.position.x, d.position.y, d.position.z],
|
||||
yaw: 0.0,
|
||||
pitch: 0.0,
|
||||
head_yaw: 0.0,
|
||||
on_ground: d.on_ground,
|
||||
velocity: [d.velocity.x, d.velocity.y, d.velocity.z],
|
||||
data: 0,
|
||||
meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))],
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
});
|
||||
let e = out.add(d.id as i32, entity_uuid(d.id), "minecraft:item");
|
||||
e.position = [d.position.x, d.position.y, d.position.z];
|
||||
e.on_ground = d.on_ground;
|
||||
e.velocity = [d.velocity.x, d.velocity.y, d.velocity.z];
|
||||
e.meta.push((8, serializer::ITEM_STACK, Value::Item(stack)));
|
||||
}
|
||||
for o in &self.orbs {
|
||||
out.push(EntityState {
|
||||
id: o.id as i32,
|
||||
uuid: entity_uuid(o.id),
|
||||
kind: "minecraft:experience_orb".to_owned(),
|
||||
position: [o.position.x, o.position.y, o.position.z],
|
||||
yaw: 0.0,
|
||||
pitch: 0.0,
|
||||
head_yaw: 0.0,
|
||||
on_ground: o.on_ground,
|
||||
velocity: [o.velocity.x, o.velocity.y, o.velocity.z],
|
||||
data: 0,
|
||||
// ExperienceOrb.DATA_VALUE.
|
||||
meta: vec![(8, serializer::INT, Value::Int(o.value as i32))],
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
});
|
||||
let e = out.add(o.id as i32, entity_uuid(o.id), "minecraft:experience_orb");
|
||||
e.position = [o.position.x, o.position.y, o.position.z];
|
||||
e.on_ground = o.on_ground;
|
||||
e.velocity = [o.velocity.x, o.velocity.y, o.velocity.z];
|
||||
// ExperienceOrb.DATA_VALUE.
|
||||
e.meta
|
||||
.push((8, serializer::INT, Value::Int(o.value as i32)));
|
||||
}
|
||||
self.lan_object_states(host_entity, hub, &mut out);
|
||||
out
|
||||
self.lan_object_states(host_entity, hub, out);
|
||||
}
|
||||
|
||||
/// Run the hub for this tick and apply what the guests did.
|
||||
@@ -832,21 +803,23 @@ impl Game<'_> {
|
||||
// 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();
|
||||
let entities = if has_guests {
|
||||
let mut states = std::mem::take(&mut host.states);
|
||||
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);
|
||||
self.lan_entities(host_entity, &mut host.hub)
|
||||
self.lan_entities(host_entity, &mut host.hub, &mut states);
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
states.clear();
|
||||
}
|
||||
let entities = states.as_slice();
|
||||
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
|
||||
let events = {
|
||||
let clock_rate = self.network_clock_rate();
|
||||
let mut ctx = TickCtx {
|
||||
world: &mut self.world,
|
||||
host: state.as_ref(),
|
||||
entities: &entities,
|
||||
entities,
|
||||
next_entity: &mut self.next_entity,
|
||||
spawn,
|
||||
difficulty: i32::from(self.ui.difficulty),
|
||||
@@ -887,7 +860,7 @@ impl Game<'_> {
|
||||
self.lan_log_event(event);
|
||||
}
|
||||
HostEvent::Joined(conn) => {
|
||||
self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn);
|
||||
self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn);
|
||||
if self.options.dedicated.is_some()
|
||||
&& let Some(g) = host.hub.guest(conn)
|
||||
{
|
||||
@@ -952,6 +925,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
host.states = states;
|
||||
}
|
||||
self.lan_flush_effects(&mut host);
|
||||
self.tick_guests(&mut host);
|
||||
@@ -1011,15 +985,15 @@ impl Game<'_> {
|
||||
g.dimension = in_place;
|
||||
}
|
||||
self.load_guest_records(host, conn);
|
||||
let theirs;
|
||||
let mut theirs = States::default();
|
||||
let entities = if elsewhere {
|
||||
if let Err(e) = self.enter_level(Some(host), level) {
|
||||
log::error!("could not open {}: {e}", level.id());
|
||||
return;
|
||||
}
|
||||
// A dedicated server has no host player.
|
||||
theirs = self.lan_entities(None, &mut host.hub);
|
||||
&theirs[..]
|
||||
self.lan_entities(None, &mut host.hub, &mut theirs);
|
||||
theirs.as_slice()
|
||||
} else {
|
||||
entities
|
||||
};
|
||||
|
||||
@@ -532,12 +532,14 @@ impl Game<'_> {
|
||||
g.health = m.health.health();
|
||||
g.food = m.health.food.food;
|
||||
g.saturation = m.health.food.saturation;
|
||||
// A teleport (commands) moves the guest.
|
||||
// A teleport (commands, a pearl) moves the guest; a pearl's is
|
||||
// sent even to where they stand (ServerPlayer.teleport).
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
m.sprinting = false;
|
||||
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 {
|
||||
if moved > 0.0001 || turned || teleported {
|
||||
host.hub.teleport(i, Some(at));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,17 +83,16 @@ impl Game<'_> {
|
||||
/// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed
|
||||
/// modifier, its effects' modifiers, its equipment's, and what
|
||||
/// `/attribute` changed.
|
||||
pub(super) fn mob_attributes(&self, m: &Mob) -> Vec<AttributeSnapshot> {
|
||||
pub(super) fn mob_attributes(&self, m: &Mob, out: &mut Vec<AttributeSnapshot>) {
|
||||
let kind = m.kind.id.as_str();
|
||||
let mut out = Vec::new();
|
||||
if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") {
|
||||
instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed));
|
||||
instance(out, a, finalize::base_value(m, Attr::MovementSpeed));
|
||||
}
|
||||
if let Some(s) = m.extra.attributes.as_deref() {
|
||||
for (attr, v) in &s.bases {
|
||||
if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name()))
|
||||
{
|
||||
instance(&mut out, a, *v).base = *v;
|
||||
instance(out, a, *v).base = *v;
|
||||
}
|
||||
}
|
||||
for x in &s.modifiers {
|
||||
@@ -101,7 +100,7 @@ impl Game<'_> {
|
||||
self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name()))
|
||||
{
|
||||
add_modifier(
|
||||
&mut out,
|
||||
out,
|
||||
a,
|
||||
finalize::base_value(m, x.attr),
|
||||
AttributeModifier {
|
||||
@@ -122,7 +121,7 @@ impl Game<'_> {
|
||||
finalize::transient(m, Attr::MovementSpeed),
|
||||
) {
|
||||
add_modifier(
|
||||
&mut out,
|
||||
out,
|
||||
a,
|
||||
finalize::base_value(m, Attr::MovementSpeed),
|
||||
AttributeModifier {
|
||||
@@ -150,7 +149,7 @@ impl Game<'_> {
|
||||
};
|
||||
let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute));
|
||||
add_modifier(
|
||||
&mut out,
|
||||
out,
|
||||
a,
|
||||
start,
|
||||
AttributeModifier {
|
||||
@@ -172,10 +171,9 @@ impl Game<'_> {
|
||||
("chest", e.chest.as_ref()),
|
||||
("head", e.head.as_ref()),
|
||||
],
|
||||
&mut out,
|
||||
out,
|
||||
);
|
||||
self.generic_attributes_of(Target::Mob(m.id), &mut out);
|
||||
out
|
||||
self.generic_attributes_of(Target::Mob(m.id), out);
|
||||
}
|
||||
|
||||
/// An armor stand's synced instances: movement speed (its first
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! synched data that differs from the defaults), and who rides what.
|
||||
use super::Game;
|
||||
use horizon_client::lan::{
|
||||
entity::{EntityState, Riding},
|
||||
entity::{EntityState, Riding, States},
|
||||
hub::Hub,
|
||||
};
|
||||
use horizon_protocol::entity_data::{Value, serializer};
|
||||
@@ -107,7 +107,7 @@ impl Game<'_> {
|
||||
&self,
|
||||
host_entity: Option<i32>,
|
||||
hub: &mut Hub,
|
||||
out: &mut Vec<EntityState>,
|
||||
out: &mut States,
|
||||
) {
|
||||
for b in &self.boats {
|
||||
let p = b.position;
|
||||
@@ -268,12 +268,7 @@ impl Game<'_> {
|
||||
|
||||
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
|
||||
/// end crystals, as guests track them.
|
||||
fn lan_projectile_states(
|
||||
&self,
|
||||
host_entity: Option<i32>,
|
||||
hub: &mut Hub,
|
||||
out: &mut Vec<EntityState>,
|
||||
) {
|
||||
fn lan_projectile_states(&self, host_entity: Option<i32>, hub: &mut Hub, out: &mut States) {
|
||||
let owner = |who: Option<horizon_client::mobs::Who>| match who {
|
||||
Some(horizon_client::mobs::Who::Mob(id)) => id as i32,
|
||||
Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0),
|
||||
|
||||
@@ -312,15 +312,10 @@ impl Game<'_> {
|
||||
.map_or_else(String::new, |(end, start)| {
|
||||
format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0)
|
||||
});
|
||||
let list: Vec<String> = spans
|
||||
.iter()
|
||||
.filter(|(_, ms)| *ms >= 0.5)
|
||||
.map(|(n, ms)| format!("{n} {ms:.1}"))
|
||||
.collect();
|
||||
log::info!(
|
||||
"Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}",
|
||||
self.mobs.len(),
|
||||
list.join(", ")
|
||||
horizon_client::spans::describe(&spans)
|
||||
);
|
||||
}
|
||||
result
|
||||
|
||||
@@ -191,7 +191,13 @@ impl NaturalLevel for GameLevel<'_, '_> {
|
||||
StructureSpawns::shared(&self.game.options.resources)
|
||||
}
|
||||
fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option<f64> {
|
||||
nearest_player(&self.players, x, y, z).map(|p| p.distance_sqr(x, y, z))
|
||||
// The nearest player's distance (`nearest_player`), without finding
|
||||
// which player it is: every spawn attempt asks.
|
||||
self.players
|
||||
.iter()
|
||||
.filter(|p| !p.spectator)
|
||||
.map(|p| p.distance_sqr(x, y, z))
|
||||
.reduce(f64::min)
|
||||
}
|
||||
fn respawn(&self) -> Option<[i32; 3]> {
|
||||
// The world spawn point lives in the overworld.
|
||||
|
||||
@@ -230,6 +230,11 @@ impl Game<'_> {
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
super::packs::open_folder(&dir);
|
||||
}
|
||||
Event::OpenShaderPackFolder => {
|
||||
let dir = horizon_client::shader_pack::folder();
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
super::packs::open_folder(&dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -312,6 +312,7 @@ impl Game<'_> {
|
||||
let crouching = p.pose == Pose::Crouching;
|
||||
let (position, flying) = (p.position, p.flying || p.fall_flying);
|
||||
let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity);
|
||||
let spinning = p.auto_spin_attack_ticks > 0;
|
||||
let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0);
|
||||
let using_off_hand = self
|
||||
.using
|
||||
@@ -397,6 +398,7 @@ impl Game<'_> {
|
||||
m.velocity = velocity;
|
||||
m.extra.fall_flying = fall_flying;
|
||||
m.extra.fall_fly_ticks = fly_ticks;
|
||||
m.extra.auto_spin_attack = spinning;
|
||||
m.extra.main_hand_left = self.settings.main_hand_left;
|
||||
m.extra.using_item = using;
|
||||
m.extra.using_off_hand = using_off_hand;
|
||||
@@ -451,6 +453,7 @@ impl Game<'_> {
|
||||
out,
|
||||
);
|
||||
self.player_elytra_geometry(m, camera, alpha as f32, packed, out);
|
||||
self.spin_attack_geometry(m, camera, alpha as f32, packed, out);
|
||||
self.held_item_geometry(m, camera, alpha, packed, true, out);
|
||||
}
|
||||
/// `extractEntityInInventoryFollowsMouse`: the player in the box
|
||||
@@ -592,6 +595,47 @@ impl Game<'_> {
|
||||
out,
|
||||
);
|
||||
}
|
||||
/// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning
|
||||
/// player (`SpinAttackEffectModel.setupAnim`).
|
||||
fn spin_attack_geometry(
|
||||
&self,
|
||||
m: &Mob,
|
||||
camera: glam::DVec3,
|
||||
partial: f32,
|
||||
light: u32,
|
||||
out: &mut Vec<horizon_client::mesher::Vertex>,
|
||||
) {
|
||||
if !m.extra.auto_spin_attack {
|
||||
return;
|
||||
}
|
||||
let (Some(model), Some(rect)) = (
|
||||
self.res.spin_attack().as_ref(),
|
||||
self.gui.atlas.sprites.get("entity/trident/trident_riptide"),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let age = m.age as f32 + partial;
|
||||
horizon_client::mobs::render_model(
|
||||
model,
|
||||
horizon_client::mobs::render::base_transform(m, partial, camera),
|
||||
&|part| {
|
||||
let mut p = part.pose;
|
||||
if let Some(i) = part
|
||||
.name
|
||||
.strip_prefix("box")
|
||||
.and_then(|i| i.parse::<u8>().ok())
|
||||
{
|
||||
let angle = age * -(45.0 + f32::from(i + 1) * 5.0);
|
||||
p[4] = wrap(angle).to_radians();
|
||||
}
|
||||
p
|
||||
},
|
||||
[rect.u0, rect.v0, rect.u1, rect.v1],
|
||||
light,
|
||||
0,
|
||||
out,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn player_preview_quads(
|
||||
|
||||
@@ -103,6 +103,10 @@ pub(super) struct Remote {
|
||||
last_input: u8,
|
||||
was_sprinting: bool,
|
||||
carried: Option<usize>,
|
||||
/// The last ClientboundPlayerAbilitiesPacket. Vanilla's LocalPlayer
|
||||
/// holds its abilities from the login on; here the player is made at
|
||||
/// the first teleport, which takes them then.
|
||||
abilities: Option<play::PlayerAbilities>,
|
||||
loaded_sent: bool,
|
||||
/// The view distance last sent in ClientInformation.
|
||||
sent_view: i8,
|
||||
@@ -331,6 +335,7 @@ impl Game<'_> {
|
||||
last_input: 0,
|
||||
was_sprinting: false,
|
||||
carried: None,
|
||||
abilities: None,
|
||||
loaded_sent: false,
|
||||
sent_view: view,
|
||||
predictions: HashMap::new(),
|
||||
@@ -544,6 +549,28 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The minecarts the server sent, for the control socket's `status`
|
||||
/// (their velocity is not tracked here).
|
||||
pub(super) fn remote_carts(&self) -> Option<Vec<serde_json::Value>> {
|
||||
let r = self.remote.as_ref()?;
|
||||
let mut carts: Vec<&Tracked> = r
|
||||
.entities
|
||||
.values()
|
||||
.filter(|t| t.kind.ends_with("minecart"))
|
||||
.collect();
|
||||
carts.sort_by(|a, b| {
|
||||
a.position
|
||||
.partial_cmp(&b.position)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
});
|
||||
Some(
|
||||
carts
|
||||
.into_iter()
|
||||
.map(|t| serde_json::json!({"kind": t.kind, "position": t.position, "velocity": [0.0, 0.0, 0.0]}))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The names in the server's player list, sorted.
|
||||
pub(super) fn remote_online_names(&self) -> Option<Vec<String>> {
|
||||
let r = self.remote.as_ref()?;
|
||||
@@ -1891,9 +1918,10 @@ impl Game<'_> {
|
||||
},
|
||||
C::PlayerAbilities(p) => {
|
||||
self.creative = p.flags & 8 != 0;
|
||||
if let Some(player) = &mut self.player {
|
||||
player.flying_speed = p.flying_speed;
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.abilities = Some(p);
|
||||
}
|
||||
self.apply_remote_abilities();
|
||||
}
|
||||
C::SetHeldSlot(p) => {
|
||||
self.selected = p.slot.clamp(0, 8) as usize;
|
||||
@@ -2536,6 +2564,7 @@ impl Game<'_> {
|
||||
self.previous_eye = 1.62;
|
||||
self.clock.reset();
|
||||
self.apply_remote_health();
|
||||
self.apply_remote_abilities();
|
||||
}
|
||||
}
|
||||
self.previous_position = position;
|
||||
@@ -2671,6 +2700,7 @@ impl Game<'_> {
|
||||
[player.velocity.x, player.velocity.y, player.velocity.z],
|
||||
[player.position.x, player.position.y, player.position.z],
|
||||
);
|
||||
let was_flying = player.flying;
|
||||
player.yaw = self.yaw;
|
||||
let dead = self.screen == Screen::Dead;
|
||||
// LivingEntity.isImmobile: a sleeper lies still in the bed.
|
||||
@@ -2693,6 +2723,9 @@ impl Game<'_> {
|
||||
}
|
||||
.controlled_simulation_tick(keys)?;
|
||||
}
|
||||
// LocalPlayer.onUpdateAbilities: flight turned on or off (a double
|
||||
// jump, a spectator, landing) is sent to the server.
|
||||
let flying = player.flying;
|
||||
let events = std::mem::take(&mut player.events);
|
||||
self.previous_eye = self.eye;
|
||||
self.eye += (player.dimensions.eye_height - self.eye) * 0.5;
|
||||
@@ -2727,9 +2760,29 @@ impl Game<'_> {
|
||||
if !dead {
|
||||
self.remote_tick_using();
|
||||
}
|
||||
if flying != was_flying {
|
||||
self.send(S::PlayerAbilities(play::PlayerAbilitiesRequest {
|
||||
flags: if flying { 2 } else { 0 },
|
||||
}));
|
||||
}
|
||||
self.remote_send_state(input);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// ClientPacketListener.handlePlayerAbilities: the player flies, may fly
|
||||
/// and is invulnerable as the server says (bits 2, 4 and 1).
|
||||
fn apply_remote_abilities(&mut self) {
|
||||
let (Some(player), Some(a)) = (
|
||||
self.player.as_mut(),
|
||||
self.remote.as_ref().and_then(|r| r.abilities.as_ref()),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
player.invulnerable = a.flags & 1 != 0;
|
||||
player.flying = a.flags & 2 != 0;
|
||||
player.may_fly = a.flags & 4 != 0;
|
||||
player.flying_speed = a.flying_speed;
|
||||
}
|
||||
/// The local player's share of every touching entity's
|
||||
/// `LivingEntity.pushEntities`: on a client `EntitySelector.pushableBy`
|
||||
/// lets entities push only the local player, so the server never sends
|
||||
|
||||
@@ -37,11 +37,8 @@ impl ShaderPacks {
|
||||
}
|
||||
}
|
||||
|
||||
/// `shaderpacks/` beside `options.txt`.
|
||||
pub(super) fn dir() -> PathBuf {
|
||||
std::env::current_dir()
|
||||
.unwrap_or_default()
|
||||
.join(shader_pack::DIR)
|
||||
shader_pack::folder()
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -77,6 +74,7 @@ impl Game<'_> {
|
||||
return self.shader_pack_error(&id, &e.to_string());
|
||||
}
|
||||
self.shader_packs.pack = pack;
|
||||
self.ui.options.shader_pack_error = None;
|
||||
}
|
||||
/// Give the loaded pack to the renderer (also after it is rebuilt).
|
||||
pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> {
|
||||
@@ -105,6 +103,11 @@ impl Game<'_> {
|
||||
}
|
||||
fn shader_pack_error(&mut self, id: &str, error: &str) {
|
||||
log::warn!("Horizon: shader pack {id}: {error}");
|
||||
// The Shader Packs page says why on the pack's row: the first line,
|
||||
// since translator errors go on with a drawn source excerpt.
|
||||
let first = error.lines().map(str::trim).find(|l| !l.is_empty());
|
||||
self.ui.options.shader_pack_error =
|
||||
Some((id.to_owned(), first.unwrap_or(error).to_owned()));
|
||||
self.system_message(Text::literal(format!("Shader pack {id}: {error}")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,6 +373,11 @@ impl Loading {
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
packs::open_folder(&dir);
|
||||
}
|
||||
Event::OpenShaderPackFolder => {
|
||||
let dir = horizon_client::shader_pack::folder();
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
packs::open_folder(&dir);
|
||||
}
|
||||
Event::ButtonClick => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +122,38 @@ impl Game<'_> {
|
||||
let sky = self.world.light(x, y + 1, z) >> 4 == 15;
|
||||
water || (self.world.weather.raining && sky)
|
||||
}
|
||||
/// The living entities a spinning player can touch this tick, for
|
||||
/// `LivingEntity.checkAutoSpinAttack` (none when not spinning).
|
||||
pub(super) fn spin_targets(&self) -> Vec<(u32, Aabb)> {
|
||||
let Some(p) = self
|
||||
.player
|
||||
.as_ref()
|
||||
.filter(|p| p.auto_spin_attack_ticks > 0)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
// A spin moves a few blocks a tick at most.
|
||||
let near = p.bounds().inflate(Vec3::new(16.0, 16.0, 16.0));
|
||||
self.mobs
|
||||
.iter()
|
||||
.filter(|m| m.alive() && m.bounds().intersects(near))
|
||||
.map(|m| (m.id, m.bounds()))
|
||||
.collect()
|
||||
}
|
||||
/// `Player.doAutoAttackOnTouch`: the touched entity takes `Player.attack`
|
||||
/// with the spin's damage; once the spin is over its damage is cleared.
|
||||
pub(super) fn end_spin_attack(&mut self, hit: Option<u32>) {
|
||||
if let Some(id) = hit
|
||||
&& let Some(index) = self.mobs.iter().position(|m| m.id == id)
|
||||
{
|
||||
self.attack_mob(index);
|
||||
}
|
||||
if let Some(p) = self.player.as_mut()
|
||||
&& p.auto_spin_attack_ticks <= 0
|
||||
{
|
||||
p.auto_spin_attack_dmg = 0.0;
|
||||
}
|
||||
}
|
||||
/// `TridentItem.releaseUsing`.
|
||||
pub(super) fn release_trident(&mut self, ticks: u32) {
|
||||
if ticks < 10 {
|
||||
@@ -152,6 +184,9 @@ impl Game<'_> {
|
||||
p.velocity.y + d[1] * f64::from(strength),
|
||||
p.velocity.z + d[2] * f64::from(strength),
|
||||
);
|
||||
// Player.startAutoSpinAttack(20, 8, stack).
|
||||
p.auto_spin_attack_ticks = 20;
|
||||
p.auto_spin_attack_dmg = 8.0;
|
||||
if p.ground.on_ground {
|
||||
p.position.y += 1.2;
|
||||
}
|
||||
|
||||
@@ -107,13 +107,16 @@ struct Globals {
|
||||
fog_ends: [f32; 4],
|
||||
/// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
|
||||
end_portal_sprites: [[f32; 4]; 2],
|
||||
/// x: vanilla's `GameTime` uniform; y: nether cardinal lighting, zw unused.
|
||||
/// x: vanilla's `GameTime` uniform; y: nether cardinal lighting; z: how many
|
||||
/// `dynamic_lights` are set; w unused.
|
||||
time: [f32; 4],
|
||||
/// Atlas rect of a destroy stage (entity.wgsl takes only its size: every stage's is the same,
|
||||
/// and each crack carries its own stage's origin).
|
||||
crumbling_sprite: [f32; 4],
|
||||
/// Framebuffer size, selection stroke width, perspective layering scale.
|
||||
outline_params: [f32; 4],
|
||||
/// Horizon Extras' dynamic lights: camera-relative position and level (`dynamic_light`).
|
||||
dynamic_lights: [[f32; 4]; crate::dynamic_light::MAX],
|
||||
}
|
||||
pub type SectionKey = (i32, i32, i32);
|
||||
struct SectionGpu {
|
||||
@@ -186,6 +189,8 @@ pub struct Frame<'a> {
|
||||
pub nether_lighting: bool,
|
||||
/// Camera-relative entity geometry textured from the shared atlas.
|
||||
pub entities: &'a [Vertex],
|
||||
/// 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).
|
||||
@@ -2908,10 +2913,17 @@ impl Renderer {
|
||||
time: [
|
||||
frame.shader_game_time,
|
||||
f32::from(frame.nether_lighting),
|
||||
0.0,
|
||||
frame.dynamic_lights.len().min(crate::dynamic_light::MAX) as f32,
|
||||
0.0,
|
||||
],
|
||||
outline_params: outline_params(self.config.width, self.config.height),
|
||||
dynamic_lights: {
|
||||
let mut lights = [[0.0; 4]; crate::dynamic_light::MAX];
|
||||
for (to, from) in lights.iter_mut().zip(frame.dynamic_lights) {
|
||||
*to = *from;
|
||||
}
|
||||
lights
|
||||
},
|
||||
};
|
||||
self.uploads
|
||||
.buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals));
|
||||
@@ -4155,6 +4167,34 @@ mod tests {
|
||||
);
|
||||
assert_eq!(surface_format(&[Rgba16Float], Bgra8UnormSrgb), Rgba16Float);
|
||||
}
|
||||
/// A Wayland surface on a compositor with colour management, as wgpu lists it (Mesa 26.2
|
||||
/// ANV on an Intel HD 620 under weston 16): wide formats first. The pre-#1075 choice,
|
||||
/// the first non-sRGB format, took `Rgba16Float` and the window looked washed out, as if
|
||||
/// under a white overlay (#1007); XWayland lists no such format, which is why it looked fine.
|
||||
#[test]
|
||||
fn a_colour_managed_wayland_surface_still_gets_8_bit() {
|
||||
use super::surface_format;
|
||||
use wgpu::TextureFormat::*;
|
||||
let wayland = [
|
||||
Rgba16Float,
|
||||
Rgba16Unorm,
|
||||
Rgb10a2Unorm,
|
||||
Bgra8UnormSrgb,
|
||||
Bgra8Unorm,
|
||||
Rgba8UnormSrgb,
|
||||
Rgba8Unorm,
|
||||
];
|
||||
assert_eq!(surface_format(&wayland, Bgra8UnormSrgb), Bgra8Unorm);
|
||||
// Without Bgra8: Rgba8, still not a 16- or 10-bit format.
|
||||
let without_bgra = [
|
||||
Rgba16Float,
|
||||
Rgba16Unorm,
|
||||
Rgb10a2Unorm,
|
||||
Rgba8UnormSrgb,
|
||||
Rgba8Unorm,
|
||||
];
|
||||
assert_eq!(surface_format(&without_bgra, Rgba8UnormSrgb), Rgba8Unorm);
|
||||
}
|
||||
#[test]
|
||||
fn special_material_batches_preserve_quad_order_and_offsets() {
|
||||
let quad = |layer, id| {
|
||||
|
||||
@@ -237,7 +237,7 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
h(
|
||||
H::ShaderPack,
|
||||
High,
|
||||
"Redraws the world with a pack from shaderpacks/. Off is vanilla.",
|
||||
"Redraws the world with a pack from the shaderpacks folder. Off is vanilla.",
|
||||
),
|
||||
Row::Header("Preferences"),
|
||||
v(Opt::ViewBobbing, None, "Sways the view while walking."),
|
||||
@@ -422,17 +422,6 @@ impl H {
|
||||
H::Antialiasing => g.fxaa = !g.fxaa,
|
||||
H::BatteryMode => g.battery = !g.battery,
|
||||
H::GraphicsApi => g.api = step(&GraphicsApi::ALL, g.api, back),
|
||||
H::ShaderPack => {
|
||||
// Off, then every pack in shaderpacks/ by folder name.
|
||||
let dir = std::env::current_dir()
|
||||
.unwrap_or_default()
|
||||
.join(crate::shader_pack::DIR);
|
||||
let mut all = vec![String::new()];
|
||||
all.extend(crate::shader_pack::list(&dir).into_iter().map(|(id, _)| id));
|
||||
let i = all.iter().position(|x| *x == g.shader_pack).unwrap_or(0);
|
||||
let n = all.len();
|
||||
g.shader_pack = all[if back { (i + n - 1) % n } else { (i + 1) % n }].clone();
|
||||
}
|
||||
H::Pacing => {
|
||||
g.pacing = match g.pacing {
|
||||
Pacing::Efficient => Pacing::Precise,
|
||||
@@ -559,6 +548,8 @@ pub enum Action {
|
||||
Changed,
|
||||
OpenAdvanced,
|
||||
OpenSimple,
|
||||
/// The Shader Pack row: the Shader Packs page (where packs are picked).
|
||||
OpenShaderPacks,
|
||||
Done,
|
||||
}
|
||||
|
||||
@@ -784,6 +775,9 @@ impl GraphicsUi {
|
||||
}
|
||||
return match wd.target {
|
||||
Target::Button(action) => vec![Action::ButtonClick, action],
|
||||
Target::Item(Item::Horizon(H::ShaderPack)) => {
|
||||
vec![Action::ButtonClick, Action::OpenShaderPacks]
|
||||
}
|
||||
Target::Item(item) => {
|
||||
if item.slider(s).is_some() {
|
||||
self.dragging = Some(item);
|
||||
@@ -1003,11 +997,30 @@ mod tests {
|
||||
);
|
||||
s.horizon.shader_pack = "horizon-sample".into();
|
||||
assert_eq!(row.label(&s).plain(), "Shader Pack: horizon-sample");
|
||||
// Picking a pack keeps the preset.
|
||||
Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480]);
|
||||
let preset = s.horizon.preset;
|
||||
row.cycle(&mut s, false, [854, 480]);
|
||||
assert_eq!(s.horizon.preset, preset);
|
||||
// The row opens the Shader Packs page, where packs are picked.
|
||||
let mut ui = GraphicsUi::default();
|
||||
let find = |ui: &mut GraphicsUi| {
|
||||
let (widgets, ..) = ui.layout(Level::Advanced, 854.0, 480.0);
|
||||
widgets
|
||||
.into_iter()
|
||||
.find(|w| matches!(w.target, Target::Item(i) if i == row))
|
||||
.unwrap()
|
||||
};
|
||||
ui.scroll = find(&mut ui).y - GraphicsUi::bounds(480.0).0 - 4.0;
|
||||
let w = find(&mut ui);
|
||||
assert_eq!(
|
||||
ui.click(
|
||||
Level::Advanced,
|
||||
&mut s,
|
||||
(w.x + 1.0, w.y + 1.0),
|
||||
(854.0, 480.0),
|
||||
[854, 480],
|
||||
false,
|
||||
false
|
||||
),
|
||||
[Action::ButtonClick, Action::OpenShaderPacks]
|
||||
);
|
||||
assert_eq!(s.horizon.shader_pack, "horizon-sample");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! The anonymous "I'm playing" ping (`horizon_telemetry::live`, docs/telemetry.md) behind the
|
||||
//! 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).
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::Thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use horizon_telemetry::live::{self, Ping};
|
||||
|
||||
/// A world is open to LAN or to friends.
|
||||
static LAN: AtomicBool = AtomicBool::new(false);
|
||||
static PINGER: OnceLock<Thread> = OnceLock::new();
|
||||
|
||||
/// After a failure the next ping waits longer, doubling up to this.
|
||||
const MAX_WAIT: Duration = Duration::from_secs(600);
|
||||
|
||||
/// Starts the pings, once. Call when the game itself starts (not a dedicated server, not a
|
||||
/// benchmark or an automated run).
|
||||
pub fn start() {
|
||||
if PINGER.get().is_some() || std::env::var_os("HORIZON_NO_HEARTBEAT").is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(endpoint) = horizon_telemetry::endpoint() else {
|
||||
return;
|
||||
};
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("Heartbeat".into())
|
||||
.spawn(move || run(&endpoint));
|
||||
match spawned {
|
||||
Ok(handle) => {
|
||||
let _ = PINGER.set(handle.thread().clone());
|
||||
}
|
||||
Err(e) => log::warn!("Horizon: no live count ping: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a world is open to LAN or friends; a change is sent at once.
|
||||
pub fn set_lan(open: bool) {
|
||||
if LAN.swap(open, Ordering::Relaxed) != open
|
||||
&& let Some(pinger) = PINGER.get()
|
||||
{
|
||||
pinger.unpark();
|
||||
}
|
||||
}
|
||||
|
||||
fn run(endpoint: &str) {
|
||||
let session = live::session_id();
|
||||
let version = crate::telemetry::version();
|
||||
let mut wait = live::INTERVAL;
|
||||
let mut failed = false;
|
||||
loop {
|
||||
let ping = Ping::new(&session, &version, LAN.load(Ordering::Relaxed));
|
||||
match live::send(endpoint, &ping) {
|
||||
Ok(()) => {
|
||||
wait = live::INTERVAL;
|
||||
failed = false;
|
||||
}
|
||||
Err(e) => {
|
||||
// Said once, not every minute the server is away.
|
||||
if !failed {
|
||||
log::info!("Horizon: the live count ping failed ({e}); trying again later");
|
||||
}
|
||||
failed = true;
|
||||
wait = (wait * 2).min(MAX_WAIT);
|
||||
}
|
||||
}
|
||||
// Woken early by `set_lan`; a spurious wake only sends one ping more.
|
||||
std::thread::park_timeout(wait);
|
||||
}
|
||||
}
|
||||
@@ -179,4 +179,43 @@ mod tests {
|
||||
);
|
||||
assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple");
|
||||
}
|
||||
|
||||
/// The packs in `HORIZON_TEST_SHADERPACKS` (folders or zips) load as the
|
||||
/// game loads them, with their default options: the compatibility table
|
||||
/// of docs/shader-packs.md. Skipped when the variable isn't set.
|
||||
#[test]
|
||||
fn real_packs_load() {
|
||||
let Some(dir) = std::env::var_os("HORIZON_TEST_SHADERPACKS") else {
|
||||
return;
|
||||
};
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| is_java_pack(p))
|
||||
.collect();
|
||||
entries.sort();
|
||||
let mut failures = Vec::new();
|
||||
for path in entries {
|
||||
let name = path.file_name().unwrap().to_string_lossy().into_owned();
|
||||
match load(&path, &BTreeMap::new(), "Apple", "Apple M4 Pro") {
|
||||
Ok(pack) => {
|
||||
let folders: Vec<String> = pack
|
||||
.folders
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let n = f.passes.len() + usize::from(f.final_pass.is_some());
|
||||
format!("{} {n} passes", f.folder)
|
||||
})
|
||||
.collect();
|
||||
println!("{name}: loads ({})", folders.join(", "));
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{name}: {e}");
|
||||
failures.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{failures:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn changed_attributes(
|
||||
}
|
||||
|
||||
/// What the game says about one entity this tick.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct EntityState {
|
||||
pub id: i32,
|
||||
pub uuid: u128,
|
||||
@@ -61,6 +61,72 @@ pub struct EntityState {
|
||||
pub precise: bool,
|
||||
}
|
||||
|
||||
impl EntityState {
|
||||
/// The entity `id` of type `kind` as a fresh state has it: at the origin,
|
||||
/// at rest, with no data, equipment or attributes. Keeps the allocations
|
||||
/// of the strings and vectors it held.
|
||||
pub fn reset(&mut self, id: i32, uuid: u128, kind: &str) {
|
||||
self.id = id;
|
||||
self.uuid = uuid;
|
||||
self.kind.clear();
|
||||
self.kind.push_str(kind);
|
||||
self.position = [0.0; 3];
|
||||
(self.yaw, self.pitch, self.head_yaw) = (0.0, 0.0, 0.0);
|
||||
self.on_ground = false;
|
||||
self.velocity = [0.0; 3];
|
||||
self.data = 0;
|
||||
self.meta.clear();
|
||||
self.equipment.clear();
|
||||
self.attributes.clear();
|
||||
self.precise = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// The states a level describes its entities with, kept from tick to tick:
|
||||
/// each tick's are written over the last tick's in place, so the strings and
|
||||
/// vectors in them are reused instead of being made and freed again for every
|
||||
/// entity on every tick.
|
||||
#[derive(Default)]
|
||||
pub struct States {
|
||||
list: Vec<EntityState>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl States {
|
||||
/// Start a new tick's states.
|
||||
pub fn clear(&mut self) {
|
||||
self.len = 0;
|
||||
}
|
||||
/// The next entity's state, reset (`EntityState::reset`).
|
||||
pub fn add(&mut self, id: i32, uuid: u128, kind: &str) -> &mut EntityState {
|
||||
if self.len == self.list.len() {
|
||||
self.list.push(EntityState::default());
|
||||
}
|
||||
let e = &mut self.list[self.len];
|
||||
self.len += 1;
|
||||
e.reset(id, uuid, kind);
|
||||
e
|
||||
}
|
||||
pub fn push(&mut self, e: EntityState) {
|
||||
match self.list.get_mut(self.len) {
|
||||
Some(slot) => *slot = e,
|
||||
None => self.list.push(e),
|
||||
}
|
||||
self.len += 1;
|
||||
}
|
||||
pub fn as_slice(&self) -> &[EntityState] {
|
||||
&self.list[..self.len]
|
||||
}
|
||||
}
|
||||
|
||||
impl Extend<EntityState> for States {
|
||||
fn extend<I: IntoIterator<Item = EntityState>>(&mut self, states: I) {
|
||||
for e in states {
|
||||
self.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `AbstractArrow`: every update sends its position and rotation.
|
||||
fn is_arrow(kind: &str) -> bool {
|
||||
matches!(
|
||||
@@ -792,6 +858,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states_are_written_over_last_ticks_in_place() {
|
||||
let mut states = States::default();
|
||||
let e = states.add(1, 1, "minecraft:zombie");
|
||||
e.position = [1.0, 2.0, 3.0];
|
||||
e.meta.push((9, serializer::FLOAT, Value::Float(20.0)));
|
||||
e.equipment.push((0, None));
|
||||
let (kind, meta) = (e.kind.as_ptr(), e.meta.as_ptr());
|
||||
states.push(state(2.0));
|
||||
states.clear();
|
||||
let e = states.add(3, 3, "minecraft:husk");
|
||||
// Nothing of the last tick's state is left, but its allocations are.
|
||||
let fresh = EntityState {
|
||||
id: 3,
|
||||
uuid: 3,
|
||||
kind: "minecraft:husk".into(),
|
||||
..EntityState::default()
|
||||
};
|
||||
assert_eq!(*e, fresh);
|
||||
assert_eq!((e.kind.as_ptr(), e.meta.as_ptr()), (kind, meta));
|
||||
assert_eq!(states.as_slice(), std::slice::from_ref(&fresh));
|
||||
states.extend([state(5.0), state(6.0)]);
|
||||
assert_eq!(states.as_slice(), [fresh, state(5.0), state(6.0)]);
|
||||
}
|
||||
|
||||
/// The entity as added this tick, then its updates (one a tick).
|
||||
fn added(e: &EntityState) -> ServerEntity {
|
||||
ServerEntity::new(e, Some(100), &Riding::default())
|
||||
|
||||
@@ -1872,6 +1872,7 @@ impl Hub {
|
||||
// (handlePlayerKnownMovement), PlayerInput once loaded.
|
||||
let acted = match &packet {
|
||||
S::AcceptTeleportation(_)
|
||||
| S::PlayerAbilities(_)
|
||||
| S::MovePlayerStatus(_)
|
||||
| S::MovePlayerRot(_)
|
||||
| S::PlayerLoaded(_)
|
||||
@@ -1909,6 +1910,11 @@ impl Hub {
|
||||
self.position_change(i, [p.x, p.y, p.z], rot, 0, ctx, events);
|
||||
}
|
||||
}
|
||||
// handlePlayerAbilities: the client flies only if it may.
|
||||
S::PlayerAbilities(p) => {
|
||||
let g = &mut self.guests[i];
|
||||
g.flying = p.flags & 2 != 0 && (g.creative() || g.spectator());
|
||||
}
|
||||
S::MovePlayerPos(p) => {
|
||||
self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags, ctx, events);
|
||||
}
|
||||
@@ -2183,6 +2189,13 @@ impl Hub {
|
||||
return;
|
||||
};
|
||||
g.game_mode = mode;
|
||||
// GameType.updatePlayerAbilities: a spectator flies, survival and
|
||||
// adventure don't, creative keeps what it had.
|
||||
if g.spectator() {
|
||||
g.flying = true;
|
||||
} else if !g.creative() {
|
||||
g.flying = false;
|
||||
}
|
||||
let uuid = g.uuid;
|
||||
g.send(&C::GameEvent(play::GameEvent {
|
||||
event: game_event::CHANGE_GAME_MODE,
|
||||
|
||||
@@ -51,6 +51,7 @@ pub mod datapack;
|
||||
pub mod debug_chart;
|
||||
pub mod debug_keys;
|
||||
pub mod debug_overlay;
|
||||
pub mod dynamic_light;
|
||||
pub mod effects;
|
||||
pub mod enchant;
|
||||
pub mod end_crystal;
|
||||
@@ -79,6 +80,7 @@ pub mod graphics;
|
||||
pub mod graphics_style;
|
||||
pub mod graphics_ui;
|
||||
pub mod health;
|
||||
pub mod heartbeat;
|
||||
pub mod hotbar;
|
||||
pub mod hud;
|
||||
pub mod hud_layout;
|
||||
|
||||
@@ -690,6 +690,8 @@ pub struct Extra {
|
||||
pub blocking: bool,
|
||||
pub fall_flying: bool,
|
||||
pub fall_fly_ticks: i32,
|
||||
/// `LivingEntity.isAutoSpinAttack` (Riptide).
|
||||
pub auto_spin_attack: bool,
|
||||
pub main_hand_left: bool,
|
||||
pub elytra: ElytraAnimation,
|
||||
pub swim: SwimAnimation,
|
||||
|
||||
@@ -771,6 +771,11 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4
|
||||
.sqrt()
|
||||
.min(1.0);
|
||||
base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians());
|
||||
} else if m.extra.auto_spin_attack {
|
||||
// Riptide: lying along the look direction, spinning 75 degrees a tick.
|
||||
let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha;
|
||||
base *= glam::Mat4::from_rotation_x((-90.0 - pitch).to_radians())
|
||||
* glam::Mat4::from_rotation_y(((m.age as f32 + alpha) * -75.0).to_radians());
|
||||
} else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) {
|
||||
// isEntityUpsideDown
|
||||
base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0))
|
||||
@@ -781,7 +786,9 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4
|
||||
let ticks = m.extra.fall_fly_ticks as f32 + alpha;
|
||||
let scale = (ticks * ticks / 100.0).min(1.0);
|
||||
let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha;
|
||||
base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians());
|
||||
if !m.extra.auto_spin_attack {
|
||||
base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians());
|
||||
}
|
||||
let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha;
|
||||
let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos());
|
||||
let v = m.velocity;
|
||||
|
||||
@@ -691,33 +691,37 @@ pub struct StructureAt {
|
||||
}
|
||||
|
||||
/// `NetherFortressStructure.FORTRESS_ENEMIES`.
|
||||
pub fn fortress_enemies() -> Vec<SpawnEntry> {
|
||||
let e = |entity: &str, weight, min, max, constant| SpawnEntry {
|
||||
entity: entity.to_owned(),
|
||||
weight,
|
||||
min,
|
||||
max,
|
||||
constant,
|
||||
};
|
||||
vec![
|
||||
e("minecraft:blaze", 10, 2, 3, false),
|
||||
e("minecraft:zombified_piglin", 5, 4, 4, true),
|
||||
e("minecraft:wither_skeleton", 8, 5, 5, true),
|
||||
e("minecraft:skeleton", 2, 5, 5, true),
|
||||
e("minecraft:magma_cube", 3, 4, 4, true),
|
||||
]
|
||||
pub fn fortress_enemies() -> &'static [SpawnEntry] {
|
||||
static ENEMIES: std::sync::LazyLock<Vec<SpawnEntry>> = std::sync::LazyLock::new(|| {
|
||||
let e = |entity: &str, weight, min, max, constant| SpawnEntry {
|
||||
entity: entity.to_owned(),
|
||||
weight,
|
||||
min,
|
||||
max,
|
||||
constant,
|
||||
};
|
||||
vec![
|
||||
e("minecraft:blaze", 10, 2, 3, false),
|
||||
e("minecraft:zombified_piglin", 5, 4, 4, true),
|
||||
e("minecraft:wither_skeleton", 8, 5, 5, true),
|
||||
e("minecraft:skeleton", 2, 5, 5, true),
|
||||
e("minecraft:magma_cube", 3, 4, 4, true),
|
||||
]
|
||||
});
|
||||
&ENEMIES
|
||||
}
|
||||
|
||||
/// `NaturalSpawner.mobsAt`: the fortress bounds on nether bricks, then
|
||||
/// `ChunkGenerator.getMobsAt` (the first referenced structure whose override
|
||||
/// for the category holds the position), else the biome's list.
|
||||
/// for the category holds the position), else the biome's list. Borrowed from
|
||||
/// the level: a spawn attempt looks it up up to twice.
|
||||
pub fn mobs_at<L: NaturalLevel>(
|
||||
l: &L,
|
||||
category: Category,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
) -> Vec<SpawnEntry> {
|
||||
) -> &[SpawnEntry] {
|
||||
// Only a fortress or a structure overriding this category's spawns can
|
||||
// change the list, so only theirs are looked up (the references reaching
|
||||
// most chunks are mineshafts, which override nothing).
|
||||
@@ -738,13 +742,12 @@ pub fn mobs_at<L: NaturalLevel>(
|
||||
if let Some(o) = overrides.get(&s.id, category.name())
|
||||
&& (if o.piece { s.in_piece } else { s.in_bounds })
|
||||
{
|
||||
return o.spawns.clone();
|
||||
return &o.spawns;
|
||||
}
|
||||
}
|
||||
l.biome_spawns(x, y, z)
|
||||
.and_then(|b| b.get(category.name()))
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
/// `WeightedList.getRandom`.
|
||||
@@ -1103,7 +1106,7 @@ pub fn spawn_category_for_position<L: NaturalLevel, R: RandomSource>(
|
||||
{
|
||||
None
|
||||
} else {
|
||||
weighted_pick(&mobs_at(l, category, x, y, z), random)
|
||||
weighted_pick(mobs_at(l, category, x, y, z), random)
|
||||
};
|
||||
let Some(entry) = list else {
|
||||
break;
|
||||
|
||||
@@ -247,6 +247,14 @@ pub struct PlayerMotion {
|
||||
pub glide_ending: bool,
|
||||
/// Glider durability to take this tick (updateFallFlying).
|
||||
pub glider_wear: u32,
|
||||
/// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's
|
||||
/// spin. The damage stays until the game has dealt the hit.
|
||||
pub auto_spin_attack_ticks: i32,
|
||||
pub auto_spin_attack_dmg: f32,
|
||||
/// The living entities the game put near a spinning player (id, box).
|
||||
pub spin_targets: Vec<(u32, Aabb)>,
|
||||
/// The entity the spin touched this tick (`doAutoAttackOnTouch`).
|
||||
pub spin_hit: Option<u32>,
|
||||
pub sprinting: bool,
|
||||
pub sprint_input: crate::sprint::SprintState,
|
||||
pub shift_key_down: bool,
|
||||
@@ -262,6 +270,10 @@ pub struct PlayerMotion {
|
||||
pub steps: MovementDistances,
|
||||
pub needs_sync: bool,
|
||||
pub sync_position: bool,
|
||||
/// Moved by an ender pearl (`ServerPlayer.teleport`): a server sends the
|
||||
/// position packet even when the player lands where they stood. The
|
||||
/// server takes it at the end of a guest's turn.
|
||||
pub teleported: bool,
|
||||
pub events: Vec<MotionEvent>,
|
||||
pub attributes: LiveAttributes<Box<dyn FnMut() -> i32>>,
|
||||
pub impulse: ImpulseContext,
|
||||
@@ -409,6 +421,10 @@ impl PlayerMotion {
|
||||
fall_fly_ticks: 0,
|
||||
glide_ending: false,
|
||||
glider_wear: 0,
|
||||
auto_spin_attack_ticks: 0,
|
||||
auto_spin_attack_dmg: 0.0,
|
||||
spin_targets: Vec::new(),
|
||||
spin_hit: None,
|
||||
sprinting: false,
|
||||
sprint_input: crate::sprint::SprintState::default(),
|
||||
shift_key_down: false,
|
||||
@@ -428,6 +444,7 @@ impl PlayerMotion {
|
||||
},
|
||||
needs_sync: false,
|
||||
sync_position: false,
|
||||
teleported: false,
|
||||
events: Vec::new(),
|
||||
attributes,
|
||||
fluids: PlayerFluids::default(),
|
||||
@@ -919,6 +936,7 @@ impl MotionWorld<'_, '_, '_> {
|
||||
input.z = 0.0;
|
||||
}
|
||||
self.jump_phase()?;
|
||||
let before_travel = self.player.bounds();
|
||||
// Player.travel: swim steering, then LivingEntity.travel (fluids
|
||||
// first, then gliding, then air), keeping 0.6 of the vertical speed
|
||||
// while flying.
|
||||
@@ -973,8 +991,26 @@ impl MotionWorld<'_, '_, '_> {
|
||||
{
|
||||
self.freeze_damage()?;
|
||||
}
|
||||
if self.player.auto_spin_attack_ticks > 0 {
|
||||
self.player.auto_spin_attack_ticks -= 1;
|
||||
self.check_auto_spin_attack(before_travel);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `LivingEntity.checkAutoSpinAttack`: the first living entity in the
|
||||
/// box swept this tick takes the hit and ends the spin, bouncing the
|
||||
/// player back at a fifth of its speed; a wall ends it too.
|
||||
fn check_auto_spin_attack(&mut self, before: Aabb) {
|
||||
let swept = before.union_bounds(self.player.bounds());
|
||||
let p = &mut self.player;
|
||||
if let Some(&(id, _)) = p.spin_targets.iter().find(|(_, b)| b.intersects(swept)) {
|
||||
p.spin_hit = Some(id);
|
||||
p.auto_spin_attack_ticks = 0;
|
||||
p.velocity = p.velocity.scale(-0.2);
|
||||
} else if p.collision.horizontal {
|
||||
p.auto_spin_attack_ticks = 0;
|
||||
}
|
||||
}
|
||||
/// `hurtServer(damageSources().freeze(), 1)` for a fully frozen player.
|
||||
fn freeze_damage(&mut self) -> Result<()> {
|
||||
let id = self
|
||||
@@ -2659,6 +2695,49 @@ mod tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn a_riptide_spin_lies_flat_and_ends_on_the_first_entity_it_touches() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("movement-properties.nbt").exists() {
|
||||
return;
|
||||
}
|
||||
let assets = Assets::load(&root).unwrap();
|
||||
let render = assets.reload(&root).unwrap();
|
||||
let binding = crate::collisions::load(&root, assets.registry).unwrap();
|
||||
let resources = MotionResources::load(&root, &assets).unwrap();
|
||||
let mut scene = World::test_scene(&assets, &render, 2).unwrap();
|
||||
let ahead = Aabb::new(Vec3::new(20.2, 9.0, 21.5), Vec3::new(20.8, 11.0, 22.1));
|
||||
for target in [None, Some(ahead)] {
|
||||
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 10.0, 20.5)).unwrap();
|
||||
player.auto_spin_attack_ticks = 20;
|
||||
player.auto_spin_attack_dmg = 8.0;
|
||||
player.velocity = Vec3::new(0.0, 0.0, 1.0);
|
||||
player.spin_targets = target.map(|b| (7, b)).into_iter().collect();
|
||||
let mut w = MotionWorld {
|
||||
entities: &[],
|
||||
player: &mut player,
|
||||
scene: &mut scene,
|
||||
assets: &assets,
|
||||
collision_binding: &binding,
|
||||
resources: &resources,
|
||||
};
|
||||
w.simulation_tick([0.0, 0.0], false).unwrap();
|
||||
if target.is_some() {
|
||||
// Touched: the hit, no more spin, bounced back at a fifth.
|
||||
assert_eq!(w.player.spin_hit, Some(7));
|
||||
assert_eq!(w.player.auto_spin_attack_ticks, 0);
|
||||
assert!(w.player.velocity.z < 0.0, "{:?}", w.player.velocity);
|
||||
assert_eq!(w.player.pose, crate::pose::Pose::Standing);
|
||||
} else {
|
||||
assert_eq!(w.player.spin_hit, None);
|
||||
assert_eq!(w.player.auto_spin_attack_ticks, 19);
|
||||
assert_eq!(w.player.pose, crate::pose::Pose::SpinAttack);
|
||||
assert_eq!(w.player.dimensions.height, 0.6);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn a_landing_glide_lasts_a_tick_so_a_jump_keeps_its_speed() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
|
||||
@@ -38,7 +38,14 @@ pub enum HRow {
|
||||
Mod(usize),
|
||||
/// Opens the directory where Horizon mods are installed.
|
||||
OpenModFolder,
|
||||
/// `shaderpacks/`'s path and a button opening it.
|
||||
ShaderPackFolder,
|
||||
/// Shader pack `i` of `OptionsUi::shader_packs` and its switch.
|
||||
ShaderPack(usize),
|
||||
}
|
||||
|
||||
/// The sidebar section listing the shader packs.
|
||||
pub const SHADER_PACKS: &str = "Shader Packs";
|
||||
/// A sidebar section: name, description, rows.
|
||||
pub struct Section {
|
||||
pub name: &'static str,
|
||||
@@ -172,6 +179,12 @@ pub const SECTIONS: &[Section] = &[
|
||||
.to_vec()
|
||||
},
|
||||
},
|
||||
Section {
|
||||
name: SHADER_PACKS,
|
||||
blurb: "Packs that redraw the world. Off is the vanilla look.",
|
||||
// The packs follow, from the folder (`horizon_rows`).
|
||||
rows: |_| vec![HRow::ShaderPackFolder],
|
||||
},
|
||||
Section {
|
||||
name: "Interface",
|
||||
blurb: "Menus and resource packs.",
|
||||
@@ -309,7 +322,15 @@ fn horizon_batch(framebuffer: [i32; 2]) -> HudBatch {
|
||||
}
|
||||
impl OptionsUi {
|
||||
fn horizon_rows(&self, s: &Settings, section: usize) -> Vec<HRow> {
|
||||
let rows = (SECTIONS[section].rows)(s);
|
||||
let mut rows = (SECTIONS[section].rows)(s);
|
||||
if SECTIONS[section].name == SHADER_PACKS {
|
||||
if self.shader_packs.packs.is_empty() {
|
||||
rows.push(HRow::Header(
|
||||
"No shader packs: put a pack's folder or .zip in this folder",
|
||||
));
|
||||
}
|
||||
rows.extend((0..self.shader_packs.packs.len()).map(HRow::ShaderPack));
|
||||
}
|
||||
let query = self.settings_search.value.to_lowercase();
|
||||
if query.is_empty() || !searchable_section(section) {
|
||||
return rows;
|
||||
@@ -511,6 +532,38 @@ impl OptionsUi {
|
||||
ui.described_row(x, y, &installed.title, "", 0.0, cost, text, cw - 60.0);
|
||||
ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, s.mods.is_on(m));
|
||||
}
|
||||
HRow::ShaderPackFolder => {
|
||||
let label = "Open Folder";
|
||||
let bw = ui.button_width(label, false).max(96.0);
|
||||
let dir = self.shader_packs.dir.display().to_string();
|
||||
ui.described_row(x, y, "Folder", "", 0.0, (0, ""), &dir, cw - bw - 24.0);
|
||||
ui.button(
|
||||
ROW + i as u64,
|
||||
[control_x - bw, y + 12.0, bw, CONTROL],
|
||||
label,
|
||||
Button::Secondary,
|
||||
true,
|
||||
);
|
||||
}
|
||||
HRow::ShaderPack(p) => {
|
||||
let (id, info) = &self.shader_packs.packs[p];
|
||||
let error = match info {
|
||||
Err(e) => Some(e.as_str()),
|
||||
Ok(_) => self
|
||||
.shader_pack_error
|
||||
.as_ref()
|
||||
.filter(|(failed, _)| failed == id)
|
||||
.map(|(_, e)| e.as_str()),
|
||||
};
|
||||
let (cost, text) = match (error, info) {
|
||||
(Some(e), _) => ((3, "Failed"), e),
|
||||
(None, Ok(info)) => ((0, ""), info.description.as_str()),
|
||||
(None, Err(_)) => unreachable!(),
|
||||
};
|
||||
ui.described_row(x, y, id, "", 0.0, cost, text, cw - 60.0);
|
||||
let on = s.horizon.shader_pack == *id;
|
||||
ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, on);
|
||||
}
|
||||
HRow::OpenModFolder => {
|
||||
ui.row(x, y, "Mod folder", "", 0.0);
|
||||
let label = "Open Folder";
|
||||
@@ -756,13 +809,7 @@ impl OptionsUi {
|
||||
return events;
|
||||
}
|
||||
match target {
|
||||
Some(Target::Nav(i)) => {
|
||||
if searchable_section(self.section) || searchable_section(i) {
|
||||
self.settings_search.set_value("");
|
||||
}
|
||||
self.section = i;
|
||||
self.hscroll = 0.0;
|
||||
}
|
||||
Some(Target::Nav(i)) => self.select_section(i),
|
||||
Some(Target::Search) => {
|
||||
self.settings_search.focused = true;
|
||||
self.settings_search.move_cursor_to_end(false);
|
||||
@@ -798,6 +845,10 @@ impl OptionsUi {
|
||||
}
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Some(HRow::Graphics(Item::Horizon(graphics_ui::H::ShaderPack), ..)) => {
|
||||
events.push(Event::ButtonClick);
|
||||
self.open_section(SHADER_PACKS);
|
||||
}
|
||||
Some(HRow::Graphics(item, ..)) => {
|
||||
item.cycle(s, right, framebuffer);
|
||||
events.push(Event::Changed);
|
||||
@@ -818,6 +869,14 @@ impl OptionsUi {
|
||||
events.push(Event::ButtonClick);
|
||||
events.push(Event::OpenModFolder);
|
||||
}
|
||||
Some(HRow::ShaderPackFolder) if !right => {
|
||||
events.push(Event::ButtonClick);
|
||||
events.push(Event::OpenShaderPackFolder);
|
||||
}
|
||||
Some(HRow::ShaderPack(p)) => {
|
||||
self.toggle_shader_pack(s, *p);
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -825,6 +884,19 @@ impl OptionsUi {
|
||||
}
|
||||
events
|
||||
}
|
||||
fn select_section(&mut self, i: usize) {
|
||||
if searchable_section(self.section) || searchable_section(i) {
|
||||
self.settings_search.set_value("");
|
||||
}
|
||||
self.section = i;
|
||||
self.hscroll = 0.0;
|
||||
}
|
||||
/// Show the sidebar section called `name`.
|
||||
fn open_section(&mut self, name: &str) {
|
||||
if let Some(i) = SECTIONS.iter().position(|s| s.name == name) {
|
||||
self.select_section(i);
|
||||
}
|
||||
}
|
||||
pub(crate) fn scroll_horizon(&mut self, amount: f32) {
|
||||
self.hscroll -= amount * 40.0;
|
||||
}
|
||||
@@ -1057,6 +1129,85 @@ mod tests {
|
||||
assert_eq!(ui.hscroll, 0.0);
|
||||
}
|
||||
|
||||
/// The Shader Packs section: the folder's path and Open Folder, a switch
|
||||
/// per pack; the Video section's Shader Pack row leads here (#941, #925).
|
||||
#[test]
|
||||
fn shader_packs_section_opens_the_folder_and_picks_a_pack() {
|
||||
let atlas = atlas();
|
||||
let framebuffer = [2560, 1440];
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("horizon-shader-section-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut options = section_ui(SHADER_PACKS);
|
||||
let mut settings = Settings::default();
|
||||
options.shader_packs.poll(dir.clone());
|
||||
assert!(matches!(
|
||||
options.horizon_rows(&settings, options.section)[..],
|
||||
[HRow::ShaderPackFolder, HRow::Header(_)]
|
||||
));
|
||||
std::fs::write(dir.join("Pack.zip"), b"").unwrap();
|
||||
options.shader_packs = Default::default();
|
||||
options.shader_packs.poll(dir.clone());
|
||||
// Click the control with hit id `id`, scrolling until it shows.
|
||||
let click = |options: &mut OptionsUi, settings: &mut Settings, id: u64| {
|
||||
for _ in 0..40 {
|
||||
let mut batch = horizon_batch(framebuffer);
|
||||
let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0));
|
||||
options.horizon_layout(settings, &mut ui, 1.0);
|
||||
if let Some(hit) = ui.hits.iter().find(|hit| hit.id == id) {
|
||||
let r = hit.rect;
|
||||
let scale = ui.density / ui.batch.scale;
|
||||
let at = ((r[0] + r[2]) * 0.5 * scale, (r[1] + r[3]) * 0.5 * scale);
|
||||
drop(ui);
|
||||
return options.click_horizon(
|
||||
settings,
|
||||
&atlas,
|
||||
at.0,
|
||||
at.1,
|
||||
framebuffer,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
}
|
||||
drop(ui);
|
||||
options.hscroll += 200.0;
|
||||
}
|
||||
panic!("no control {id}");
|
||||
};
|
||||
assert_eq!(
|
||||
click(&mut options, &mut settings, ROW),
|
||||
[Event::ButtonClick, Event::OpenShaderPackFolder]
|
||||
);
|
||||
assert_eq!(
|
||||
click(&mut options, &mut settings, ROW + 1),
|
||||
[Event::Changed]
|
||||
);
|
||||
assert_eq!(settings.horizon.shader_pack, "Pack.zip");
|
||||
click(&mut options, &mut settings, ROW + 1);
|
||||
assert_eq!(settings.horizon.shader_pack, "");
|
||||
|
||||
let mut options = section_ui("Video");
|
||||
settings.horizon.advanced = true;
|
||||
let video = SECTIONS.iter().position(|s| s.name == "Video").unwrap();
|
||||
let row = options
|
||||
.horizon_rows(&settings, video)
|
||||
.iter()
|
||||
.position(|r| {
|
||||
matches!(
|
||||
r,
|
||||
HRow::Graphics(Item::Horizon(graphics_ui::H::ShaderPack), ..)
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
click(&mut options, &mut settings, ROW + row as u64),
|
||||
[Event::ButtonClick]
|
||||
);
|
||||
assert_eq!(SECTIONS[options.section].name, SHADER_PACKS);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mods_section_opens_folder_from_its_button() {
|
||||
let atlas = atlas();
|
||||
|
||||
@@ -862,6 +862,8 @@ pub enum Page {
|
||||
Font,
|
||||
Packs,
|
||||
Mods,
|
||||
/// The shader packs in `shaderpacks/`: pick one, open the folder.
|
||||
ShaderPacks,
|
||||
/// Horizon's graphics settings (`graphics_ui`).
|
||||
Graphics,
|
||||
GraphicsAdvanced,
|
||||
@@ -888,6 +890,9 @@ enum Act {
|
||||
HorizonMenus,
|
||||
ToggleMod(usize),
|
||||
OpenModFolder,
|
||||
/// Pick shader pack `i` of `OptionsUi::shader_packs` (again: off).
|
||||
ToggleShaderPack(usize),
|
||||
OpenShaderPackFolder,
|
||||
}
|
||||
enum WKind {
|
||||
Button {
|
||||
@@ -935,6 +940,8 @@ pub enum Event {
|
||||
Packs(Vec<String>),
|
||||
OpenPackFolder,
|
||||
OpenModFolder,
|
||||
/// Create `shaderpacks/` if needed and open it.
|
||||
OpenShaderPackFolder,
|
||||
}
|
||||
/// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after
|
||||
/// the last change (`OptionInstanceSliderButton.delayedApplyAt`).
|
||||
@@ -993,6 +1000,10 @@ pub struct OptionsUi {
|
||||
/// Scroll the selected language into the middle on the next layout.
|
||||
center_language: bool,
|
||||
pub graphics: crate::graphics_ui::GraphicsUi,
|
||||
/// `shaderpacks/` and its packs, read while the Shader Packs page shows.
|
||||
pub shader_packs: crate::shader_pack::Folder,
|
||||
/// The pack that failed to load last and why (set by the game).
|
||||
pub shader_pack_error: Option<(String, String)>,
|
||||
}
|
||||
impl Default for OptionsUi {
|
||||
fn default() -> Self {
|
||||
@@ -1025,6 +1036,8 @@ impl Default for OptionsUi {
|
||||
in_world: false,
|
||||
center_language: false,
|
||||
graphics: Default::default(),
|
||||
shader_packs: Default::default(),
|
||||
shader_pack_error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1073,6 +1086,8 @@ enum Row {
|
||||
Big(Opt),
|
||||
Pair(Opt, Option<Opt>),
|
||||
Header(&'static str),
|
||||
/// A line of grey text (a path).
|
||||
Note(String),
|
||||
Buttons(Widget, Option<Widget>),
|
||||
}
|
||||
fn pairs(opts: &[Opt]) -> Vec<Row> {
|
||||
@@ -1131,6 +1146,33 @@ impl OptionsUi {
|
||||
self.graphics.reset();
|
||||
}
|
||||
}
|
||||
/// Pick shader pack `i` of the folder, or turn it off when it is the
|
||||
/// one running.
|
||||
pub(crate) fn toggle_shader_pack(&self, s: &mut Settings, i: usize) {
|
||||
let Some((id, Ok(_))) = self.shader_packs.packs.get(i) else {
|
||||
return;
|
||||
};
|
||||
let g = &mut s.horizon;
|
||||
g.shader_pack = if g.shader_pack == *id {
|
||||
String::new()
|
||||
} else {
|
||||
id.clone()
|
||||
};
|
||||
}
|
||||
pub(crate) fn shader_pack_failed(&self, id: &str) -> bool {
|
||||
self.shader_pack_error
|
||||
.as_ref()
|
||||
.is_some_and(|(e, _)| e == id)
|
||||
}
|
||||
/// Whether the Shader Packs page (or the Horizon menus' section) 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> {
|
||||
match page {
|
||||
@@ -1153,6 +1195,7 @@ impl OptionsUi {
|
||||
Page::Font => "options.font.title",
|
||||
Page::Packs => "resourcePack.title",
|
||||
Page::Mods => "Mods",
|
||||
Page::ShaderPacks => "Shader Packs",
|
||||
Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle",
|
||||
Page::Controller => "Controller Settings",
|
||||
Page::PadBinds => "Controller Binds",
|
||||
@@ -1262,6 +1305,16 @@ impl OptionsUi {
|
||||
Act::Push(Page::GraphicsAdvanced),
|
||||
)),
|
||||
)];
|
||||
rows.push(Row::Buttons(
|
||||
button(
|
||||
0.0,
|
||||
0.0,
|
||||
310.0,
|
||||
Text::literal("Shader Packs..."),
|
||||
Act::Push(Page::ShaderPacks),
|
||||
),
|
||||
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
|
||||
@@ -1450,6 +1503,32 @@ impl OptionsUi {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Page::ShaderPacks => {
|
||||
let folder = &self.shader_packs;
|
||||
let mut rows = vec![Row::Note(folder.dir.display().to_string())];
|
||||
if folder.packs.is_empty() {
|
||||
rows.push(Row::Header(
|
||||
"No shader packs: put a pack's folder or .zip in this folder",
|
||||
));
|
||||
}
|
||||
for (i, (id, info)) in folder.packs.iter().enumerate() {
|
||||
let on = s.horizon.shader_pack == *id;
|
||||
let mut label = Text::literal(format!("{id}: ")).append(on_off(on));
|
||||
if info.is_err() || self.shader_pack_failed(id) {
|
||||
label = label.append(" (Failed)");
|
||||
}
|
||||
let widget = button(0.0, 0.0, 310.0, label, Act::ToggleShaderPack(i));
|
||||
rows.push(Row::Buttons(
|
||||
if info.is_ok() {
|
||||
widget
|
||||
} else {
|
||||
inactive(widget)
|
||||
},
|
||||
None,
|
||||
));
|
||||
}
|
||||
rows
|
||||
}
|
||||
_ => {
|
||||
let _ = s;
|
||||
Vec::new()
|
||||
@@ -1849,6 +1928,21 @@ impl OptionsUi {
|
||||
});
|
||||
y += padding + 18.0;
|
||||
}
|
||||
Row::Note(text) => {
|
||||
out.push(Widget {
|
||||
x: 0.0,
|
||||
y: y + 4.0,
|
||||
w,
|
||||
h: 9.0,
|
||||
kind: WKind::Text {
|
||||
text: Text::literal(text),
|
||||
color: 0xFFA0A0A0,
|
||||
centered: true,
|
||||
},
|
||||
list: false,
|
||||
});
|
||||
y += 16.0;
|
||||
}
|
||||
Row::Big(opt) => {
|
||||
out.push(option_widget(s, opt, cx - 155.0, y + 2.0, 310.0));
|
||||
y += 25.0;
|
||||
@@ -1875,13 +1969,20 @@ impl OptionsUi {
|
||||
}
|
||||
content = y + self.scroll - top + 2.0;
|
||||
out[list_start..].iter_mut().for_each(|w| w.list = true);
|
||||
if page == Page::Mods {
|
||||
let folder = match page {
|
||||
Page::Mods => Some(("Open Mod Folder", Act::OpenModFolder)),
|
||||
Page::ShaderPacks => {
|
||||
Some(("Open Shader Pack Folder", Act::OpenShaderPackFolder))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some((label, act)) = folder {
|
||||
out.push(button(
|
||||
cx - 154.0,
|
||||
h - 27.0,
|
||||
150.0,
|
||||
Text::literal("Open Mod Folder"),
|
||||
Act::OpenModFolder,
|
||||
Text::literal(label),
|
||||
act,
|
||||
));
|
||||
out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done));
|
||||
} else {
|
||||
@@ -1911,6 +2012,9 @@ impl OptionsUi {
|
||||
atlas: &HudAtlas,
|
||||
cursor: (f32, f32),
|
||||
) {
|
||||
if self.shader_packs_shown() {
|
||||
self.shader_packs.poll(crate::shader_pack::folder());
|
||||
}
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
if let Some(error) = &self.resource_error {
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.in_world);
|
||||
@@ -2210,6 +2314,7 @@ impl OptionsUi {
|
||||
Action::ButtonClick => events.push(Event::ButtonClick),
|
||||
Action::Changed => events.push(Event::Changed),
|
||||
Action::OpenAdvanced => self.push(Page::GraphicsAdvanced),
|
||||
Action::OpenShaderPacks => self.push(Page::ShaderPacks),
|
||||
Action::OpenSimple => {
|
||||
if self.stack.len() >= 2
|
||||
&& self.stack[self.stack.len() - 2] == Page::Graphics
|
||||
@@ -2377,6 +2482,11 @@ impl OptionsUi {
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Act::OpenModFolder => events.push(Event::OpenModFolder),
|
||||
Act::ToggleShaderPack(i) => {
|
||||
self.toggle_shader_pack(s, i);
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder),
|
||||
Act::None => {}
|
||||
}
|
||||
}
|
||||
@@ -2831,6 +2941,109 @@ mod tests {
|
||||
assert!(ui.resource_error.is_none());
|
||||
}
|
||||
|
||||
/// The Shader Packs page (Video Settings > Shader Packs..., or the
|
||||
/// Shader Pack row of Advanced graphics): the folder's path, Open Shader
|
||||
/// Pack Folder, and a switch per pack (#941, #925).
|
||||
#[test]
|
||||
fn classic_shader_packs_page_shows_the_folder_and_picks_a_pack() {
|
||||
let atlas = atlas();
|
||||
let mut s = Settings::default();
|
||||
let mut ui = OptionsUi::default();
|
||||
let size = (480.0, 240.0);
|
||||
let dir = std::env::temp_dir().join(format!("horizon-shaderpacks-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let find = |ui: &mut OptionsUi, s: &Settings, act: &dyn Fn(&Act) -> bool| {
|
||||
ui.layout(s, size.0, size.1)
|
||||
.0
|
||||
.into_iter()
|
||||
.find(|w| matches!(&w.kind, WKind::Button { act: a, active: true, .. } if act(a)))
|
||||
};
|
||||
ui.show(Page::Video);
|
||||
let open = find(&mut ui, &s, &|a| *a == Act::Push(Page::ShaderPacks)).unwrap();
|
||||
ui.click(
|
||||
&mut s,
|
||||
&atlas,
|
||||
open.x + 1.0,
|
||||
open.y + 1.0,
|
||||
size,
|
||||
[480, 240],
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert_eq!(ui.page(), Page::ShaderPacks);
|
||||
|
||||
ui.shader_packs.poll(dir.clone());
|
||||
let empty = ui.layout(&s, size.0, size.1).0;
|
||||
let path = dir.display().to_string();
|
||||
for line in [path.as_str(), "No shader packs"] {
|
||||
assert!(
|
||||
empty.iter().any(
|
||||
|w| matches!(&w.kind, WKind::Text { text, .. } if text.plain().contains(line))
|
||||
),
|
||||
"{line}"
|
||||
);
|
||||
}
|
||||
let folder = find(&mut ui, &s, &|a| *a == Act::OpenShaderPackFolder).unwrap();
|
||||
assert_eq!(
|
||||
ui.click(
|
||||
&mut s,
|
||||
&atlas,
|
||||
folder.x + 1.0,
|
||||
folder.y + 1.0,
|
||||
size,
|
||||
[480, 240],
|
||||
false,
|
||||
false
|
||||
),
|
||||
vec![Event::ButtonClick, Event::OpenShaderPackFolder]
|
||||
);
|
||||
|
||||
std::fs::write(dir.join("Pack.zip"), b"").unwrap();
|
||||
ui.shader_packs = Default::default();
|
||||
ui.shader_packs.poll(dir.clone());
|
||||
let pack = find(&mut ui, &s, &|a| *a == Act::ToggleShaderPack(0)).unwrap();
|
||||
let events = ui.click(
|
||||
&mut s,
|
||||
&atlas,
|
||||
pack.x + 1.0,
|
||||
pack.y + 1.0,
|
||||
size,
|
||||
[480, 240],
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert!(events.contains(&Event::Changed));
|
||||
assert_eq!(s.horizon.shader_pack, "Pack.zip");
|
||||
ui.shader_pack_error = Some(("Pack.zip".into(), "broken".into()));
|
||||
let label = |ui: &mut OptionsUi, s: &Settings| match find(ui, s, &|a| {
|
||||
*a == Act::ToggleShaderPack(0)
|
||||
})
|
||||
.unwrap()
|
||||
.kind
|
||||
{
|
||||
WKind::Button { label, .. } => label.plain(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert!(
|
||||
label(&mut ui, &s).ends_with("(Failed)"),
|
||||
"{}",
|
||||
label(&mut ui, &s)
|
||||
);
|
||||
ui.click(
|
||||
&mut s,
|
||||
&atlas,
|
||||
pack.x + 1.0,
|
||||
pack.y + 1.0,
|
||||
size,
|
||||
[480, 240],
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert_eq!(s.horizon.shader_pack, "", "a second click turns it off");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_mods_page_toggles_mods_and_keeps_dev_and_invalid_entries_inactive() {
|
||||
let atlas = atlas();
|
||||
|
||||
@@ -14,6 +14,7 @@ pub enum Pose {
|
||||
Crouching,
|
||||
Swimming,
|
||||
FallFlying,
|
||||
SpinAttack,
|
||||
}
|
||||
impl Pose {
|
||||
pub fn name(self) -> &'static str {
|
||||
@@ -22,13 +23,14 @@ impl Pose {
|
||||
Self::Crouching => "CROUCHING",
|
||||
Self::Swimming => "SWIMMING",
|
||||
Self::FallFlying => "FALL_FLYING",
|
||||
Self::SpinAttack => "SPIN_ATTACK",
|
||||
}
|
||||
}
|
||||
pub fn dimensions(self, scale: f32) -> Dimensions {
|
||||
let (height, eye_height) = match self {
|
||||
Self::Standing => (1.8, 1.62),
|
||||
Self::Crouching => (1.5, 1.27),
|
||||
Self::Swimming | Self::FallFlying => (0.6, 0.4),
|
||||
Self::Swimming | Self::FallFlying | Self::SpinAttack => (0.6, 0.4),
|
||||
};
|
||||
Dimensions {
|
||||
width: 0.6 * scale,
|
||||
@@ -98,11 +100,13 @@ impl MotionWorld<'_, '_, '_> {
|
||||
if !self.can_fit_pose(Pose::Swimming)? {
|
||||
return Ok(());
|
||||
}
|
||||
// Player.getDesiredPose: swimming before gliding.
|
||||
// Player.getDesiredPose: swimming, gliding, Riptide's spin.
|
||||
let desired = if self.player.swimming {
|
||||
Pose::Swimming
|
||||
} else if self.player.fall_flying {
|
||||
Pose::FallFlying
|
||||
} else if self.player.auto_spin_attack_ticks > 0 {
|
||||
Pose::SpinAttack
|
||||
} else if self.player.shift_key_down && !self.player.flying {
|
||||
Pose::Crouching
|
||||
} else {
|
||||
|
||||
@@ -171,11 +171,41 @@ pub fn list(dir: &Path) -> Vec<(String, Result<Info, String>)> {
|
||||
packs
|
||||
}
|
||||
|
||||
/// `shaderpacks/` beside `options.txt` (the game's working folder: the game
|
||||
/// home, not the launcher's version folder).
|
||||
pub fn folder() -> PathBuf {
|
||||
std::env::current_dir().unwrap_or_default().join(DIR)
|
||||
}
|
||||
|
||||
/// `shaderpacks/` and its packs as the Shader Packs page lists them, read
|
||||
/// again at most once a second while the page is open, so a pack dropped
|
||||
/// into the folder shows up.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Folder {
|
||||
pub dir: PathBuf,
|
||||
pub packs: Vec<(String, Result<Info, String>)>,
|
||||
read: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
impl Folder {
|
||||
pub fn poll(&mut self, dir: PathBuf) {
|
||||
let fresh = self
|
||||
.read
|
||||
.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(1));
|
||||
if fresh && self.dir == dir {
|
||||
return;
|
||||
}
|
||||
self.packs = list(&dir);
|
||||
self.dir = dir;
|
||||
self.read = Some(std::time::Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
/// A Java pack has no manifest: its name is its file name.
|
||||
fn java_info(name: String) -> Info {
|
||||
Info {
|
||||
name,
|
||||
description: String::new(),
|
||||
description: "Iris/OptiFine pack: its full-screen passes run.".into(),
|
||||
authors: Vec::new(),
|
||||
version: String::new(),
|
||||
license: String::new(),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Named timings within a frame, for finding what makes a frame slow:
|
||||
//! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time
|
||||
//! exceeds MS milliseconds, and of every server tick (dedicated or
|
||||
//! integrated) longer than MS. Costs one clock read per span when enabled
|
||||
//! and a relaxed load otherwise.
|
||||
//! integrated) longer than MS. Each span keeps its wall time and the
|
||||
//! thread's CPU time inside it, so a span that waited (for a lock, the GPU
|
||||
//! or a core on a busy machine) shows apart from one that worked. Costs two
|
||||
//! clock reads per span when enabled and a relaxed load otherwise.
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
@@ -11,7 +13,15 @@ use std::{
|
||||
|
||||
static ENABLED: AtomicBool = AtomicBool::new(false);
|
||||
thread_local! {
|
||||
static SPANS: RefCell<Vec<(&'static str, f32)>> = const { RefCell::new(Vec::new()) };
|
||||
static SPANS: RefCell<Vec<Span>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// A named timing: wall milliseconds and the thread's CPU milliseconds in it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Span {
|
||||
pub name: &'static str,
|
||||
pub ms: f32,
|
||||
pub cpu_ms: f32,
|
||||
}
|
||||
|
||||
pub fn enable(on: bool) {
|
||||
@@ -23,10 +33,13 @@ pub fn time<T>(name: &'static str, f: impl FnOnce() -> T) -> T {
|
||||
if !ENABLED.load(Ordering::Relaxed) {
|
||||
return f();
|
||||
}
|
||||
let started = Instant::now();
|
||||
let (started, cpu) = (Instant::now(), thread_cpu());
|
||||
let out = f();
|
||||
let ms = started.elapsed().as_secs_f32() * 1000.0;
|
||||
SPANS.with(|s| s.borrow_mut().push((name, ms)));
|
||||
let cpu_ms = thread_cpu()
|
||||
.zip(cpu)
|
||||
.map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0);
|
||||
SPANS.with(|s| s.borrow_mut().push(Span { name, ms, cpu_ms }));
|
||||
out
|
||||
}
|
||||
/// The CPU time this thread has used, where the platform tells it: a tick
|
||||
@@ -42,21 +55,84 @@ pub fn thread_cpu() -> Option<Duration> {
|
||||
None
|
||||
}
|
||||
/// The frame's spans, summed by name, slowest first; clears them.
|
||||
pub fn take() -> Vec<(&'static str, f32)> {
|
||||
pub fn take() -> Vec<Span> {
|
||||
let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut()));
|
||||
let mut sums: Vec<(&'static str, f32)> = Vec::new();
|
||||
for (name, ms) in spans {
|
||||
match sums.iter_mut().find(|(n, _)| *n == name) {
|
||||
Some(entry) => entry.1 += ms,
|
||||
None => sums.push((name, ms)),
|
||||
let mut sums: Vec<Span> = Vec::new();
|
||||
for span in spans {
|
||||
match sums.iter_mut().find(|s| s.name == span.name) {
|
||||
Some(sum) => {
|
||||
sum.ms += span.ms;
|
||||
sum.cpu_ms += span.cpu_ms;
|
||||
}
|
||||
None => sums.push(span),
|
||||
}
|
||||
}
|
||||
sums.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
sums.sort_by(|a, b| b.ms.total_cmp(&a.ms));
|
||||
sums
|
||||
}
|
||||
/// `name wall` for spans of at least 0.5 ms, with `/cpu` when the thread
|
||||
/// worked for less than nine tenths of it: the slow-frame and slow-tick lines.
|
||||
pub fn describe(spans: &[Span]) -> String {
|
||||
let list: Vec<String> = spans
|
||||
.iter()
|
||||
.filter(|s| s.ms >= 0.5)
|
||||
.map(|s| {
|
||||
if s.cpu_ms < s.ms * 0.9 {
|
||||
format!("{} {:.1}/{:.1}", s.name, s.ms, s.cpu_ms)
|
||||
} else {
|
||||
format!("{} {:.1}", s.name, s.ms)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
list.join(", ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Span;
|
||||
|
||||
/// Spans of one name add up; a span the thread spent mostly waiting
|
||||
/// shows its CPU time after the wall time, short ones are left out.
|
||||
#[test]
|
||||
fn spans_sum_by_name_and_show_waits() {
|
||||
super::SPANS.with(|s| {
|
||||
s.borrow_mut().extend([
|
||||
Span {
|
||||
name: "tick",
|
||||
ms: 2.0,
|
||||
cpu_ms: 2.0,
|
||||
},
|
||||
Span {
|
||||
name: "submit",
|
||||
ms: 30.0,
|
||||
cpu_ms: 0.2,
|
||||
},
|
||||
Span {
|
||||
name: "tick",
|
||||
ms: 3.0,
|
||||
cpu_ms: 2.9,
|
||||
},
|
||||
Span {
|
||||
name: "hud",
|
||||
ms: 0.3,
|
||||
cpu_ms: 0.3,
|
||||
},
|
||||
]);
|
||||
});
|
||||
let spans = super::take();
|
||||
assert_eq!(
|
||||
spans[0],
|
||||
Span {
|
||||
name: "submit",
|
||||
ms: 30.0,
|
||||
cpu_ms: 0.2
|
||||
}
|
||||
);
|
||||
assert_eq!((spans[1].name, spans[1].ms), ("tick", 5.0));
|
||||
assert_eq!(super::describe(&spans), "submit 30.0/0.2, tick 5.0");
|
||||
assert!(super::take().is_empty());
|
||||
}
|
||||
|
||||
/// The thread's CPU clock moves with work done on it, not with time
|
||||
/// spent asleep.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The game's part in opt-in data collection (`horizon_telemetry`, docs/telemetry.md). When the
|
||||
//! player allows it, the game keeps a scrubbed crash report, or a play session's performance
|
||||
//! summary, in the outbox. It never sends anything itself: the launcher does, at its next start.
|
||||
//! summary, in the outbox. It never sends those itself: the launcher does, at its next start (the
|
||||
//! game's only sending is the anonymous "I'm playing" ping, `heartbeat.rs`).
|
||||
//! Without the player's yes for that kind nothing is kept, and crash-reports/ stays local.
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
@@ -75,7 +76,7 @@ pub fn system() -> System {
|
||||
system
|
||||
}
|
||||
|
||||
/// The release (`v2026.10.15`), or the client's crate version for a build from source.
|
||||
/// The release (`v0.2.3`), or the client's crate version for a build from source.
|
||||
pub fn version() -> String {
|
||||
crate::crash::release_tag().unwrap_or_else(|| format!("dev {}", env!("CARGO_PKG_VERSION")))
|
||||
}
|
||||
|
||||
@@ -16,11 +16,14 @@ struct Globals {
|
||||
fog_ends: vec4<f32>,
|
||||
// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
|
||||
end_portal_sprites: array<vec4<f32>, 2>,
|
||||
// x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000)
|
||||
// x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000), z: how many
|
||||
// dynamic_lights are set
|
||||
time: vec4<f32>,
|
||||
// Atlas rect of the current destroy stage (read by entity.wgsl).
|
||||
crumbling_sprite: vec4<f32>,
|
||||
outline_params: vec4<f32>,
|
||||
// Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs).
|
||||
dynamic_lights: array<vec4<f32>, 16>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> globals: Globals;
|
||||
@group(0) @binding(1) var sprites: texture_2d_array<f32>;
|
||||
@@ -67,6 +70,18 @@ struct TerrainOut {
|
||||
@location(3) spherical: f32,
|
||||
@location(4) cylindrical: f32,
|
||||
}
|
||||
// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units
|
||||
// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one
|
||||
// level less per block. time.z of them are set: none when the extra is off, so no loop runs.
|
||||
fn dynamic_block_light(pos: vec3<f32>) -> f32 {
|
||||
let count = min(u32(globals.time.z), 16u);
|
||||
var level = 0.0;
|
||||
for (var i = 0u; i < count; i++) {
|
||||
let l = globals.dynamic_lights[i];
|
||||
level = max(level, l.w - distance(pos, l.xyz));
|
||||
}
|
||||
return level * 16.0;
|
||||
}
|
||||
fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> {
|
||||
let uv = vec2(block, sky) * 16.0;
|
||||
return textureSampleLevel(lightmap, lightmap_sampler,
|
||||
@@ -105,7 +120,8 @@ fn terrain_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f3
|
||||
out.clip = globals.view_proj * vec4(pos, 1.0);
|
||||
out.uv = uv;
|
||||
out.layer = layer;
|
||||
out.color = color * sample_lightmap(f32(light.x) / 16.0, f32(light.y) / 16.0);
|
||||
let block = max(f32(light.y), dynamic_block_light(pos));
|
||||
out.color = color * sample_lightmap(f32(light.x) / 16.0, block / 16.0);
|
||||
out.spherical = length(pos);
|
||||
out.cylindrical = max(length(pos.xz), abs(pos.y));
|
||||
return out;
|
||||
|
||||
@@ -17,6 +17,7 @@ pub mod storage;
|
||||
pub mod text;
|
||||
pub mod ticks;
|
||||
|
||||
pub mod release;
|
||||
pub mod version;
|
||||
|
||||
pub use version::VANILLA_VERSION;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Which Horizon release this build is (docs/versioning.md). Not Minecraft's version: that is
|
||||
//! [`crate::version`], generated from the game's own files.
|
||||
|
||||
/// The release's version (`0.2.3`, no `v`): release.yml builds every release with `HORIZON_VERSION`
|
||||
/// set from its tag, so there are no version-bump commits. None for a build from source.
|
||||
pub const RELEASE: Option<&str> = match option_env!("HORIZON_VERSION") {
|
||||
Some(version) if !version.is_empty() => Some(version),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
/// [`RELEASE`], or this crate's Cargo.toml version for a build from source: what `--version`, user
|
||||
/// agents and reports say.
|
||||
pub const VERSION: &str = match RELEASE {
|
||||
Some(version) => version,
|
||||
None => env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn the_version_is_the_release_or_the_crate() {
|
||||
assert_eq!(
|
||||
super::RELEASE,
|
||||
option_env!("HORIZON_VERSION").filter(|v| !v.is_empty())
|
||||
);
|
||||
assert_eq!(
|
||||
super::VERSION,
|
||||
super::RELEASE.unwrap_or(env!("CARGO_PKG_VERSION"))
|
||||
);
|
||||
assert!(!super::VERSION.starts_with('v'));
|
||||
}
|
||||
}
|
||||
@@ -707,7 +707,8 @@ pub fn carry(
|
||||
let mut biome_conventions = BTreeSet::new();
|
||||
let set_tags = crate::worldgen::structure_set_tags(&mut zip);
|
||||
let piece_counts = crate::worldgen::piece_counts(&mut zip);
|
||||
let processor_data = crate::processors::ProcessorData::read(&mut zip);
|
||||
let mut processor_data = crate::processors::ProcessorData::read(&mut zip);
|
||||
processor_data.mark_loaded(loaded);
|
||||
report.namespaces = extra_namespaces(&mut zip, id, pack.mods);
|
||||
let owned: Vec<&str> = std::iter::once(id.as_str())
|
||||
.chain(report.namespaces.iter().map(String::as_str))
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
//! `condition` become the game's `horizon:apply_random` and
|
||||
//! `horizon:condition`, with the lists inside them carried the same way,
|
||||
//! and its `set_block` (simple or weighted states) `horizon:set_block`.
|
||||
//! - Repurposed Structures' mineshaft sky view becomes the game's
|
||||
//! `horizon:mineshaft_sky_view`.
|
||||
//! - Choice Theorem's Overhauled Village's `modular_compat` runs another
|
||||
//! list only when the mod it names is loaded: that list is written in its
|
||||
//! place when the mod is ported along, and it is taken out (a no-op, as in
|
||||
//! the mod) when it is not.
|
||||
//!
|
||||
//! What is not here is taken out of its list later and counted
|
||||
//! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an
|
||||
@@ -37,9 +43,37 @@ pub struct ProcessorData {
|
||||
pub replace_vanilla: BTreeSet<(String, String)>,
|
||||
/// The mod's processor lists by id, for Lithostitched's references.
|
||||
pub lists: BTreeMap<String, Value>,
|
||||
/// The mods named by its `ctov:modular_compat` processors that are
|
||||
/// ported along ([`Self::mark_loaded`]).
|
||||
pub compat_loaded: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// Choice Theorem's Overhauled Village's processor that runs the list
|
||||
/// `reference` when mod `modid` is loaded (ModularCompatProcessor).
|
||||
const MODULAR_COMPAT: &str = "ctov:modular_compat";
|
||||
|
||||
impl ProcessorData {
|
||||
/// Notes which mods its compat processors name are `loaded`.
|
||||
pub fn mark_loaded(&mut self, loaded: &dyn Fn(&str) -> bool) {
|
||||
fn walk(v: &Value, out: &mut BTreeSet<String>) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT) {
|
||||
if let Some(id) = o.get("modid").and_then(Value::as_str) {
|
||||
out.insert(id.to_owned());
|
||||
}
|
||||
}
|
||||
o.values().for_each(|v| walk(v, out));
|
||||
}
|
||||
Value::Array(a) => a.iter().for_each(|v| walk(v, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut named = BTreeSet::new();
|
||||
self.lists.values().for_each(|l| walk(l, &mut named));
|
||||
self.compat_loaded = named.into_iter().filter(|m| loaded(m)).collect();
|
||||
}
|
||||
|
||||
pub fn read<R: Read + Seek>(zip: &mut zip::ZipArchive<R>) -> Self {
|
||||
let mut out = Self::default();
|
||||
for i in 0..zip.len() {
|
||||
@@ -408,6 +442,17 @@ fn references(
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
let mut changed = false;
|
||||
for p in list {
|
||||
if p["processor_type"] == MODULAR_COMPAT && depth < 8 {
|
||||
*carried.entry(MODULAR_COMPAT.into()).or_default() += 1;
|
||||
changed = true;
|
||||
let loaded = p["modid"]
|
||||
.as_str()
|
||||
.is_some_and(|m| data.compat_loaded.contains(m));
|
||||
if let Some(inner) = loaded.then(|| referenced(&p["reference"], data)).flatten() {
|
||||
out.extend(references(inner, data, carried, depth + 1).0);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let named = (p["processor_type"] == "lithostitched:reference" && depth < 8)
|
||||
.then(|| referenced(&p["processor_lists"], data))
|
||||
.flatten();
|
||||
@@ -491,6 +536,10 @@ fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option<Vec<Value>> {
|
||||
"repurposed_structures:waterlogging_when_replacing_water_processor" => {
|
||||
vec![json!({"processor_type": "horizon:waterlog_in_world_water"})]
|
||||
}
|
||||
// Its mineshafts: nothing above the ocean floor but grounded rails.
|
||||
"repurposed_structures:mineshaft_sky_view_processor" => {
|
||||
vec![json!({"processor_type": "horizon:mineshaft_sky_view"})]
|
||||
}
|
||||
"moogs_structures:vanilla_loot_swap_processor" => {
|
||||
let key = (
|
||||
p["modid"].as_str()?.to_owned(),
|
||||
@@ -1344,7 +1393,8 @@ mod tests {
|
||||
#[test]
|
||||
fn repurposed_waterlogging_follows_the_world() {
|
||||
let mut list = json!({"processors": [{"processor_type":
|
||||
"repurposed_structures:waterlogging_when_replacing_water_processor"}]});
|
||||
"repurposed_structures:waterlogging_when_replacing_water_processor"},
|
||||
{"processor_type": "repurposed_structures:mineshaft_sky_view_processor"}]});
|
||||
let mut carried = BTreeMap::new();
|
||||
assert!(carry(
|
||||
"processor_list",
|
||||
@@ -1354,7 +1404,8 @@ mod tests {
|
||||
));
|
||||
assert_eq!(
|
||||
list["processors"],
|
||||
json!([{"processor_type": "horizon:waterlog_in_world_water"}])
|
||||
json!([{"processor_type": "horizon:waterlog_in_world_water"},
|
||||
{"processor_type": "horizon:mineshaft_sky_view"}])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1391,6 +1442,27 @@ mod tests {
|
||||
assert_eq!(p[1]["processor_type"], "lithostitched:block_swap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modular_compat_runs_its_list_only_with_its_mod() {
|
||||
let mut data = ProcessorData::default();
|
||||
let swap = json!({"processor_type": "minecraft:rule", "rules": []});
|
||||
data.lists
|
||||
.insert("v:house_ns".into(), json!({"processors": [swap.clone()]}));
|
||||
let compat = |m: &str| json!({"processor_type": "ctov:modular_compat", "modid": m, "reference": "v:house_ns"});
|
||||
let gravity = json!({"processor_type": "minecraft:gravity"});
|
||||
data.lists.insert(
|
||||
"v:house".into(),
|
||||
json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}),
|
||||
);
|
||||
data.mark_loaded(&|m| m == "ns");
|
||||
assert_eq!(data.compat_loaded, BTreeSet::from(["ns".to_owned()]));
|
||||
let mut v = json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]});
|
||||
let mut carried = BTreeMap::new();
|
||||
assert!(carry("processor_list", &mut v, &data, &mut carried));
|
||||
assert_eq!(v, json!({"processors": [swap, gravity]}));
|
||||
assert_eq!(carried["ctov:modular_compat"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lithostitched_references_are_written_in() {
|
||||
let mut data = data();
|
||||
|
||||
@@ -86,6 +86,31 @@ const YUNG_REPLACES: [(&str, &str); 7] = [
|
||||
("betterfortresses:fortress", "minecraft:fortress"),
|
||||
("bettermineshafts:mineshaft_", "minecraft:mineshaft"),
|
||||
];
|
||||
/// Mo' Structures' placement (`mostructures:type`) takes its spacing and
|
||||
/// separation from the mod's config, not its files: the defaults it writes
|
||||
/// (MoStructuresConfig), by config key, as (spacing, separation).
|
||||
const MO_SPREADS: [(&str, i64, i64); 17] = [
|
||||
("abandoned_church", 33, 20),
|
||||
("air_balloon", 22, 12),
|
||||
("barn_house", 32, 16),
|
||||
("big_pyramid", 32, 25),
|
||||
("ice_tower", 28, 20),
|
||||
("jungle_pyramid", 25, 22),
|
||||
("killer_bunny_castle", 32, 22),
|
||||
("lighthouse", 24, 14),
|
||||
("moai", 17, 15),
|
||||
("pillager_factory", 34, 16),
|
||||
("pillager_mines", 40, 27),
|
||||
("pirate_ship", 32, 16),
|
||||
("tavern", 26, 16),
|
||||
("the_castle_in_the_sky", 32, 22),
|
||||
("villager_market", 32, 16),
|
||||
("villager_tower", 26, 16),
|
||||
("sphinx", 24, 16),
|
||||
];
|
||||
/// Mo' Structures keeps a start out of this many chunks around a start of
|
||||
/// each set in its `structure_set_to_avoid`.
|
||||
const MO_AVOID_CHUNKS: i64 = 3;
|
||||
/// Moog's Structure Lib spreads its structures 1.65 times as far apart as
|
||||
/// its files say (AdvancedRandomSpread's constructor).
|
||||
const MOOGS_SPACING: f64 = 1.65;
|
||||
@@ -510,12 +535,44 @@ fn upgrade_types(
|
||||
v["type"] = "minecraft:jigsaw".into();
|
||||
true
|
||||
}
|
||||
// Mo' Structures' ModStructure: vanilla's jigsaw that starts only
|
||||
// where the terrain under the 5×5 chunks around varies by no
|
||||
// more than `heightRange` blocks (-1: anywhere).
|
||||
Some("mostructures:generic") => {
|
||||
let range = v
|
||||
.as_object_mut()
|
||||
.and_then(|o| o.remove("heightRange"))
|
||||
.and_then(|r| r.as_i64())
|
||||
.unwrap_or(-1);
|
||||
if range >= 0 {
|
||||
v["horizon:start_checks"] =
|
||||
serde_json::json!({"terrain_radius": 2, "terrain_range": range});
|
||||
}
|
||||
v["type"] = "minecraft:jigsaw".into();
|
||||
true
|
||||
}
|
||||
// Formations' SimpleStructure: its pool and placement, laid out
|
||||
// by the game (`horizon_world::worldgen::structure::formations`).
|
||||
Some("formations:simple") => {
|
||||
v["type"] = "horizon:formations".into();
|
||||
true
|
||||
}
|
||||
// Its PiecedStructure: the same start, then vanilla's jigsaw
|
||||
// (`horizon:pieced`).
|
||||
Some("formations:pieced") => {
|
||||
let Some(o) = v.as_object_mut() else {
|
||||
return false;
|
||||
};
|
||||
let pool = o.remove("start_pool").unwrap_or_default();
|
||||
let mut pieced = serde_json::Map::new();
|
||||
for k in ["max_depth", "max_distance_from_center"] {
|
||||
pieced.insert(k.into(), o.remove(k).unwrap_or_default());
|
||||
}
|
||||
o.insert("template".into(), pool);
|
||||
o.insert("horizon:pieced".into(), pieced.into());
|
||||
o.insert("type".into(), "horizon:formations".into());
|
||||
true
|
||||
}
|
||||
Some(t) if !t.starts_with("minecraft:") => {
|
||||
unsupported(t);
|
||||
false
|
||||
@@ -533,6 +590,7 @@ fn upgrade_types(
|
||||
p["type"] = "minecraft:random_spread".into();
|
||||
true
|
||||
}
|
||||
Some("mostructures:type") => mo_placement(&mut v["placement"], lost),
|
||||
Some(t) if YUNG_SPREADS.contains(&t) => {
|
||||
let t = t.to_owned();
|
||||
yung_placement(&t, &mut v["placement"], set_tags, lost);
|
||||
@@ -1022,6 +1080,41 @@ fn placement_rules(
|
||||
}
|
||||
}
|
||||
|
||||
/// Mo' Structures' placement as vanilla's random spread: the spacing and
|
||||
/// separation of its config key, and its sets to avoid as
|
||||
/// `horizon:exclusion_zone` tested by their spread alone
|
||||
/// (ModStructurePlacement.exclusionZoneCheck). A key the config does not
|
||||
/// have fails the mod's codec, and the set stays as it is.
|
||||
fn mo_placement(p: &mut Value, lost: &mut BTreeMap<String, usize>) -> bool {
|
||||
let key = p["config_key"].as_str().unwrap_or_default();
|
||||
let Some(&(_, spacing, separation)) = MO_SPREADS.iter().find(|(k, ..)| *k == key) else {
|
||||
*lost.entry("config_key".into()).or_default() += 1;
|
||||
return false;
|
||||
};
|
||||
let Some(o) = p.as_object_mut() else {
|
||||
return false;
|
||||
};
|
||||
o.remove("config_key");
|
||||
o.insert("spacing".into(), spacing.into());
|
||||
o.insert("separation".into(), separation.into());
|
||||
let avoid = o.remove("structure_set_to_avoid");
|
||||
let sets: Vec<Value> = avoid
|
||||
.iter()
|
||||
.flat_map(|a| a.as_array().into_iter().flatten())
|
||||
.filter(|s| s.is_string())
|
||||
.cloned()
|
||||
.collect();
|
||||
if !sets.is_empty() {
|
||||
o.insert(
|
||||
"horizon:exclusion_zone".into(),
|
||||
serde_json::json!({"other_sets": sets, "chunk_count": MO_AVOID_CHUNKS,
|
||||
"their_zones": false}),
|
||||
);
|
||||
}
|
||||
o.insert("type".into(), "minecraft:random_spread".into());
|
||||
true
|
||||
}
|
||||
|
||||
/// One of YUNG's placements as vanilla's random spread with `horizon:` keys:
|
||||
/// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples'
|
||||
/// ocean and river search (findBiomeHorizontal around the chunk's middle
|
||||
@@ -1222,6 +1315,21 @@ mod tests {
|
||||
|
||||
const NO_TAGS: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
|
||||
#[test]
|
||||
fn formations_pieced_structure_keeps_its_jigsaw() {
|
||||
let mut v = json!({"type": "formations:pieced", "start_pool": "fo:fountain/fountains",
|
||||
"max_depth": 2, "max_distance_from_center": 116, "placement": "surface"});
|
||||
let mut report = Upgrade::default();
|
||||
assert!(upgrade("structure", &mut v, &mut report, &BTreeMap::new()));
|
||||
assert_eq!(
|
||||
v,
|
||||
json!({"type": "horizon:formations", "template": "fo:fountain/fountains",
|
||||
"placement": "surface",
|
||||
"horizon:pieced": {"max_depth": 2, "max_distance_from_center": 116}})
|
||||
);
|
||||
assert!(report.unsupported.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formations_become_the_games() {
|
||||
let mut report = Upgrade::default();
|
||||
@@ -1247,12 +1355,7 @@ mod tests {
|
||||
(json!(6), json!(1))
|
||||
);
|
||||
assert!(e(0).get("ground_level").is_none());
|
||||
// The pieced structure stays out.
|
||||
let mut pieced = json!({"type": "formations:pieced", "start_pool": "f:p", "max_depth": 2,
|
||||
"max_distance_from_center": 40, "placement": "surface", "biomes": "#f:x"});
|
||||
assert!(!upgrade("structure", &mut pieced, &mut report, &NO_TAGS));
|
||||
assert_eq!(report.unsupported.get("formations:pieced"), Some(&1));
|
||||
assert_eq!(report.unsupported.len(), 1);
|
||||
assert!(report.unsupported.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1385,6 +1488,71 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mo_structures_become_vanillas_jigsaw_and_spread() {
|
||||
let mut report = Upgrade::default();
|
||||
let mut s = json!({"type": "mostructures:generic", "start_pool": "mostructures:a/base",
|
||||
"size": 7, "heightRange": 25, "use_expansion_hack": true,
|
||||
"start_height": {"absolute": 0}, "max_distance_from_center": 80});
|
||||
assert!(upgrade("structure", &mut s, &mut report, &BTreeMap::new()));
|
||||
assert_eq!(s["type"], "minecraft:jigsaw");
|
||||
assert!(s.get("heightRange").is_none());
|
||||
assert_eq!(
|
||||
s["horizon:start_checks"],
|
||||
json!({"terrain_radius": 2, "terrain_range": 25})
|
||||
);
|
||||
let mut anywhere = json!({"type": "mostructures:generic", "heightRange": -1});
|
||||
assert!(upgrade(
|
||||
"structure",
|
||||
&mut anywhere,
|
||||
&mut report,
|
||||
&BTreeMap::new()
|
||||
));
|
||||
assert!(anywhere.get("horizon:start_checks").is_none());
|
||||
|
||||
// The config's spacing and separation, not the file's.
|
||||
let mut set = json!({"placement": {"type": "mostructures:type", "config_key": "moai",
|
||||
"salt": 12994829, "spacing": 17, "separation": 15,
|
||||
"structure_set_to_avoid": ["minecraft:villages", "mostructures:lighthouse"]}});
|
||||
assert!(upgrade(
|
||||
"structure_set",
|
||||
&mut set,
|
||||
&mut report,
|
||||
&BTreeMap::new()
|
||||
));
|
||||
assert_eq!(
|
||||
set["placement"],
|
||||
json!({"type": "minecraft:random_spread", "salt": 12994829, "spacing": 17,
|
||||
"separation": 15, "horizon:exclusion_zone": {"chunk_count": 3,
|
||||
"other_sets": ["minecraft:villages", "mostructures:lighthouse"],
|
||||
"their_zones": false}})
|
||||
);
|
||||
let mut set = json!({"placement": {"type": "mostructures:type",
|
||||
"config_key": "jungle_pyramid", "salt": 1, "spacing": 16, "separation": 14}});
|
||||
assert!(upgrade(
|
||||
"structure_set",
|
||||
&mut set,
|
||||
&mut report,
|
||||
&BTreeMap::new()
|
||||
));
|
||||
assert_eq!(
|
||||
(
|
||||
&set["placement"]["spacing"],
|
||||
&set["placement"]["separation"]
|
||||
),
|
||||
(&json!(25), &json!(22))
|
||||
);
|
||||
assert!(set["placement"].get("horizon:exclusion_zone").is_none());
|
||||
let mut unknown = json!({"placement": {"type": "mostructures:type", "config_key": "x"}});
|
||||
assert!(!upgrade(
|
||||
"structure_set",
|
||||
&mut unknown,
|
||||
&mut report,
|
||||
&BTreeMap::new()
|
||||
));
|
||||
assert_eq!(report.rules_lost["config_key"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn super_exclusion_zones_name_their_sets() {
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
|
||||
@@ -5,6 +5,13 @@ use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
/// This release's version: release.yml builds it with `HORIZON_VERSION` from the tag
|
||||
/// (docs/versioning.md); a build from source says Cargo.toml's.
|
||||
const VERSION: &str = match option_env!("HORIZON_VERSION") {
|
||||
Some(version) if !version.is_empty() => version,
|
||||
_ => env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
const HELP: &str = "\
|
||||
horizon-prepare: prepare Horizon's resources from your own Minecraft Java Edition
|
||||
|
||||
@@ -92,7 +99,7 @@ fn main() -> ExitCode {
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
"-V" | "--version" => {
|
||||
println!("horizon-prepare {}", env!("CARGO_PKG_VERSION"));
|
||||
println!("horizon-prepare {VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
_ => Err(format!("unrecognized argument: {text}")),
|
||||
|
||||
@@ -1674,6 +1674,8 @@ packet!(
|
||||
);
|
||||
packet!(ChangeDifficultyRequest { difficulty: i32 => VarInt });
|
||||
packet!(LockDifficulty { locked: bool => Bool });
|
||||
// ServerboundPlayerAbilitiesPacket: only whether the player flies (2).
|
||||
packet!(PlayerAbilitiesRequest { flags: i8 => Byte });
|
||||
packet!(SetGameRule { entries: Vec<GameRuleEntry> => List<GameRuleEntry> });
|
||||
packet!(ChunkBatchReceived { chunks_per_tick: f32 => Float });
|
||||
packet!(
|
||||
@@ -1786,6 +1788,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
|
||||
MovePlayerStatus(MovePlayerStatus) = MOVE_PLAYER_STATUS_ONLY,
|
||||
PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK,
|
||||
PingRequest(crate::packets::status::Ping) = PING_REQUEST,
|
||||
PlayerAbilities(PlayerAbilitiesRequest) = PLAYER_ABILITIES,
|
||||
PlayerAction(PlayerAction) = PLAYER_ACTION,
|
||||
PlayerCommand(PlayerCommand) = PLAYER_COMMAND,
|
||||
PlayerInput(PlayerInput) = PLAYER_INPUT,
|
||||
@@ -1805,6 +1808,17 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal};
|
||||
|
||||
#[test]
|
||||
fn serverbound_abilities_carry_only_flying() {
|
||||
// ServerboundPlayerAbilitiesPacket.write: one byte, 2 when flying.
|
||||
let flying = Serverbound::PlayerAbilities(PlayerAbilitiesRequest { flags: 2 });
|
||||
assert_eq!(
|
||||
flying.encode(),
|
||||
[crate::ids::play::serverbound::PLAYER_ABILITIES as u8, 2]
|
||||
);
|
||||
round_trip(flying, Serverbound::encode, Serverbound::decode);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_options_packets_match_vanilla_stream_codecs() {
|
||||
// mcsrc.dev 26.3: difficulty is a VarInt, locking is a Boolean,
|
||||
|
||||
@@ -45,7 +45,7 @@ pub fn resolve(name: &str, online: bool) -> Option<NameAndId> {
|
||||
pub fn find_by_name(discovery: &str, name: &str) -> Option<NameAndId> {
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(15))
|
||||
.user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION")))
|
||||
.user_agent(&format!("Horizon/{}", horizon_core::release::VERSION))
|
||||
.build();
|
||||
let doc = json::parse(&agent.get(discovery).call().ok()?.into_string().ok()?, true).ok()?;
|
||||
let url = endpoint(&doc, "profiles", "getByName")?.replace("{name}", &name.to_lowercase());
|
||||
@@ -61,7 +61,7 @@ pub fn fetch_profile_key_keys(discovery: &str) -> Result<Vec<RsaPublicKey>, &'st
|
||||
const FAILED: &str = "Failed to request Minecraft Services public key";
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(15))
|
||||
.user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION")))
|
||||
.user_agent(&format!("Horizon/{}", horizon_core::release::VERSION))
|
||||
.build();
|
||||
let get = |url: &str| agent.get(url).call().ok()?.into_string().ok();
|
||||
let doc = get(discovery)
|
||||
|
||||
@@ -286,7 +286,7 @@ fn status(shared: &Shared) -> Value {
|
||||
let state = shared.state.lock().unwrap();
|
||||
json!({
|
||||
"phase": state.phase.name(),
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"version": crate::VERSION,
|
||||
"pid": std::process::id(),
|
||||
"uptime_seconds": shared.started.elapsed().as_secs(),
|
||||
"engine_pid": state.engine_pid,
|
||||
|
||||
@@ -18,6 +18,13 @@ mod update;
|
||||
|
||||
use std::{path::PathBuf, process::ExitCode};
|
||||
|
||||
/// This release's version: release.yml builds it with `HORIZON_VERSION` from the tag
|
||||
/// (docs/versioning.md); a build from source says Cargo.toml's.
|
||||
const VERSION: &str = match option_env!("HORIZON_VERSION") {
|
||||
Some(version) if !version.is_empty() => version,
|
||||
_ => env!("CARGO_PKG_VERSION"),
|
||||
};
|
||||
|
||||
const HELP: &str = "\
|
||||
horizon-server: host a Horizon (Minecraft Java Edition 26.3) server
|
||||
|
||||
@@ -86,7 +93,7 @@ fn main() -> ExitCode {
|
||||
Ok(())
|
||||
}
|
||||
Some("version" | "-V" | "--version") => {
|
||||
println!("horizon-server {}", env!("CARGO_PKG_VERSION"));
|
||||
println!("horizon-server {VERSION}");
|
||||
Ok(())
|
||||
}
|
||||
Some("init") => init_answers(&args[1..]).and_then(|a| init::run(&dir, a)),
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
use crate::include::Inlined;
|
||||
use pp_rs::{
|
||||
pp::Preprocessor,
|
||||
token::{Punct, TokenValue},
|
||||
token::{PreprocessorError, Punct, TokenValue},
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The version of Minecraft packs are told they run on (`MC_VERSION`,
|
||||
/// Iris's `formatVersionString("26.3")`).
|
||||
@@ -286,14 +287,176 @@ fn mark_comments(text: &str) -> (String, Vec<String>) {
|
||||
(out, comments)
|
||||
}
|
||||
|
||||
/// Whether trimmed `line` is an `#if` or `#elif` directive.
|
||||
pub(crate) fn is_condition(line: &str) -> bool {
|
||||
line.strip_prefix('#')
|
||||
.map(str::trim_start)
|
||||
.and_then(|d| d.strip_prefix("elif").or_else(|| d.strip_prefix("if")))
|
||||
.is_some_and(|r| !r.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_'))
|
||||
}
|
||||
|
||||
/// Whether `word` is a float literal.
|
||||
pub(crate) fn is_float(word: &str) -> bool {
|
||||
word.starts_with(|c: char| c.is_ascii_digit() || c == '.')
|
||||
&& !word.starts_with("0x")
|
||||
&& !word.starts_with("0X")
|
||||
&& word.contains(['.', 'e', 'E'])
|
||||
}
|
||||
|
||||
/// What JCPP's `#if` makes of a number (`Preprocessor.expr` takes
|
||||
/// `NumericValue.longValue`): a float counts as its integer part, so
|
||||
/// `0.75` is 0 and `1.5e1` is 10. `None` for a non-number.
|
||||
pub(crate) fn jcpp_integer(number: &str) -> Option<i64> {
|
||||
let number = number.trim_end_matches(['f', 'F', 'l', 'L', 'u', 'U']);
|
||||
let (mantissa, exponent) = match number.find(['e', 'E']) {
|
||||
Some(i) => (&number[..i], number[i + 1..].parse::<i32>().ok()?),
|
||||
None => (number, 0),
|
||||
};
|
||||
let integer = mantissa.split('.').next()?;
|
||||
let value = if integer.is_empty() {
|
||||
0
|
||||
} else {
|
||||
integer.parse::<i64>().ok()?
|
||||
};
|
||||
Some((value as f64 * 10f64.powi(exponent)) as i64)
|
||||
}
|
||||
|
||||
/// `line` with each word (identifier or number, with an exponent's sign:
|
||||
/// `1e-3`) replaced by what `f` returns for it, if anything. The directive's
|
||||
/// name and the names after `defined` are kept.
|
||||
pub(crate) fn rewrite_condition(line: &str, f: impl Fn(&str) -> Option<String>) -> String {
|
||||
let mut out = String::with_capacity(line.len());
|
||||
let (mut rest, mut first, mut after_defined) = (line, true, false);
|
||||
while let Some(c) = rest.chars().next() {
|
||||
if !(c.is_ascii_alphanumeric() || c == '_' || c == '.') {
|
||||
if !c.is_whitespace() && c != '(' && c != '#' {
|
||||
after_defined = false;
|
||||
}
|
||||
out.push(c);
|
||||
rest = &rest[c.len_utf8()..];
|
||||
continue;
|
||||
}
|
||||
let bytes = rest.as_bytes();
|
||||
let mut len = 0;
|
||||
while let Some(&b) = bytes.get(len) {
|
||||
let sign = (b == b'+' || b == b'-')
|
||||
&& bytes[0].is_ascii_digit()
|
||||
&& matches!(bytes[len - 1], b'e' | b'E');
|
||||
if !(b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || sign) {
|
||||
break;
|
||||
}
|
||||
len += 1;
|
||||
}
|
||||
let word = &rest[..len];
|
||||
let kept = first || after_defined;
|
||||
match (!kept).then(|| f(word)).flatten() {
|
||||
Some(replacement) => out.push_str(&replacement),
|
||||
None => out.push_str(word),
|
||||
}
|
||||
after_defined = word == "defined";
|
||||
first = false;
|
||||
rest = &rest[len..];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Make pp-rs read `text` as JCPP, Iris's preprocessor, does:
|
||||
/// - a `#define` replaces an earlier macro (`Preprocessor.addMacro`; Bloop
|
||||
/// and Steadfast redefine theirs), where pp-rs refuses a different
|
||||
/// redefinition: an `#undef` line goes before every `#define`;
|
||||
/// - in `#if`/`#elif`, a float counts as its integer part, and so does a
|
||||
/// macro always defined as the same float (an option: `#define LEVEL 0.5`);
|
||||
/// a macro always defined empty (Iris's `MC_GL_VENDOR_OTHER`, Bloop's
|
||||
/// `#define TAA_USE_YCOCG`) counts as 0: JCPP reports the missing operand
|
||||
/// and goes on with 0. pp-rs stops on both;
|
||||
/// - `#error "..."` (Photon's guard in programs it disables) lexes: pp-rs
|
||||
/// has no string tokens and fails on the quote, even in a skipped block.
|
||||
///
|
||||
/// Returns the text and the added lines' 1-based numbers in it.
|
||||
fn jcpp_compatible(text: &str, env: &Environment) -> (String, Vec<u32>) {
|
||||
// A `#define` line's name and body.
|
||||
let define = |l: &str| {
|
||||
let rest = l
|
||||
.trim_start()
|
||||
.strip_prefix('#')?
|
||||
.trim_start()
|
||||
.strip_prefix("define")
|
||||
.filter(|rest| rest.starts_with([' ', '\t']))?
|
||||
.trim_start();
|
||||
let end = rest
|
||||
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.unwrap_or(rest.len());
|
||||
let (name, body) = rest.split_at(end);
|
||||
let body = body.split("//").next().unwrap_or("").trim();
|
||||
(!name.is_empty()).then(|| (name.to_owned(), body.to_owned()))
|
||||
};
|
||||
// Each macro's body, if every definition has the same one.
|
||||
let mut bodies: HashMap<String, Option<String>> = HashMap::new();
|
||||
let definitions = env
|
||||
.defines
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(text.lines().filter_map(define));
|
||||
for (name, body) in definitions {
|
||||
bodies
|
||||
.entry(name)
|
||||
.and_modify(|b| {
|
||||
if b.as_ref() != Some(&body) {
|
||||
*b = None;
|
||||
}
|
||||
})
|
||||
.or_insert(Some(body));
|
||||
}
|
||||
let number = |word: &str| -> Option<String> {
|
||||
let word = match bodies.get(word) {
|
||||
Some(Some(body)) if body.is_empty() => return Some("0".into()),
|
||||
Some(Some(body)) => body.as_str(),
|
||||
Some(None) => return None,
|
||||
None => word,
|
||||
};
|
||||
is_float(word)
|
||||
.then(|| jcpp_integer(word))
|
||||
.flatten()
|
||||
.map(|n| n.to_string())
|
||||
};
|
||||
let mut out = String::with_capacity(text.len() + text.len() / 16);
|
||||
let mut added = Vec::new();
|
||||
let (mut line, mut continued) = (1, false);
|
||||
for l in text.split_inclusive('\n') {
|
||||
if !continued && let Some((name, _)) = define(l) {
|
||||
out.push_str(&format!("#undef {name}\n"));
|
||||
added.push(line);
|
||||
line += 1;
|
||||
}
|
||||
let directive = l.trim_start().strip_prefix('#').map(str::trim_start);
|
||||
if !continued
|
||||
&& directive.is_some_and(|d| d.starts_with("error") || d.starts_with("warning"))
|
||||
{
|
||||
out.push_str(&l.replace(['"', '\''], ""));
|
||||
} else if !continued && is_condition(l.trim_start()) {
|
||||
out.push_str(&rewrite_condition(l, number));
|
||||
} else {
|
||||
out.push_str(l);
|
||||
}
|
||||
continued = l.trim_end().ends_with('\\');
|
||||
line += 1;
|
||||
}
|
||||
(out, added)
|
||||
}
|
||||
|
||||
/// Expand `source` with `env`'s macros. Errors name the file and line.
|
||||
pub fn preprocess(source: &Inlined, env: &Environment) -> Result<Preprocessed, String> {
|
||||
let (marked, comments) = mark_comments(&source.text);
|
||||
let text = &marked;
|
||||
let (text, added) = jcpp_compatible(&marked, env);
|
||||
let text = &text;
|
||||
let line_starts: Vec<usize> = std::iter::once(0)
|
||||
.chain(text.match_indices('\n').map(|(i, _)| i + 1))
|
||||
.collect();
|
||||
let line_of = |offset: u32| line_starts.partition_point(|&s| s <= offset as usize) as u32;
|
||||
// Lines of the source: the added `#undef` lines don't count.
|
||||
let line_of = |offset: u32| {
|
||||
let line = line_starts.partition_point(|&s| s <= offset as usize) as u32;
|
||||
line - added.partition_point(|&a| a < line) as u32
|
||||
};
|
||||
let mut pp = Preprocessor::new(text);
|
||||
for (name, value) in &env.defines {
|
||||
pp.add_define(name, value)
|
||||
@@ -307,8 +470,15 @@ pub fn preprocess(source: &Inlined, env: &Environment) -> Result<Preprocessed, S
|
||||
};
|
||||
let mut line = 1;
|
||||
for item in pp {
|
||||
let token =
|
||||
item.map_err(|(e, at)| format!("{}: {e:?}", source.locate(line_of(at.start))))?;
|
||||
let token = match item {
|
||||
// JCPP lets an `#if` run to the end of the input (Bloop's
|
||||
// taa.fsh never closes its `#ifdef TAA`); pp-rs says so there,
|
||||
// after the last token.
|
||||
Err((PreprocessorError::UnfinishedBlock, _)) => break,
|
||||
item => {
|
||||
item.map_err(|(e, at)| format!("{}: {e:?}", source.locate(line_of(at.start))))?
|
||||
}
|
||||
};
|
||||
let at = line_of(token.location.start);
|
||||
let piece = match token.value {
|
||||
TokenValue::Version(v) => {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! so `#if` blocks pick the directives that apply.
|
||||
|
||||
use crate::options::{OptionSet, OptionValues};
|
||||
use crate::preprocess::Environment;
|
||||
use crate::preprocess::{Environment, is_condition, is_float, jcpp_integer, rewrite_condition};
|
||||
use pp_rs::{pp::Preprocessor, token::TokenValue};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -120,9 +120,32 @@ const DIRECTIVES: &[&str] = &[
|
||||
"#warning", "#pragma", "#line", "#include",
|
||||
];
|
||||
|
||||
/// An `#if`/`#elif` line with its floats as JCPP reads them (Steadfast tests
|
||||
/// `#if ATMOSPHERE_FOG_STRENGTH_NOON == 0.75` with the option at 0.5, which
|
||||
/// Iris reads as `0 == 0`): float literals and the options set to a float
|
||||
/// become their integer part.
|
||||
fn jcpp_condition(line: &str, options: &OptionSet, values: &OptionValues) -> String {
|
||||
rewrite_condition(line, |word| {
|
||||
let value = match options.strings.get(word) {
|
||||
Some(o) => values.strings.get(word).unwrap_or(&o.default).as_str(),
|
||||
None => word,
|
||||
};
|
||||
is_float(value)
|
||||
.then(|| jcpp_integer(value))
|
||||
.flatten()
|
||||
.map(|n| n.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// What backslashes are while the macros expand, as in Iris: the
|
||||
/// preprocessor must not join a `\`-continued value with the directive on
|
||||
/// the next line (Photon ends an `#if`'d value with `) \` before `#else`).
|
||||
const BACKSLASH: &str = "IRIS_PASSTHROUGHBACKSLASH";
|
||||
|
||||
/// `PropertiesPreprocessor.preprocessSource`: comment lines dropped, other
|
||||
/// `#`s removed, then the macros expanded. Tokens keep their source spelling
|
||||
/// and spacing (`0.50` stays `0.50`, `<empty>` stays one word).
|
||||
/// `#`s removed, then the macros expanded with the backslashes hidden.
|
||||
/// Tokens keep their source spelling and spacing (`0.50` stays `0.50`,
|
||||
/// `<empty>` stays one word).
|
||||
pub fn preprocess(
|
||||
text: &str,
|
||||
env: &Environment,
|
||||
@@ -132,7 +155,6 @@ pub fn preprocess(
|
||||
let filtered: String = text
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| match l.starts_with('#') {
|
||||
// JCPP lets a #define replace a macro (Complementary sets
|
||||
// COLORED_LIGHTING 0 on macOS); pp-rs refuses, so undefine first.
|
||||
@@ -142,11 +164,12 @@ pub fn preprocess(
|
||||
None => l.to_owned(),
|
||||
}
|
||||
}
|
||||
true if is_condition(l) => jcpp_condition(l, options, values),
|
||||
true if DIRECTIVES.iter().any(|d| l.starts_with(d)) => l.to_owned(),
|
||||
true => String::new(),
|
||||
false => l.replace('#', ""),
|
||||
})
|
||||
.map(|l| l + "\n")
|
||||
.map(|l| l.replace('\\', BACKSLASH) + "\n")
|
||||
.collect();
|
||||
let mut pp = Preprocessor::new(&filtered);
|
||||
let mut define = |name: &str, value: &str| {
|
||||
@@ -202,7 +225,7 @@ pub fn preprocess(
|
||||
});
|
||||
}
|
||||
out.push('\n');
|
||||
Ok(out)
|
||||
Ok(out.replace(BACKSLASH, "\\"))
|
||||
}
|
||||
|
||||
/// One element of an option screen (`OptionMenuElement`).
|
||||
@@ -698,6 +721,39 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floats_in_conditions_count_as_their_integer_part() {
|
||||
assert_eq!(
|
||||
[".5", "0.75", "1.0", "2.5f", "1.5e1", "7", "0x10"].map(jcpp_integer),
|
||||
[Some(0), Some(0), Some(1), Some(2), Some(10), Some(7), None]
|
||||
);
|
||||
// Steadfast's fog strength: the option is 0.5, so Iris takes the
|
||||
// 0.75 branch (0 == 0).
|
||||
let set = options(&["#define FOG 0.5 // [0.0 0.5 0.75 1.0]"]);
|
||||
let text = "\
|
||||
#if FOG == 1.0
|
||||
a = 1
|
||||
#elif FOG == 0.75
|
||||
a = 0.75
|
||||
#else
|
||||
a = 0.5
|
||||
#endif
|
||||
#if(FOG<1e1)
|
||||
b = 1
|
||||
#endif
|
||||
";
|
||||
let env = Environment {
|
||||
defines: Vec::new(),
|
||||
};
|
||||
let values = OptionValues::default();
|
||||
let out = preprocess(text, &env, &set, &values).unwrap();
|
||||
assert_eq!(out, "a = 0.75\nb = 1\n");
|
||||
assert_eq!(
|
||||
jcpp_condition("#elif FOG == 0.75 && X > 2.5", &set, &values),
|
||||
"#elif 0 == 0 && X > 2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boolean_expressions() {
|
||||
let set = options(&["#define A", "//#define B", "#define C"]);
|
||||
|
||||
@@ -18,7 +18,11 @@
|
||||
//! swizzled shadow lookup is widened first (naga has no scalar swizzle);
|
||||
//! - global initialisers run at the start of `main` (drivers accept
|
||||
//! non-constant ones), unsized global arrays are sized from them;
|
||||
//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none).
|
||||
//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none);
|
||||
//! - what naga refuses and drivers accept: `%` goes through overloads (naga
|
||||
//! won't take `ivec2 % int`), `sqrt` of a negative constant isn't folded,
|
||||
//! constants naga can't fold (`?:`, `mix`) become globals set in `main`,
|
||||
//! and 16/8-bit types are their 32-bit ones.
|
||||
//!
|
||||
//! The programs of one pass share a [`Link`], so their locations, bindings and
|
||||
//! uniform block agree.
|
||||
@@ -234,6 +238,106 @@ vec3 iris_modf(vec3 x, out vec3 i) { i = trunc(x); return x - i; }
|
||||
vec4 iris_modf(vec4 x, out vec4 i) { i = trunc(x); return x - i; }
|
||||
";
|
||||
|
||||
/// A fragment output narrower than four channels (`out vec3 color`,
|
||||
/// Steadfast's `final`): the four-channel type it is written through and the
|
||||
/// epilogue line that fills it, with alpha 1 and the rest 0. `None` when the
|
||||
/// output already has four channels.
|
||||
fn widen_output(ty: &str, name: &str) -> Option<(String, String)> {
|
||||
let (wide, one, zero) = match ty {
|
||||
"float" | "vec2" | "vec3" => ("vec4", "1.0", "0.0"),
|
||||
"int" | "ivec2" | "ivec3" => ("ivec4", "1", "0"),
|
||||
"uint" | "uvec2" | "uvec3" => ("uvec4", "1u", "0u"),
|
||||
_ => return None,
|
||||
};
|
||||
let channels = match ty.chars().last() {
|
||||
Some('2') => 2,
|
||||
Some('3') => 3,
|
||||
_ => 1,
|
||||
};
|
||||
let mut parts = vec![name.to_owned()];
|
||||
parts.extend((channels..3).map(|_| zero.to_owned()));
|
||||
parts.push(one.to_owned());
|
||||
Some((
|
||||
wide.to_owned(),
|
||||
format!("iris_out_{name} = {wide}({});", parts.join(", ")),
|
||||
))
|
||||
}
|
||||
|
||||
/// `%` as overloads: naga's GLSL front end splats a scalar operand for
|
||||
/// `+ - / & ^ |` but not for `%`, and rejects `ivec2(uv) % 256` (Noble).
|
||||
fn modulo_helpers() -> String {
|
||||
let mut out = String::new();
|
||||
for (s, v) in [("int", "ivec"), ("uint", "uvec")] {
|
||||
out.push_str(&format!("{s} iris_mod({s} a, {s} b) {{ return a % b; }}\n"));
|
||||
for n in 2..=4 {
|
||||
let v = format!("{v}{n}");
|
||||
out.push_str(&format!("{v} iris_mod({v} a, {v} b) {{ return a % b; }}\n"));
|
||||
out.push_str(&format!(
|
||||
"{v} iris_mod({v} a, {s} b) {{ return a % {v}(b); }}\n"
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"{v} iris_mod({s} a, {v} b) {{ return {v}(a) % b; }}\n"
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 16- and 8-bit types (`GL_NV_gpu_shader5`, `GL_EXT_shader_explicit_arithmetic_types`)
|
||||
/// and their built-ins, as the 32-bit ones WGSL has: Noble declares
|
||||
/// `u16vec2` & co. when Iris reports an NVIDIA GPU, and falls back to these
|
||||
/// same aliases elsewhere.
|
||||
const SMALL_TYPES: &[(&str, &str)] = &[
|
||||
("float16_t", "float"),
|
||||
("f16vec2", "vec2"),
|
||||
("f16vec3", "vec3"),
|
||||
("f16vec4", "vec4"),
|
||||
("int16_t", "int"),
|
||||
("i16vec2", "ivec2"),
|
||||
("i16vec3", "ivec3"),
|
||||
("i16vec4", "ivec4"),
|
||||
("uint16_t", "uint"),
|
||||
("u16vec2", "uvec2"),
|
||||
("u16vec3", "uvec3"),
|
||||
("u16vec4", "uvec4"),
|
||||
("int8_t", "int"),
|
||||
("i8vec2", "ivec2"),
|
||||
("i8vec3", "ivec3"),
|
||||
("i8vec4", "ivec4"),
|
||||
("uint8_t", "uint"),
|
||||
("u8vec2", "uvec2"),
|
||||
("u8vec3", "uvec3"),
|
||||
("u8vec4", "uvec4"),
|
||||
("packFloat2x16", "packHalf2x16"),
|
||||
("unpackFloat2x16", "unpackHalf2x16"),
|
||||
];
|
||||
|
||||
/// `source` with [`SMALL_TYPES`] replaced, word by word.
|
||||
fn widen_small_types(source: &str) -> std::borrow::Cow<'_, str> {
|
||||
if !SMALL_TYPES.iter().any(|(t, _)| source.contains(t)) {
|
||||
return source.into();
|
||||
}
|
||||
let mut out = String::with_capacity(source.len());
|
||||
let mut rest = source;
|
||||
while let Some(c) = rest.chars().next() {
|
||||
let len = if c.is_ascii_alphanumeric() || c == '_' {
|
||||
rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.unwrap_or(rest.len())
|
||||
} else {
|
||||
c.len_utf8()
|
||||
};
|
||||
let word = &rest[..len];
|
||||
out.push_str(
|
||||
SMALL_TYPES
|
||||
.iter()
|
||||
.find(|(t, _)| *t == word)
|
||||
.map_or(word, |(_, w)| w),
|
||||
);
|
||||
rest = &rest[len..];
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
|
||||
/// Translate one preprocessed program. `locate` turns a line of `source`
|
||||
/// into `file:line` for errors.
|
||||
pub fn translate(
|
||||
@@ -248,7 +352,8 @@ pub fn translate(
|
||||
Stage::Compute => naga::ShaderStage::Compute,
|
||||
_ => return Err(format!("{stage:?} programs are not supported")),
|
||||
};
|
||||
let mut unit = ast::TranslationUnit::parse(source).map_err(|e| {
|
||||
let source = widen_small_types(source);
|
||||
let mut unit = ast::TranslationUnit::parse(&source).map_err(|e| {
|
||||
let line = e.line() + 1;
|
||||
format!("{}: {}", locate(line), e.inner())
|
||||
})?;
|
||||
@@ -281,6 +386,111 @@ pub fn translate(
|
||||
})
|
||||
}
|
||||
|
||||
/// The GLSL built-ins naga's constant evaluator folds (`MathFunction`s it
|
||||
/// implements), besides type constructors.
|
||||
const FOLDABLE: &[&str] = &[
|
||||
"abs",
|
||||
"acos",
|
||||
"acosh",
|
||||
"asin",
|
||||
"asinh",
|
||||
"atan",
|
||||
"atanh",
|
||||
"ceil",
|
||||
"clamp",
|
||||
"cos",
|
||||
"cosh",
|
||||
"cross",
|
||||
"degrees",
|
||||
"distance",
|
||||
"dot",
|
||||
"exp",
|
||||
"exp2",
|
||||
"floor",
|
||||
"fma",
|
||||
"fract",
|
||||
"inversesqrt",
|
||||
"length",
|
||||
"log",
|
||||
"log2",
|
||||
"max",
|
||||
"min",
|
||||
"normalize",
|
||||
"pow",
|
||||
"radians",
|
||||
"round",
|
||||
"sign",
|
||||
"sin",
|
||||
"sinh",
|
||||
"sqrt",
|
||||
"step",
|
||||
"tan",
|
||||
"tanh",
|
||||
"trunc",
|
||||
];
|
||||
|
||||
/// Whether a constant's initialisers need what naga can't fold and drivers
|
||||
/// do: a `?:`, another built-in (Bliss's `mix`), or a constant that had to
|
||||
/// become a global (`runtime`).
|
||||
fn needs_runtime(list: &ast::InitDeclaratorList, runtime: &HashSet<String>) -> bool {
|
||||
let constructor = |name: &str| {
|
||||
let n = name.trim_start_matches(['i', 'u', 'b', 'd']);
|
||||
matches!(name, "float" | "int" | "uint" | "bool" | "double")
|
||||
|| n.starts_with("vec")
|
||||
|| n.starts_with("mat")
|
||||
};
|
||||
let expr = |e: &ast::Expr| {
|
||||
fn walk(e: &ast::Expr, f: &dyn Fn(&ast::Expr) -> bool) -> bool {
|
||||
use ast::ExprData as E;
|
||||
f(e) || match &e.content {
|
||||
E::Unary(_, a) | E::PostInc(a) | E::PostDec(a) | E::Dot(a, _) => walk(a, f),
|
||||
E::Binary(_, a, b) | E::Assignment(a, _, b) | E::Comma(a, b) | E::Bracket(a, b) => {
|
||||
walk(a, f) || walk(b, f)
|
||||
}
|
||||
E::Ternary(a, b, c) => walk(a, f) || walk(b, f) || walk(c, f),
|
||||
E::FunCall(_, args) => args.iter().any(|a| walk(a, f)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
walk(e, &|e| match &e.content {
|
||||
ast::ExprData::Ternary(..) => true,
|
||||
ast::ExprData::Variable(v) => runtime.contains(v.as_str()),
|
||||
ast::ExprData::FunCall(f, _) => {
|
||||
callee(f).is_some_and(|c| !constructor(&c) && !FOLDABLE.contains(&c.as_str()))
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
fn init(i: &ast::Initializer, expr: &dyn Fn(&ast::Expr) -> bool) -> bool {
|
||||
match &i.content {
|
||||
ast::InitializerData::Simple(e) => expr(e),
|
||||
ast::InitializerData::List(items) => items.iter().any(|i| init(i, expr)),
|
||||
}
|
||||
}
|
||||
let tail = list.tail.iter().filter_map(|t| t.initializer.as_ref());
|
||||
list.head
|
||||
.initializer
|
||||
.iter()
|
||||
.chain(tail)
|
||||
.any(|i| init(i, &expr))
|
||||
}
|
||||
|
||||
/// A negative number: `-1.0`, `-1`.
|
||||
fn negative_constant(e: &ast::Expr) -> bool {
|
||||
use ast::ExprData as E;
|
||||
match &e.content {
|
||||
E::Unary(op, a) if op.content == ast::UnaryOpData::Minus => {
|
||||
matches!(
|
||||
a.content,
|
||||
E::FloatConst(v) if v > 0.0
|
||||
) || matches!(a.content, E::IntConst(v) if v > 0)
|
||||
|| matches!(a.content, E::DoubleConst(v) if v > 0.0)
|
||||
}
|
||||
E::FloatConst(v) => *v < 0.0,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn first_lines(s: &str) -> String {
|
||||
s.lines().take(8).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
@@ -316,6 +526,14 @@ struct Legaliser<'a> {
|
||||
/// Identifiers used, for the implicit declarations.
|
||||
used: HashSet<String>,
|
||||
errors: Vec<String>,
|
||||
/// Inside a constant initialiser: no helper calls there.
|
||||
constant: bool,
|
||||
/// The program uses `%` ([`modulo_helpers`]) or `iris_sqrt`: their
|
||||
/// helpers go in.
|
||||
modulo: bool,
|
||||
nan: bool,
|
||||
/// Constants turned into globals ([`needs_runtime`]).
|
||||
runtime_constants: HashSet<String>,
|
||||
}
|
||||
|
||||
fn var(name: &str) -> ast::Expr {
|
||||
@@ -507,6 +725,10 @@ impl<'a> Legaliser<'a> {
|
||||
declared: HashSet::new(),
|
||||
used: HashSet::new(),
|
||||
errors: Vec::new(),
|
||||
constant: false,
|
||||
modulo: false,
|
||||
nan: false,
|
||||
runtime_constants: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -727,8 +949,19 @@ impl<'a> Legaliser<'a> {
|
||||
let at = explicit
|
||||
.map(|l: u32| l + i as u32)
|
||||
.unwrap_or_else(|| self.next_output());
|
||||
self.header
|
||||
.push(format!("layout(location = {at}) out {full} {name}{array};"));
|
||||
if let (Some(widened), "") = (widen_output(&full, name), array.as_str()) {
|
||||
// GL fills the missing channels of a narrow output;
|
||||
// wgpu wants every channel of the target written.
|
||||
let (wide, fill) = widened;
|
||||
self.header.push(format!("{full} {name};"));
|
||||
self.header.push(format!(
|
||||
"layout(location = {at}) out {wide} iris_out_{name};"
|
||||
));
|
||||
self.epilogue.push(fill);
|
||||
} else {
|
||||
self.header
|
||||
.push(format!("layout(location = {at}) out {full} {name}{array};"));
|
||||
}
|
||||
self.interface.outputs.insert(at, name.clone());
|
||||
} else {
|
||||
self.varying(dir, &interp, &full, name, array);
|
||||
@@ -736,9 +969,25 @@ impl<'a> Legaliser<'a> {
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
if has(ast::StorageQualifierData::Const) || has(ast::StorageQualifierData::Shared) {
|
||||
// A constant naga can't fold becomes a global set at the start of `main`.
|
||||
if has(ast::StorageQualifierData::Const) && needs_runtime(list, &self.runtime_constants) {
|
||||
self.runtime_constants
|
||||
.extend(names.iter().map(|(n, _)| n.clone()));
|
||||
let q = &mut list.head.ty.qualifier;
|
||||
if let Some(q) = q {
|
||||
q.qualifiers.retain(|q| {
|
||||
!matches!(&q.content, ast::TypeQualifierSpecData::Storage(s)
|
||||
if s.content == ast::StorageQualifierData::Const)
|
||||
});
|
||||
}
|
||||
if q.as_ref().is_some_and(|q| q.qualifiers.is_empty()) {
|
||||
*q = None;
|
||||
}
|
||||
} else if has(ast::StorageQualifierData::Const) || has(ast::StorageQualifierData::Shared) {
|
||||
self.sized(list);
|
||||
self.constant = true;
|
||||
self.global_initialisers(list, false);
|
||||
self.constant = false;
|
||||
return Ok(true);
|
||||
}
|
||||
self.sized(list);
|
||||
@@ -930,6 +1179,8 @@ impl<'a> Legaliser<'a> {
|
||||
return;
|
||||
};
|
||||
self.sized(list);
|
||||
self.constant =
|
||||
storage(&list.head.ty.qualifier).contains(&ast::StorageQualifierData::Const);
|
||||
if let Some(i) = &mut list.head.initializer {
|
||||
self.initializer(i);
|
||||
}
|
||||
@@ -944,6 +1195,7 @@ impl<'a> Legaliser<'a> {
|
||||
let n = t.ident.ident.as_str().to_owned();
|
||||
self.declare(&n);
|
||||
}
|
||||
self.constant = false;
|
||||
}
|
||||
|
||||
fn initializer(&mut self, i: &mut ast::Initializer) {
|
||||
@@ -1148,6 +1400,24 @@ impl<'a> Legaliser<'a> {
|
||||
| E::FloatConst(_)
|
||||
| E::DoubleConst(_) => {}
|
||||
E::Unary(_, a) | E::PostInc(a) | E::PostDec(a) => self.expr(a),
|
||||
E::Binary(op, a, b) if op.content == ast::BinaryOpData::Mod && !self.constant => {
|
||||
self.expr(a);
|
||||
self.expr(b);
|
||||
self.modulo = true;
|
||||
let (a, b) = (
|
||||
std::mem::replace(&mut **a, var("_")),
|
||||
std::mem::replace(&mut **b, var("_")),
|
||||
);
|
||||
*e = call("iris_mod", vec![a, b]);
|
||||
}
|
||||
E::Assignment(a, op, b) if op.content == ast::AssignmentOpData::Mod => {
|
||||
self.expr(a);
|
||||
self.expr(b);
|
||||
self.modulo = true;
|
||||
let rhs = std::mem::replace(&mut **b, var("_"));
|
||||
**b = call("iris_mod", vec![(**a).clone(), rhs]);
|
||||
*op = ast::AssignmentOpData::Equal.into_node();
|
||||
}
|
||||
E::Binary(_, a, b) | E::Assignment(a, _, b) | E::Comma(a, b) => {
|
||||
self.expr(a);
|
||||
self.expr(b);
|
||||
@@ -1268,6 +1538,12 @@ impl<'a> Legaliser<'a> {
|
||||
if self.functions.contains(&name) {
|
||||
return;
|
||||
}
|
||||
// `sqrt(-1.0)`, Bloop's NaN: naga folds it and fails, drivers give NaN.
|
||||
if name == "sqrt" && !self.constant && args.len() == 1 && negative_constant(&args[0]) {
|
||||
*f = ast::FunIdentifierData::Expr(Box::new(var("iris_sqrt"))).into_node();
|
||||
self.nan = true;
|
||||
return;
|
||||
}
|
||||
if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) {
|
||||
*f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node();
|
||||
} else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) {
|
||||
@@ -1307,6 +1583,12 @@ impl<'a> Legaliser<'a> {
|
||||
}
|
||||
let mut out = String::from("#version 450 core\n");
|
||||
out.push_str(HELPERS);
|
||||
if self.modulo {
|
||||
out.push_str(&modulo_helpers());
|
||||
}
|
||||
if self.nan {
|
||||
out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n");
|
||||
}
|
||||
if !self.link.uniforms.is_empty() {
|
||||
out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n");
|
||||
for (_, decl) in &self.link.uniforms {
|
||||
|
||||
@@ -121,6 +121,69 @@ fn preprocesses_with_defaults_and_with_values() {
|
||||
);
|
||||
}
|
||||
|
||||
/// JCPP lets a `#define` replace a macro (Bloop's `TILT_ANGLE`); the added
|
||||
/// `#undef`s don't move the lines errors name.
|
||||
#[test]
|
||||
fn a_define_replaces_an_earlier_one() {
|
||||
use horizon_shaderpack::{include::Inlined, preprocess::preprocess};
|
||||
let text = "#define TILT 5.0\nfloat a = TILT;\n # define TILT 1.5 // radians\nfloat b = TILT;\n#define F(x) x\n#define F(x) (x * 2)\nfloat c = F(1);\n#if\n";
|
||||
let source = Inlined {
|
||||
text: text.into(),
|
||||
origin: (1..=8).map(|l| ("lib/specular.glsl".into(), l)).collect(),
|
||||
};
|
||||
let error = preprocess(&source, &env()).unwrap_err();
|
||||
assert!(error.starts_with("lib/specular.glsl:8:"), "{error}");
|
||||
let source = Inlined {
|
||||
text: text.replace("#if\n", ""),
|
||||
..source
|
||||
};
|
||||
let out = preprocess(&source, &env()).unwrap().text;
|
||||
let lines: Vec<&str> = out.lines().collect();
|
||||
assert_eq!(lines[1], "float a = 5.0 ;");
|
||||
assert_eq!(lines[3], "float b = 1.5 ;");
|
||||
assert_eq!(lines[6], "float c = ( 1 * 2 ) ;");
|
||||
}
|
||||
|
||||
/// Conditions as JCPP reads them: an empty macro counts as 0 (Bloop's
|
||||
/// `#if MC_GL_VENDOR_INTEL || MC_GL_VENDOR_OTHER` with Iris's empty vendor
|
||||
/// macro, its `#define TAA_USE_YCOCG`), a float as its integer part; a
|
||||
/// quoted `#error` lexes, and an `#if` may run to the end.
|
||||
#[test]
|
||||
fn conditions_read_as_jcpp_does() {
|
||||
use horizon_shaderpack::{include::Inlined, preprocess::preprocess};
|
||||
let mut env = env();
|
||||
env.define("MC_GL_VENDOR_OTHER", "");
|
||||
let text = "#define TAA_USE_YCOCG
|
||||
#define LEVEL 0.5
|
||||
#if MC_GL_VENDOR_INTEL || MC_GL_VENDOR_OTHER
|
||||
float gather = 0.0;
|
||||
#else
|
||||
float gather = 1.0;
|
||||
#endif
|
||||
#if TAA_USE_YCOCG
|
||||
float ycocg = 1.0;
|
||||
#endif
|
||||
#if defined TAA_USE_YCOCG && defined(MC_GL_VENDOR_OTHER) && LEVEL == 0
|
||||
float both = 1.0;
|
||||
#endif
|
||||
#ifndef TAA_USE_YCOCG
|
||||
#error \"This program should be disabled\"
|
||||
#endif
|
||||
#ifdef TAA_USE_YCOCG
|
||||
float open = 1.0;
|
||||
";
|
||||
let source = Inlined {
|
||||
text: text.into(),
|
||||
origin: Vec::new(),
|
||||
};
|
||||
let out = preprocess(&source, &env).unwrap().text;
|
||||
let words: Vec<&str> = out.split_whitespace().collect();
|
||||
assert_eq!(
|
||||
words.join(" "),
|
||||
"float gather = 1.0 ; float both = 1.0 ; float open = 1.0 ;"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_missing_includes_and_cycles() {
|
||||
let pack = JavaPack::open(&mini()).unwrap();
|
||||
|
||||
@@ -290,6 +290,103 @@ fn reports_errors_with_their_place() {
|
||||
assert_eq!(err, "uniform a is declared as both `float a` and `int a`");
|
||||
}
|
||||
|
||||
/// What naga refuses and drivers accept: `vec % scalar` (Noble), `sqrt` of
|
||||
/// a negative constant (Bloop's NaN), constants naga can't fold (Bliss's
|
||||
/// `?:`, `mix`), and 16-bit types (Noble on NVIDIA).
|
||||
#[test]
|
||||
fn legalises_what_naga_refuses() {
|
||||
let mut link = Link::default();
|
||||
let fs = run(
|
||||
Stage::Fragment,
|
||||
"uniform vec2 uv;
|
||||
const int RES = 256 % 100;
|
||||
const vec3 TARGET = length(vec3(1.0)) < 0.001 ? vec3(0.0) : normalize(vec3(1.0));
|
||||
const vec3 TINT = mix(TARGET, vec3(1.0), 0.5);
|
||||
const vec3 HALF = TINT * 0.5;
|
||||
u16vec2 pack(uint v) { return u16vec2(v & 65535u, v >> 16u); }
|
||||
float nan() { return sqrt(-1.0); }
|
||||
void main() {
|
||||
ivec2 texel = ivec2(uv) % RES;
|
||||
texel %= 7;
|
||||
uint packed = packFloat2x16(f16vec2(HALF.xy));
|
||||
gl_FragColor = vec4(vec2(texel), float(pack(packed).x), nan());
|
||||
}
|
||||
",
|
||||
&mut link,
|
||||
)
|
||||
.unwrap();
|
||||
for wanted in [
|
||||
"const int RES = 256 % 100;",
|
||||
"vec3 TARGET;",
|
||||
"vec3 TINT;",
|
||||
"vec3 HALF;",
|
||||
"ivec2 texel = iris_mod(ivec2(uv), RES);",
|
||||
"texel = iris_mod(texel, 7);",
|
||||
"uvec2 pack(uint v)",
|
||||
"return iris_sqrt(-1.);",
|
||||
"uint packed = packHalf2x16(vec2(HALF.xy));",
|
||||
] {
|
||||
assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl);
|
||||
}
|
||||
reparse(&fs.wgsl).unwrap();
|
||||
}
|
||||
|
||||
/// A fragment output narrower than its four-channel target (Steadfast's
|
||||
/// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1:
|
||||
/// GL fills the missing channels, wgpu refuses the pipeline.
|
||||
#[test]
|
||||
fn narrow_fragment_outputs_fill_four_channels() {
|
||||
let mut link = Link::default();
|
||||
let fs = run(
|
||||
Stage::Fragment,
|
||||
"uniform vec3 tint;
|
||||
layout(location = 0) out vec3 color;
|
||||
layout(location = 1) out float depth;
|
||||
out vec4 extra;
|
||||
void main() {
|
||||
color = tint;
|
||||
depth = 0.5;
|
||||
extra = vec4(tint, 0.25);
|
||||
}
|
||||
",
|
||||
&mut link,
|
||||
)
|
||||
.unwrap();
|
||||
for wanted in [
|
||||
"layout(location = 0) out vec4 iris_out_color;",
|
||||
"iris_out_color = vec4(color, 1.0);",
|
||||
"layout(location = 1) out vec4 iris_out_depth;",
|
||||
"iris_out_depth = vec4(depth, 0.0, 0.0, 1.0);",
|
||||
"layout(location = 2) out vec4 extra;",
|
||||
] {
|
||||
assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl);
|
||||
}
|
||||
assert_eq!(
|
||||
fs.interface.outputs.values().collect::<Vec<_>>(),
|
||||
["color", "depth", "extra"]
|
||||
);
|
||||
let module = naga::front::wgsl::parse_str(&fs.wgsl).unwrap();
|
||||
let entry = &module.entry_points[0];
|
||||
let result = entry.function.result.as_ref().unwrap();
|
||||
let naga::TypeInner::Struct { members, .. } = &module.types[result.ty].inner else {
|
||||
panic!("{}", fs.wgsl);
|
||||
};
|
||||
for m in members {
|
||||
assert!(
|
||||
matches!(
|
||||
module.types[m.ty].inner,
|
||||
naga::TypeInner::Vector {
|
||||
size: naga::VectorSize::Quad,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{}",
|
||||
fs.wgsl
|
||||
);
|
||||
}
|
||||
reparse(&fs.wgsl).unwrap();
|
||||
}
|
||||
|
||||
/// The written WGSL, read back and validated: what wgpu is given.
|
||||
fn reparse(wgsl: &str) -> Result<(), String> {
|
||||
let module = naga::front::wgsl::parse_str(wgsl).map_err(|e| e.emit_to_string(wgsl))?;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# horizon-telemetry-server
|
||||
|
||||
This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It is one small Rust process, about 7 MB of memory when idle.
|
||||
This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It also keeps the live player count from the games' anonymous "I'm playing" pings, in memory only. It is one small Rust process, about 7 MB of memory when idle.
|
||||
|
||||
cargo run --release # in this folder: its own workspace, like the launcher's
|
||||
PORT=8080 HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3 horizon-telemetry-server
|
||||
@@ -14,6 +14,8 @@ 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. |
|
||||
| `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.
|
||||
@@ -27,6 +29,8 @@ The totals are grouped per version, OS, GPU vendor and render distance. Each gro
|
||||
|
||||
Measured: **about 190 bytes per play session** on disk, indexes included (`tests/server.rs`, 10 000 sessions). 1 000 players playing twice a day for 180 days is about 70 MB.
|
||||
|
||||
The live count is a table in memory: a session ID, when it last pinged, its version, platform and LAN flag, about 100 bytes a session. A session counts while its last ping is under 2 minutes old and is forgotten after that. Nothing of it reaches the disk, so a restart empties it; it is whole again a minute later.
|
||||
|
||||
The day stored is the day the server received an item. The sender's IP address is never written down. The per-address rate limit keeps addresses in memory for an hour at most.
|
||||
|
||||
Raw rows are deleted after `HORIZON_TELEMETRY_RETENTION_DAYS` (180). The daily totals stay; they hold no install ID.
|
||||
@@ -43,6 +47,9 @@ All are environment variables:
|
||||
- `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_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)
|
||||
- `HORIZON_TELEMETRY_LIVE_MAX_SESSIONS` (200 000)
|
||||
|
||||
## Hosting
|
||||
|
||||
|
||||
@@ -3,12 +3,15 @@
|
||||
//! - `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.
|
||||
//! - `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`.
|
||||
//!
|
||||
//! Abuse limits: a token bucket per IP address (kept in memory for an hour, never stored), a
|
||||
//! daily item cap per install, and the batch size limits. Raw rows expire after
|
||||
//! `retention_days`; the daily totals stay. One small process and one SQLite file: see
|
||||
//! `README.md` for running it.
|
||||
//! daily item cap per install, and the batch size limits. The live count has its own, larger
|
||||
//! bucket per address (several players can share one) and a cap on the sessions it holds. Raw
|
||||
//! rows expire after `retention_days`; the daily totals stay. One small process and one SQLite
|
||||
//! file: see `README.md` for running it.
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -21,8 +24,11 @@ use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post};
|
||||
use horizon_telemetry::batch;
|
||||
|
||||
pub mod live;
|
||||
pub mod store;
|
||||
|
||||
use horizon_telemetry::live::{MAX_PING_BYTES, Ping};
|
||||
use live::Live;
|
||||
use store::Store;
|
||||
|
||||
pub struct Config {
|
||||
@@ -38,6 +44,13 @@ pub struct Config {
|
||||
pub trust_proxy: bool,
|
||||
/// The website allowed to read the totals from a browser.
|
||||
pub allow_origin: String,
|
||||
/// Live count requests (pings and reads) an IP address may make an hour, with a burst of a
|
||||
/// tenth of it. A game pings once a minute, so the default lets ten play behind one address.
|
||||
pub live_per_hour: f64,
|
||||
/// How long a session counts after its last ping.
|
||||
pub live_window: Duration,
|
||||
/// Sessions the live count holds at most; a new one past that is refused.
|
||||
pub live_max_sessions: usize,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
@@ -49,13 +62,17 @@ impl Default for Config {
|
||||
items_per_day: 100,
|
||||
trust_proxy: false,
|
||||
allow_origin: "https://playhorizon.dev".into(),
|
||||
live_per_hour: 600.0,
|
||||
live_window: horizon_telemetry::live::WINDOW,
|
||||
live_max_sessions: 200_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// The defaults, with `HORIZON_TELEMETRY_RETENTION_DAYS`, `…_MIN_INSTALL_DAYS`,
|
||||
/// `…_REQUESTS_PER_HOUR`, `…_ITEMS_PER_DAY`, `…_TRUST_PROXY` (1) and `…_ALLOW_ORIGIN`.
|
||||
/// `…_REQUESTS_PER_HOUR`, `…_ITEMS_PER_DAY`, `…_TRUST_PROXY` (1), `…_ALLOW_ORIGIN`,
|
||||
/// `…_LIVE_PER_HOUR`, `…_LIVE_WINDOW_SECONDS` and `…_LIVE_MAX_SESSIONS`.
|
||||
pub fn from_env() -> Self {
|
||||
let var = |k: &str| std::env::var(format!("HORIZON_TELEMETRY_{k}")).ok();
|
||||
let d = Self::default();
|
||||
@@ -74,6 +91,15 @@ impl Config {
|
||||
.unwrap_or(d.items_per_day),
|
||||
trust_proxy: var("TRUST_PROXY").is_some_and(|v| v == "1"),
|
||||
allow_origin: var("ALLOW_ORIGIN").unwrap_or(d.allow_origin),
|
||||
live_per_hour: var("LIVE_PER_HOUR")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(d.live_per_hour),
|
||||
live_window: var("LIVE_WINDOW_SECONDS")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.map_or(d.live_window, Duration::from_secs),
|
||||
live_max_sessions: var("LIVE_MAX_SESSIONS")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(d.live_max_sessions),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,13 +108,21 @@ pub struct App {
|
||||
store: Mutex<Store>,
|
||||
config: Config,
|
||||
/// Tokens left and when they were counted, per client address.
|
||||
buckets: Mutex<HashMap<IpAddr, (f64, Instant)>>,
|
||||
buckets: Mutex<Buckets>,
|
||||
/// The same for the live count's requests.
|
||||
live_buckets: Mutex<Buckets>,
|
||||
/// Who is playing now (`live`).
|
||||
live: Mutex<Live>,
|
||||
/// `GET /v1/live`'s answer and when it was made.
|
||||
live_cache: Mutex<Option<(Instant, String)>>,
|
||||
/// `/v1/aggregate` answers by `days`, with when they were made.
|
||||
cache: Mutex<HashMap<u32, (Instant, String)>>,
|
||||
/// Today, in days since 1970 (a test moves it).
|
||||
today: Box<dyn Fn() -> u32 + Send + Sync>,
|
||||
}
|
||||
|
||||
type Buckets = HashMap<IpAddr, (f64, Instant)>;
|
||||
|
||||
const CACHE_FOR: Duration = Duration::from_secs(600);
|
||||
|
||||
fn status(code: StatusCode, message: &str) -> Response {
|
||||
@@ -105,10 +139,14 @@ impl App {
|
||||
config: Config,
|
||||
today: Box<dyn Fn() -> u32 + Send + Sync>,
|
||||
) -> Arc<Self> {
|
||||
let live = Live::new(config.live_window, config.live_max_sessions);
|
||||
Arc::new(Self {
|
||||
store: Mutex::new(store),
|
||||
config,
|
||||
buckets: Mutex::default(),
|
||||
live_buckets: Mutex::default(),
|
||||
live: Mutex::new(live),
|
||||
live_cache: Mutex::default(),
|
||||
cache: Mutex::default(),
|
||||
today,
|
||||
})
|
||||
@@ -120,18 +158,16 @@ impl App {
|
||||
|
||||
/// Takes a token for `ip`; false when it has none left.
|
||||
fn allow(&self, ip: IpAddr) -> bool {
|
||||
let rate = self.config.requests_per_hour / 3600.0;
|
||||
let burst = (self.config.requests_per_hour / 10.0).max(1.0);
|
||||
let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let now = Instant::now();
|
||||
let (tokens, at) = buckets.entry(ip).or_insert((burst, now));
|
||||
*tokens = (*tokens + now.duration_since(*at).as_secs_f64() * rate).min(burst);
|
||||
*at = now;
|
||||
if *tokens < 1.0 {
|
||||
return false;
|
||||
}
|
||||
*tokens -= 1.0;
|
||||
true
|
||||
take(&self.buckets, self.config.requests_per_hour, ip)
|
||||
}
|
||||
|
||||
/// [`Self::allow`] for the live count's requests.
|
||||
fn allow_live(&self, ip: IpAddr) -> bool {
|
||||
take(&self.live_buckets, self.config.live_per_hour, ip)
|
||||
}
|
||||
|
||||
fn live(&self) -> std::sync::MutexGuard<'_, Live> {
|
||||
self.live.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn client(&self, headers: &HeaderMap, peer: Option<SocketAddr>) -> IpAddr {
|
||||
@@ -160,14 +196,18 @@ impl App {
|
||||
self.store().newest_day(install).ok().flatten()
|
||||
}
|
||||
|
||||
/// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries forgotten.
|
||||
/// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries and live
|
||||
/// sessions forgotten.
|
||||
pub fn maintain(&self) -> rusqlite::Result<usize> {
|
||||
let oldest = (self.today)().saturating_sub(self.config.retention_days);
|
||||
let removed = self.store().expire(oldest)?;
|
||||
self.buckets
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600));
|
||||
for buckets in [&self.buckets, &self.live_buckets] {
|
||||
buckets
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600));
|
||||
}
|
||||
self.live().forget_expired(Instant::now());
|
||||
if removed > 0 {
|
||||
self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
}
|
||||
@@ -175,6 +215,23 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes a token for `ip` from its bucket in `buckets` (`per_hour`, bursts of a tenth of it);
|
||||
/// false when it has none left.
|
||||
fn take(buckets: &Mutex<Buckets>, per_hour: f64, ip: IpAddr) -> bool {
|
||||
let rate = per_hour / 3600.0;
|
||||
let burst = (per_hour / 10.0).max(1.0);
|
||||
let mut buckets = buckets.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let now = Instant::now();
|
||||
let (tokens, at) = buckets.entry(ip).or_insert((burst, now));
|
||||
*tokens = (*tokens + now.duration_since(*at).as_secs_f64() * rate).min(burst);
|
||||
*at = now;
|
||||
if *tokens < 1.0 {
|
||||
return false;
|
||||
}
|
||||
*tokens -= 1.0;
|
||||
true
|
||||
}
|
||||
|
||||
fn peer(req: &Request) -> Option<SocketAddr> {
|
||||
req.extensions()
|
||||
.get::<ConnectInfo<SocketAddr>>()
|
||||
@@ -278,18 +335,65 @@ async fn aggregate(State(app): State<Arc<App>>, Query(window): Query<Window>) ->
|
||||
}
|
||||
}
|
||||
};
|
||||
json_response(&app, json, CACHE_FOR.as_secs())
|
||||
}
|
||||
|
||||
/// `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 {
|
||||
if !app.allow_live(app.client(req.headers(), peer(&req))) {
|
||||
return status(StatusCode::TOO_MANY_REQUESTS, "too many requests");
|
||||
}
|
||||
let Ok(body) = axum::body::to_bytes(req.into_body(), MAX_PING_BYTES).await else {
|
||||
return status(StatusCode::PAYLOAD_TOO_LARGE, "a ping is at most 512 bytes");
|
||||
};
|
||||
let ping: Ping = match serde_json::from_slice(&body) {
|
||||
Ok(ping) => ping,
|
||||
Err(e) => return status(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
};
|
||||
if let Err(e) = ping.check() {
|
||||
return status(StatusCode::BAD_REQUEST, e);
|
||||
}
|
||||
match app.live().ping(&ping, Instant::now()) {
|
||||
Ok(()) => StatusCode::NO_CONTENT.into_response(),
|
||||
Err(live::Full) => status(StatusCode::SERVICE_UNAVAILABLE, "try again later"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /v1/live`: the rounded live count (`horizon_telemetry::live::Count`), made again at
|
||||
/// most every eighth of the window.
|
||||
async fn playing(State(app): State<Arc<App>>, req: Request) -> Response {
|
||||
if !app.allow_live(app.client(req.headers(), peer(&req))) {
|
||||
return status(StatusCode::TOO_MANY_REQUESTS, "too many requests");
|
||||
}
|
||||
let fresh_for = app.config.live_window / 8;
|
||||
let json = {
|
||||
let mut cache = app.live_cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match &*cache {
|
||||
Some((at, json)) if at.elapsed() < fresh_for => json.clone(),
|
||||
_ => {
|
||||
let json =
|
||||
serde_json::to_string(&app.live().count(Instant::now())).unwrap_or_default();
|
||||
*cache = Some((Instant::now(), json.clone()));
|
||||
json
|
||||
}
|
||||
}
|
||||
};
|
||||
json_response(&app, json, fresh_for.as_secs())
|
||||
}
|
||||
|
||||
fn json_response(app: &App, json: String, max_age: u64) -> Response {
|
||||
let origin =
|
||||
HeaderValue::from_str(&app.config.allow_origin).unwrap_or(HeaderValue::from_static("*"));
|
||||
let cache = HeaderValue::from_str(&format!("public, max-age={max_age}"))
|
||||
.unwrap_or(HeaderValue::from_static("no-cache"));
|
||||
(
|
||||
[
|
||||
(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/json"),
|
||||
),
|
||||
(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("public, max-age=600"),
|
||||
),
|
||||
(header::CACHE_CONTROL, cache),
|
||||
(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin),
|
||||
],
|
||||
json,
|
||||
@@ -300,6 +404,7 @@ async fn aggregate(State(app): State<Arc<App>>, Query(window): Query<Window>) ->
|
||||
pub fn router(app: Arc<App>) -> Router {
|
||||
Router::new()
|
||||
.route("/v1/batch", post(receive))
|
||||
.route("/v1/live", post(ping).get(playing))
|
||||
.route("/v1/installs/{id}", delete(forget))
|
||||
.route("/v1/aggregate", get(aggregate))
|
||||
.route("/healthz", get(|| async { "ok" }))
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Who is playing now, from the games' "I'm playing" pings (`horizon_telemetry::live`). Kept in
|
||||
//! memory only: a session ID, when it last pinged, its version, platform and LAN flag. A
|
||||
//! session counts while its last ping is under the window old and is forgotten after it. No
|
||||
//! address is kept, and nothing is written to disk, so a restart starts the count again (it
|
||||
//! is whole again a minute later).
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use horizon_telemetry::live::{Count, PLATFORMS, Ping, round};
|
||||
|
||||
/// Versions listed by name in a count; the rest are summed under `other`.
|
||||
const VERSIONS_SHOWN: usize = 12;
|
||||
|
||||
struct Seen {
|
||||
at: Instant,
|
||||
version: Box<str>,
|
||||
platform: u8,
|
||||
lan: bool,
|
||||
}
|
||||
|
||||
pub struct Live {
|
||||
sessions: HashMap<u128, Seen>,
|
||||
window: Duration,
|
||||
max_sessions: usize,
|
||||
}
|
||||
|
||||
/// The table is full and this session is new.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Full;
|
||||
|
||||
impl Live {
|
||||
pub fn new(window: Duration, max_sessions: usize) -> Self {
|
||||
Self {
|
||||
sessions: HashMap::new(),
|
||||
window,
|
||||
max_sessions,
|
||||
}
|
||||
}
|
||||
|
||||
/// Records `ping` (already checked) as seen at `now`.
|
||||
pub fn ping(&mut self, ping: &Ping, now: Instant) -> Result<(), Full> {
|
||||
let Ok(id) = u128::from_str_radix(&ping.session, 16) else {
|
||||
return Ok(());
|
||||
};
|
||||
if !self.sessions.contains_key(&id) && self.sessions.len() >= self.max_sessions {
|
||||
self.forget_expired(now);
|
||||
if self.sessions.len() >= self.max_sessions {
|
||||
return Err(Full);
|
||||
}
|
||||
}
|
||||
let platform = PLATFORMS
|
||||
.iter()
|
||||
.position(|p| *p == ping.platform)
|
||||
.unwrap_or(PLATFORMS.len() - 1) as u8;
|
||||
self.sessions.insert(
|
||||
id,
|
||||
Seen {
|
||||
at: now,
|
||||
version: ping.version.as_str().into(),
|
||||
platform,
|
||||
lan: ping.lan,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops the sessions whose last ping is older than the window.
|
||||
pub fn forget_expired(&mut self, now: Instant) {
|
||||
let window = self.window;
|
||||
self.sessions
|
||||
.retain(|_, s| now.saturating_duration_since(s.at) < window);
|
||||
}
|
||||
|
||||
/// Who is playing at `now`, rounded.
|
||||
pub fn count(&mut self, now: Instant) -> Count {
|
||||
self.forget_expired(now);
|
||||
let mut versions: HashMap<&str, u64> = HashMap::new();
|
||||
let mut platforms = [0u64; PLATFORMS.len()];
|
||||
let mut lan = 0;
|
||||
for s in self.sessions.values() {
|
||||
*versions.entry(&s.version).or_default() += 1;
|
||||
platforms[usize::from(s.platform)] += 1;
|
||||
lan += u64::from(s.lan);
|
||||
}
|
||||
let mut by_count: Vec<(&str, u64)> = versions.into_iter().collect();
|
||||
by_count.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
|
||||
let mut shown = BTreeMap::new();
|
||||
let mut other = 0;
|
||||
for (i, (version, n)) in by_count.into_iter().enumerate() {
|
||||
if i < VERSIONS_SHOWN {
|
||||
shown.insert(version.to_owned(), round(n));
|
||||
} else {
|
||||
other += n;
|
||||
}
|
||||
}
|
||||
if other > 0 {
|
||||
*shown.entry("other".to_owned()).or_default() += round(other);
|
||||
}
|
||||
Count {
|
||||
playing: round(self.sessions.len() as u64),
|
||||
lan: round(lan),
|
||||
versions: shown,
|
||||
platforms: PLATFORMS
|
||||
.iter()
|
||||
.zip(platforms)
|
||||
.filter(|(_, n)| *n > 0)
|
||||
.map(|(p, n)| ((*p).to_owned(), round(n)))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sessions held now, counted or not yet forgotten.
|
||||
pub fn len(&self) -> usize {
|
||||
self.sessions.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.sessions.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ping(n: u32, version: &str, platform: &str, lan: bool) -> Ping {
|
||||
Ping {
|
||||
session: format!("{n:032x}"),
|
||||
version: version.into(),
|
||||
platform: platform.into(),
|
||||
lan,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sessions_count_until_the_window_passes() {
|
||||
let t = Instant::now();
|
||||
let mut live = Live::new(Duration::from_secs(120), 100);
|
||||
live.ping(&ping(1, "0.2.0", "linux", false), t).unwrap();
|
||||
live.ping(&ping(2, "0.2.0", "macos", true), t).unwrap();
|
||||
// The same session again is still one.
|
||||
live.ping(
|
||||
&ping(1, "0.2.0", "linux", false),
|
||||
t + Duration::from_secs(60),
|
||||
)
|
||||
.unwrap();
|
||||
let count = live.count(t + Duration::from_secs(61));
|
||||
assert_eq!((count.playing, count.lan), (2, 1));
|
||||
assert_eq!(count.versions, BTreeMap::from([("0.2.0".into(), 2)]));
|
||||
assert_eq!(
|
||||
count.platforms,
|
||||
BTreeMap::from([("linux".into(), 1), ("macos".into(), 1)])
|
||||
);
|
||||
// Session 2 stopped pinging two minutes ago; session 1 pinged a minute later.
|
||||
let count = live.count(t + Duration::from_secs(150));
|
||||
assert_eq!((count.playing, count.lan), (1, 0));
|
||||
assert_eq!(live.len(), 1);
|
||||
assert_eq!(live.count(t + Duration::from_secs(181)), Count::default());
|
||||
assert!(live.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_table_takes_no_new_session_until_one_expires() {
|
||||
let t = Instant::now();
|
||||
let mut live = Live::new(Duration::from_secs(120), 2);
|
||||
live.ping(&ping(1, "0.2.0", "linux", false), t).unwrap();
|
||||
live.ping(&ping(2, "0.2.0", "linux", false), t).unwrap();
|
||||
assert_eq!(live.ping(&ping(3, "0.2.0", "linux", false), t), Err(Full));
|
||||
// A known session still refreshes.
|
||||
live.ping(
|
||||
&ping(1, "0.2.0", "linux", false),
|
||||
t + Duration::from_secs(100),
|
||||
)
|
||||
.unwrap();
|
||||
let later = t + Duration::from_secs(130);
|
||||
live.ping(&ping(3, "0.2.0", "linux", false), later).unwrap();
|
||||
assert_eq!(live.count(later).playing, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rare_versions_are_summed_and_counts_rounded() {
|
||||
let t = Instant::now();
|
||||
let mut live = Live::new(Duration::from_secs(120), 1000);
|
||||
for n in 0..40 {
|
||||
live.ping(&ping(n, "0.2.0", "windows", n % 4 == 0), t)
|
||||
.unwrap();
|
||||
}
|
||||
for n in 0..(VERSIONS_SHOWN as u32 + 3) {
|
||||
live.ping(&ping(100 + n, &format!("dev {n}"), "other", false), t)
|
||||
.unwrap();
|
||||
}
|
||||
let count = live.count(t);
|
||||
assert_eq!(count.playing, 55);
|
||||
assert_eq!(count.lan, 10);
|
||||
assert_eq!(count.versions["0.2.0"], 40);
|
||||
assert_eq!(count.versions["other"], 4);
|
||||
assert_eq!(count.versions.len(), VERSIONS_SHOWN + 1);
|
||||
assert_eq!(count.platforms["windows"], 40);
|
||||
assert_eq!(count.platforms["other"], 15);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! The live count through its HTTP interface, and end to end with the game's ping and the
|
||||
//! launcher's read (`horizon_telemetry::live`).
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode, header};
|
||||
use horizon_telemetry::live::{self, Count, Ping};
|
||||
use horizon_telemetry_server::store::Store;
|
||||
use horizon_telemetry_server::{App, Config, router};
|
||||
use http_body_util::BodyExt;
|
||||
use tower::ServiceExt;
|
||||
|
||||
fn app(config: Config) -> Arc<App> {
|
||||
App::new(Store::open(":memory:").unwrap(), config)
|
||||
}
|
||||
|
||||
fn quick() -> Config {
|
||||
Config {
|
||||
live_per_hour: 100_000.0,
|
||||
live_window: Duration::from_secs(1),
|
||||
trust_proxy: true,
|
||||
..Config::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn ping(n: u32, version: &str, lan: bool) -> String {
|
||||
serde_json::to_string(&Ping {
|
||||
session: format!("{n:032x}"),
|
||||
version: version.into(),
|
||||
platform: "linux".into(),
|
||||
lan,
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn send(app: &Arc<App>, req: Request<Body>) -> (StatusCode, axum::http::HeaderMap, String) {
|
||||
let res = router(app.clone()).oneshot(req).await.unwrap();
|
||||
let (code, headers) = (res.status(), res.headers().clone());
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
(code, headers, String::from_utf8_lossy(&body).into_owned())
|
||||
}
|
||||
|
||||
async fn post(app: &Arc<App>, body: impl Into<Body>, from: &str) -> StatusCode {
|
||||
let req = Request::post("/v1/live")
|
||||
.header("x-forwarded-for", from)
|
||||
.body(body.into())
|
||||
.unwrap();
|
||||
send(app, req).await.0
|
||||
}
|
||||
|
||||
async fn count(app: &Arc<App>) -> Count {
|
||||
let req = Request::get("/v1/live")
|
||||
.header("x-forwarded-for", "198.51.100.1")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let (code, headers, body) = send(app, req).await;
|
||||
assert_eq!(code, StatusCode::OK, "{body}");
|
||||
assert_eq!(headers[header::CONTENT_TYPE], "application/json");
|
||||
assert_eq!(
|
||||
headers[header::ACCESS_CONTROL_ALLOW_ORIGIN],
|
||||
"https://playhorizon.dev"
|
||||
);
|
||||
serde_json::from_str(&body).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_count_while_they_ping_and_expire_after() {
|
||||
let app = app(quick());
|
||||
assert_eq!(
|
||||
post(&app, ping(1, "0.2.0", false), "203.0.113.1").await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(
|
||||
post(&app, ping(2, "0.2.0", true), "203.0.113.2").await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
// A second ping from the same session is still one player.
|
||||
assert_eq!(
|
||||
post(&app, ping(1, "0.2.0", false), "203.0.113.1").await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
let now = count(&app).await;
|
||||
assert_eq!((now.playing, now.lan), (2, 1));
|
||||
assert_eq!(now.versions["0.2.0"], 2);
|
||||
assert_eq!(now.platforms["linux"], 2);
|
||||
|
||||
// Session 1 keeps pinging; session 2 stops.
|
||||
for _ in 0..5 {
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
post(&app, ping(1, "0.2.0", false), "203.0.113.1").await;
|
||||
}
|
||||
let later = count(&app).await;
|
||||
assert_eq!((later.playing, later.lan), (1, 0));
|
||||
tokio::time::sleep(Duration::from_millis(1200)).await;
|
||||
assert_eq!(count(&app).await, Count::default());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bad_pings_are_refused() {
|
||||
let app = app(quick());
|
||||
let from = "203.0.113.3";
|
||||
assert_eq!(post(&app, "not json", from).await, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(
|
||||
post(&app, ping(1, "<b>0.2</b>", false), from).await,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
let extra = r#"{"session":"00000000000000000000000000000001","version":"0.2.0","platform":"linux","lan":false,"name":"Steve"}"#;
|
||||
assert_eq!(post(&app, extra, from).await, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(
|
||||
post(&app, "x".repeat(4096), from).await,
|
||||
StatusCode::PAYLOAD_TOO_LARGE
|
||||
);
|
||||
assert_eq!(count(&app).await.playing, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_address_is_rate_limited_on_its_own_bucket() {
|
||||
let app = app(Config {
|
||||
live_per_hour: 60.0,
|
||||
trust_proxy: true,
|
||||
..Config::default()
|
||||
});
|
||||
// A burst of a tenth of the hour's 60, then 429.
|
||||
let mut codes = Vec::new();
|
||||
for n in 0..8 {
|
||||
codes.push(post(&app, ping(n, "0.2.0", false), "203.0.113.4").await);
|
||||
}
|
||||
assert_eq!(
|
||||
codes
|
||||
.iter()
|
||||
.filter(|c| **c == StatusCode::NO_CONTENT)
|
||||
.count(),
|
||||
6
|
||||
);
|
||||
assert_eq!(codes[7], StatusCode::TOO_MANY_REQUESTS);
|
||||
// Another address is not held back.
|
||||
assert_eq!(
|
||||
post(&app, ping(9, "0.2.0", false), "203.0.113.5").await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_full_table_refuses_new_sessions() {
|
||||
let app = app(Config {
|
||||
live_max_sessions: 2,
|
||||
..quick()
|
||||
});
|
||||
for n in 0..2 {
|
||||
assert_eq!(
|
||||
post(&app, ping(n, "0.2.0", false), "203.0.113.6").await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
post(&app, ping(2, "0.2.0", false), "203.0.113.6").await,
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
);
|
||||
assert_eq!(
|
||||
post(&app, ping(1, "0.2.0", false), "203.0.113.6").await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_games_ping_and_the_launchers_read_reach_it_end_to_end() {
|
||||
let app = app(Config {
|
||||
live_window: Duration::from_secs(120),
|
||||
..quick()
|
||||
});
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let service = router(app.clone()).into_make_service_with_connect_info::<std::net::SocketAddr>();
|
||||
tokio::spawn(async move { axum::serve(listener, service).await.unwrap() });
|
||||
|
||||
let count = tokio::task::spawn_blocking(move || {
|
||||
let a = Ping::new(&live::session_id(), "0.2.0", false);
|
||||
let b = Ping::new(&live::session_id(), "dev 0.1.0", true);
|
||||
live::send(&url, &a)?;
|
||||
live::send(&url, &b)?;
|
||||
live::fetch(&url)
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!((count.playing, count.lan), (2, 1));
|
||||
assert_eq!(count.versions.len(), 2);
|
||||
assert_eq!(count.platforms[live::platform()], 2);
|
||||
}
|
||||
@@ -13,12 +13,14 @@ serde_json = "1"
|
||||
ruzstd = "0.9"
|
||||
# The random install ID and outbox file names.
|
||||
getrandom = "0.3"
|
||||
# Sending, for the launcher; the ingest server builds without it.
|
||||
# Sending, for the launcher (and the game's "I'm playing" ping); the ingest server builds without it.
|
||||
ureq = { version = "2", default-features = false, features = ["tls"], optional = true }
|
||||
|
||||
[features]
|
||||
default = ["upload"]
|
||||
default = ["upload", "live"]
|
||||
upload = ["dep:ureq"]
|
||||
# The "I'm playing" ping and reading the live count (`live`), for the game and the launcher.
|
||||
live = ["dep:ureq"]
|
||||
|
||||
[[test]]
|
||||
name = "consent_gating"
|
||||
|
||||
@@ -6,11 +6,15 @@
|
||||
//! connection. Items are small summaries (percentiles and histogram buckets, never raw streams),
|
||||
//! dated to the day, with no account, world, server or address in them ([`scrub`]); they leave
|
||||
//! in zstd batches ([`batch`]). `docs/telemetry.md` lists every field.
|
||||
//!
|
||||
//! The one exception is [`live`]: the anonymous "I'm playing" ping the game sends while it
|
||||
//! runs, for the live player count. It holds no install ID and nothing about the player.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub mod batch;
|
||||
pub mod consent;
|
||||
pub mod live;
|
||||
pub mod outbox;
|
||||
pub mod payload;
|
||||
pub mod scrub;
|
||||
@@ -29,8 +33,9 @@ pub const SCHEMA: u32 = 1;
|
||||
/// and until the player answers nothing new is kept or sent.
|
||||
pub const CONSENT_VERSION: u32 = 1;
|
||||
|
||||
/// The ingest server, or none while there isn't one: then nothing is ever sent and the outbox
|
||||
/// stays within its caps. `HORIZON_TELEMETRY_URL` overrides it (tests, a local server).
|
||||
/// The ingest server, or none while there isn't one: then nothing is ever sent (no ping either)
|
||||
/// and the outbox stays within its caps. `HORIZON_TELEMETRY_URL` overrides it (tests, a local
|
||||
/// server).
|
||||
pub const DEFAULT_ENDPOINT: Option<&str> = None;
|
||||
|
||||
/// Where items are sent, if anywhere.
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! The anonymous "I'm playing" ping, and the live count it feeds ("N playing now" in the
|
||||
//! launcher).
|
||||
//!
|
||||
//! Unlike everything else in this crate it does not wait for consent: Ludovic decided
|
||||
//! (2026-10-22) to count every player and tell them, in the launcher's first-run question, its
|
||||
//! Settings and the privacy page. So a ping holds only what the count needs: a random session ID
|
||||
//! made when the game starts and kept only in its memory (not the install ID), the Horizon
|
||||
//! version, the platform and whether a LAN or play-with-friends world is open. The game sends
|
||||
//! one every [`INTERVAL`]; the server counts a session while its last ping is under
|
||||
//! [`WINDOW`] old, keeps nothing on disk and serves the counts rounded ([`round`]).
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How often the game pings while it runs.
|
||||
pub const INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
/// How long a session counts after its last ping: two pings, so one lost on the way doesn't
|
||||
/// drop it.
|
||||
pub const WINDOW: Duration = Duration::from_secs(120);
|
||||
|
||||
/// The platforms a ping may name; anything else is `other`.
|
||||
pub const PLATFORMS: [&str; 4] = ["linux", "macos", "windows", "other"];
|
||||
|
||||
/// The largest ping body the server reads.
|
||||
pub const MAX_PING_BYTES: usize = 512;
|
||||
|
||||
const MAX_VERSION: usize = 40;
|
||||
|
||||
/// One "I'm playing", as it is sent: `{"session":"…","version":"…","platform":"…","lan":false}`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Ping {
|
||||
/// 128 random bits in hex, made when the game starts ([`session_id`]) and never written down.
|
||||
pub session: String,
|
||||
/// The release (`v2026.10.15`, `0.2.0`) or `dev 0.1.0` for a build from source.
|
||||
pub version: String,
|
||||
/// One of [`PLATFORMS`].
|
||||
pub platform: String,
|
||||
/// A world is open to LAN or to friends over the internet.
|
||||
pub lan: bool,
|
||||
}
|
||||
|
||||
impl Ping {
|
||||
pub fn new(session: &str, version: &str, lan: bool) -> Self {
|
||||
Self {
|
||||
session: session.to_owned(),
|
||||
version: version.to_owned(),
|
||||
platform: platform().to_owned(),
|
||||
lan,
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the server refuses this ping, if it does.
|
||||
pub fn check(&self) -> Result<(), &'static str> {
|
||||
if !crate::consent::is_install_id(&self.session) {
|
||||
return Err("session: 32 lowercase hex digits");
|
||||
}
|
||||
let version_ok = !self.version.is_empty()
|
||||
&& self.version.len() <= MAX_VERSION
|
||||
&& self
|
||||
.version
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b" .+-_".contains(&b));
|
||||
if !version_ok {
|
||||
return Err("version: at most 40 letters, digits, spaces and .+-_");
|
||||
}
|
||||
if !PLATFORMS.contains(&self.platform.as_str()) {
|
||||
return Err("platform: linux, macos, windows or other");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A new session ID: 128 random bits in hex.
|
||||
pub fn session_id() -> String {
|
||||
crate::random_hex(16)
|
||||
}
|
||||
|
||||
/// This machine's entry in [`PLATFORMS`].
|
||||
pub fn platform() -> &'static str {
|
||||
match std::env::consts::OS {
|
||||
os @ ("linux" | "macos" | "windows") => os,
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
|
||||
/// The live count, as `GET /v1/live` serves it: every number already [`round`]ed.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Count {
|
||||
/// Sessions that pinged within the window.
|
||||
pub playing: u64,
|
||||
/// Of those, the ones with a LAN or play-with-friends world open.
|
||||
pub lan: u64,
|
||||
/// Per version: the most played ones, the rest summed under `other`.
|
||||
pub versions: BTreeMap<String, u64>,
|
||||
/// Per platform.
|
||||
pub platforms: BTreeMap<String, u64>,
|
||||
}
|
||||
|
||||
/// Rounds a count for showing: exact under 10, then to the nearest 5 under 100, the nearest 10
|
||||
/// under 1000 and the nearest 100 above. Small numbers stay true; large ones don't pretend to
|
||||
/// a precision a two-minute window doesn't have.
|
||||
pub fn round(n: u64) -> u64 {
|
||||
let step = match n {
|
||||
0..10 => return n,
|
||||
10..100 => 5,
|
||||
100..1000 => 10,
|
||||
_ => 100,
|
||||
};
|
||||
(n + step / 2) / step * step
|
||||
}
|
||||
|
||||
/// Sends `ping` to `endpoint` (`https://host`, without a trailing slash).
|
||||
#[cfg(feature = "live")]
|
||||
pub fn send(endpoint: &str, ping: &Ping) -> Result<(), String> {
|
||||
agent()
|
||||
.post(&format!("{endpoint}/v1/live"))
|
||||
.set("Content-Type", "application/json")
|
||||
.send_string(&serde_json::to_string(ping).map_err(|e| e.to_string())?)
|
||||
.map(drop)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The live count at `endpoint`.
|
||||
#[cfg(feature = "live")]
|
||||
pub fn fetch(endpoint: &str) -> Result<Count, String> {
|
||||
let body = agent()
|
||||
.get(&format!("{endpoint}/v1/live"))
|
||||
.call()
|
||||
.map_err(|e| e.to_string())?
|
||||
.into_string()
|
||||
.map_err(|e| e.to_string())?;
|
||||
serde_json::from_str(&body).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(feature = "live")]
|
||||
fn agent() -> ureq::Agent {
|
||||
ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(5))
|
||||
.build()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ping() -> Ping {
|
||||
Ping::new(&session_id(), "v2026.10.15", false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ping_holds_only_the_four_fields() {
|
||||
let json = serde_json::to_value(Ping::new(&"a".repeat(32), "0.2.0", true)).unwrap();
|
||||
let mut keys: Vec<&str> = json
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.map(|k| k.as_str())
|
||||
.collect();
|
||||
keys.sort_unstable();
|
||||
assert_eq!(keys, ["lan", "platform", "session", "version"]);
|
||||
assert!(serde_json::to_string(&ping()).unwrap().len() < MAX_PING_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_ids_are_fresh_each_time() {
|
||||
let (a, b) = (session_id(), session_id());
|
||||
assert_ne!(a, b);
|
||||
assert!(ping().check().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_pings_are_refused() {
|
||||
let bad = |f: fn(&mut Ping)| {
|
||||
let mut p = ping();
|
||||
f(&mut p);
|
||||
p.check().is_err()
|
||||
};
|
||||
assert!(bad(|p| p.session = "ABC".into()));
|
||||
assert!(bad(|p| p.session = "G".repeat(32)));
|
||||
assert!(bad(|p| p.version = String::new()));
|
||||
assert!(bad(|p| p.version = "1".repeat(41)));
|
||||
assert!(bad(|p| p.version = "<script>".into()));
|
||||
assert!(bad(|p| p.platform = "haiku".into()));
|
||||
assert!(!bad(|p| p.version = "dev 0.1.0".into()));
|
||||
let extra = r#"{"session":"00000000000000000000000000000000","version":"0.2.0","platform":"linux","lan":false,"name":"Steve"}"#;
|
||||
assert!(serde_json::from_str::<Ping>(extra).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_round_more_as_they_grow() {
|
||||
let cases = [
|
||||
(0, 0),
|
||||
(1, 1),
|
||||
(9, 9),
|
||||
(10, 10),
|
||||
(12, 10),
|
||||
(13, 15),
|
||||
(97, 95),
|
||||
(98, 100),
|
||||
(104, 100),
|
||||
(105, 110),
|
||||
(994, 990),
|
||||
(995, 1000),
|
||||
(1049, 1000),
|
||||
(1050, 1100),
|
||||
];
|
||||
for (n, shown) in cases {
|
||||
assert_eq!(round(n), shown, "{n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,9 @@ impl<L: LevelAccess + ?Sized> PlacementContext for LevelFeatureWorld<'_, '_, L>
|
||||
) -> Result<bool, PlacementQueryError> {
|
||||
Ok(self.sim.b.has_flag(state, state_flags::COLLISION_EMPTY))
|
||||
}
|
||||
fn can_occlude(&mut self, state: BlockStateId) -> Result<bool, PlacementQueryError> {
|
||||
Ok(self.sim.b.has_flag(state, state_flags::CAN_OCCLUDE))
|
||||
}
|
||||
/// BeehiveDecorator's bees go into the nest's block entity (the tree
|
||||
/// checked the nest is there).
|
||||
fn store_beehive_occupants(
|
||||
|
||||
@@ -816,6 +816,19 @@ impl PlacementContext for World<'_> {
|
||||
.is_face_sturdy(self, state, position, direction, SupportType::Center)
|
||||
.map_err(query)
|
||||
}
|
||||
fn can_occlude(&mut self, state: BlockStateId) -> Result<bool, PlacementQueryError> {
|
||||
if let Some(behaviours) = self.behaviours {
|
||||
return Ok(behaviours.has_flag(state, crate::level::data::state_flags::CAN_OCCLUDE));
|
||||
}
|
||||
let properties = &self.blocks()?.properties;
|
||||
let name = properties
|
||||
.registry()
|
||||
.state(state)
|
||||
.ok_or(PlacementQueryError::Unavailable)?
|
||||
.name
|
||||
.clone();
|
||||
Ok(properties.definition(&name).is_some_and(|d| d.can_occlude))
|
||||
}
|
||||
fn collision_full_block(
|
||||
&mut self,
|
||||
state: BlockStateId,
|
||||
|
||||
@@ -211,6 +211,13 @@ pub trait PlacementContext {
|
||||
fn water_at(&mut self, _position: [i32; 3]) -> Result<bool, PlacementQueryError> {
|
||||
Err(PlacementQueryError::Unavailable)
|
||||
}
|
||||
/// `BlockState.canOcclude()` of a state.
|
||||
fn can_occlude(
|
||||
&mut self,
|
||||
_state: crate::registry::BlockStateId,
|
||||
) -> Result<bool, PlacementQueryError> {
|
||||
Err(PlacementQueryError::Unavailable)
|
||||
}
|
||||
/// Multiface attachment: neighbor support, then empty-context collision.
|
||||
fn attachment_at(
|
||||
&mut self,
|
||||
|
||||
@@ -3,9 +3,14 @@
|
||||
//! one pool element at a random spot of the chunk, at a height its
|
||||
//! placement finds in the noise columns under the element's corners and
|
||||
//! centre ([`StartContext::noise_column`]).
|
||||
//!
|
||||
//! Its PiecedStructure (the fountain) starts the same way, then lays out
|
||||
//! the element's jigsaw children with vanilla's jigsaw
|
||||
//! ([`super::jigsaw::add_children`]): `horizon:pieced` on the structure
|
||||
//! holds its `max_depth` and `max_distance_from_center`.
|
||||
use super::{
|
||||
BoundingBox, Rotation, StructureResources,
|
||||
jigsaw::{PoolElement, PoolPiece, Pools},
|
||||
jigsaw::{JigsawConfig, PoolElement, PoolPiece, Pools, add_children},
|
||||
start::{NoiseBlock, NoiseColumn, StartContext},
|
||||
};
|
||||
use crate::{
|
||||
@@ -51,6 +56,8 @@ impl Placement {
|
||||
pub struct Def {
|
||||
pub pool: String,
|
||||
pub placement: Placement,
|
||||
/// PiecedStructure's jigsaw: (max depth, max distance from the centre).
|
||||
pub pieced: Option<(i32, i32)>,
|
||||
}
|
||||
impl Def {
|
||||
pub fn decode(v: &Value) -> Result<Self, DecodeError> {
|
||||
@@ -61,11 +68,21 @@ impl Def {
|
||||
.ok_or(DecodeError::Field("formations template"))?
|
||||
.to_owned(),
|
||||
placement: Placement::decode(v["placement"].as_str().unwrap_or_default())?,
|
||||
pieced: match v.get("horizon:pieced") {
|
||||
None => None,
|
||||
Some(p) => {
|
||||
let int = |k: &'static str| {
|
||||
p[k].as_i64().map(|n| n as i32).ok_or(DecodeError::Field(k))
|
||||
};
|
||||
Some((int("max_depth")?, int("max_distance_from_center")?))
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// SimpleStructure.findGenerationPoint: the start's position and piece.
|
||||
/// SimpleStructure.findGenerationPoint, or PiecedStructure's: the start's
|
||||
/// position and pieces.
|
||||
pub fn generate(
|
||||
def: &Def,
|
||||
context: &mut impl StartContext,
|
||||
@@ -74,7 +91,7 @@ pub fn generate(
|
||||
bindings: &FeatureBlockBindings<'_>,
|
||||
random: &mut impl RandomSource,
|
||||
chunk: ChunkPos,
|
||||
) -> Option<([i32; 3], PoolPiece)> {
|
||||
) -> Option<([i32; 3], Vec<PoolPiece>)> {
|
||||
let element = pools
|
||||
.get(&def.pool, resources, bindings)?
|
||||
.random_template(random);
|
||||
@@ -88,7 +105,7 @@ pub fn generate(
|
||||
let height = find_height(def.placement, context, b, random)?;
|
||||
let ground = element.ground_level_delta();
|
||||
let y = height - ground + 1;
|
||||
if y < context.min_y() {
|
||||
if def.pieced.is_none() && y < context.min_y() {
|
||||
return None;
|
||||
}
|
||||
let piece = PoolPiece {
|
||||
@@ -101,7 +118,46 @@ pub fn generate(
|
||||
// LiquidSettings.APPLY_WATERLOGGING.
|
||||
waterlogging: true,
|
||||
};
|
||||
Some(([x, y, z], piece))
|
||||
let Some((max_depth, distance)) = def.pieced else {
|
||||
return Some(([x, y, z], vec![piece]));
|
||||
};
|
||||
// PiecedStructure.addPieces: the start sits at the element's centre, one
|
||||
// above the height found, and its children may fill the box of
|
||||
// `distance` around it (not clamped to the world's height) less its own.
|
||||
let (cx, cy, cz) = (
|
||||
(b.max[0] + b.min[0]) / 2,
|
||||
height + 1,
|
||||
(b.max[2] + b.min[2]) / 2,
|
||||
);
|
||||
let mut pieces = vec![piece];
|
||||
if max_depth > 0 {
|
||||
let config = JigsawConfig {
|
||||
start_pool: &def.pool,
|
||||
start_jigsaw: None,
|
||||
max_depth,
|
||||
use_expansion_hack: false,
|
||||
project_to: None,
|
||||
max_distance: [distance, distance],
|
||||
aliases: &Default::default(),
|
||||
padding: [0, 0],
|
||||
waterlogging: true,
|
||||
};
|
||||
let container = BoundingBox::new(
|
||||
[cx - distance, cy - distance, cz - distance],
|
||||
[cx + distance, cy + distance, cz + distance],
|
||||
);
|
||||
add_children(
|
||||
&config,
|
||||
context,
|
||||
pools,
|
||||
resources,
|
||||
bindings,
|
||||
random,
|
||||
&mut pieces,
|
||||
container,
|
||||
);
|
||||
}
|
||||
Some(([cx, cy, cz], pieces))
|
||||
}
|
||||
|
||||
/// The four corners (min x min z, min x max z, max x max z, max x min z)
|
||||
@@ -335,6 +391,15 @@ mod tests {
|
||||
);
|
||||
assert!(Placement::decode("floating").is_err());
|
||||
let def = Def::decode(&serde_json::json!({"template": "a:b", "placement": "surface"}));
|
||||
assert_eq!(def.unwrap().placement, Placement::Surface);
|
||||
let def = def.unwrap();
|
||||
assert_eq!((def.placement, def.pieced), (Placement::Surface, None));
|
||||
let pieced = Def::decode(
|
||||
&serde_json::json!({"template": "a:b", "placement": "surface",
|
||||
"horizon:pieced": {"max_depth": 2, "max_distance_from_center": 116}}),
|
||||
);
|
||||
assert_eq!(pieced.unwrap().pieced, Some((2, 116)));
|
||||
let broken = serde_json::json!({"template": "a:b", "placement": "surface",
|
||||
"horizon:pieced": {"max_depth": 2}});
|
||||
assert!(Def::decode(&broken).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -690,25 +690,53 @@ pub fn assemble(
|
||||
let [h, v] = config.max_distance;
|
||||
let low_y = (cy - v).max(context.min_y() + config.padding[0]);
|
||||
let high_y = (cy + v + 1).min(context.max_y() + 1 - config.padding[1]);
|
||||
let free = Rc::new(RefCell::new(Free {
|
||||
container: BoundingBox::new([cx - h, low_y, cz - h], [cx + h, high_y - 1, cz + h]),
|
||||
removed: vec![pieces[0].bounding_box],
|
||||
}));
|
||||
let mut placer = Placer {
|
||||
let container = BoundingBox::new([cx - h, low_y, cz - h], [cx + h, high_y - 1, cz + h]);
|
||||
add_children(
|
||||
config,
|
||||
context,
|
||||
pools,
|
||||
resources,
|
||||
bindings,
|
||||
pieces: &mut pieces,
|
||||
queue: BTreeMap::new(),
|
||||
};
|
||||
placer.children(0, free, 0, context, random);
|
||||
while let Some(state) = placer.next() {
|
||||
placer.children(state.piece, state.free, state.depth, context, random);
|
||||
}
|
||||
random,
|
||||
&mut pieces,
|
||||
container,
|
||||
);
|
||||
}
|
||||
Some(([cx, cy, cz], pieces))
|
||||
}
|
||||
|
||||
/// The inner JigsawPlacement.addPieces: lays out the children of
|
||||
/// `pieces[0]`, a start piece already placed, to `config.max_depth`,
|
||||
/// within `container` (inclusive) less the start's box. A structure with
|
||||
/// its own start (Formations' pieced one) reaches the jigsaw layout here.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn add_children(
|
||||
config: &JigsawConfig<'_>,
|
||||
context: &mut impl JigsawContext,
|
||||
pools: &Pools,
|
||||
resources: &StructureResources,
|
||||
bindings: &FeatureBlockBindings<'_>,
|
||||
random: &mut impl RandomSource,
|
||||
pieces: &mut Vec<PoolPiece>,
|
||||
container: BoundingBox,
|
||||
) {
|
||||
let free = Rc::new(RefCell::new(Free {
|
||||
container,
|
||||
removed: vec![pieces[0].bounding_box],
|
||||
}));
|
||||
let mut placer = Placer {
|
||||
config,
|
||||
pools,
|
||||
resources,
|
||||
bindings,
|
||||
pieces,
|
||||
queue: BTreeMap::new(),
|
||||
};
|
||||
placer.children(0, free, 0, context, random);
|
||||
while let Some(state) = placer.next() {
|
||||
placer.children(state.piece, state.free, state.depth, context, random);
|
||||
}
|
||||
}
|
||||
struct Placer<'a, 'p> {
|
||||
config: &'a JigsawConfig<'a>,
|
||||
pools: &'a Pools,
|
||||
|
||||
@@ -331,6 +331,9 @@ pub enum Processor {
|
||||
/// `horizon:waterlog_in_world_water` (Repurposed Structures'): blocks
|
||||
/// are waterlogged where the world holds water, dry where it does not.
|
||||
WaterlogInWorldWater,
|
||||
/// `horizon:mineshaft_sky_view` (Repurposed Structures' mineshafts):
|
||||
/// nothing above the ocean floor but rails on solid ground.
|
||||
MineshaftSkyView,
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ProcessorList(pub Vec<Processor>);
|
||||
@@ -827,6 +830,7 @@ impl Processor {
|
||||
}
|
||||
"horizon:waterlog" => Self::Waterlog,
|
||||
"horizon:waterlog_in_world_water" => Self::WaterlogInWorldWater,
|
||||
"horizon:mineshaft_sky_view" => Self::MineshaftSkyView,
|
||||
"horizon:keep_world_block" => {
|
||||
Self::KeepWorldBlock(Box::new(sea_level::KeepWorldBlock::decode(value)?))
|
||||
}
|
||||
@@ -1219,6 +1223,9 @@ fn process_block<W: PlacementContext>(
|
||||
settings,
|
||||
);
|
||||
}
|
||||
Processor::MineshaftSkyView => {
|
||||
return sea_level::MineshaftSkyView::process(world, resources.registry, info);
|
||||
}
|
||||
Processor::Pick(pick) => match name(info.state) == pick.block {
|
||||
true => {
|
||||
let mut out = settings.with_random(info.pos, |r| pick.apply(info.clone(), r));
|
||||
|
||||
@@ -13,10 +13,14 @@
|
||||
//! And from Repurposed Structures':
|
||||
//! - `horizon:waterlog_in_world_water`: a block that can be waterlogged is
|
||||
//! where the world holds water and is dry where it does not (its
|
||||
//! WaterlogWhenReplacingWaterProcessor).
|
||||
//! WaterlogWhenReplacingWaterProcessor);
|
||||
//! - `horizon:mineshaft_sky_view`: its mineshafts are not built above the
|
||||
//! ocean floor, but keep their rails on solid ground (its
|
||||
//! MineshaftSkyViewProcessor).
|
||||
use super::{PlaceSettings, ProcessResult, pillars::outside_chunk};
|
||||
use crate::{
|
||||
fluid::{FluidKind, FluidState},
|
||||
heightmap::HeightmapType,
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
worldgen::{DecodeError, placement::PlacementContext, structure::BlockInfo},
|
||||
};
|
||||
@@ -152,11 +156,7 @@ impl WaterlogInWorldWater {
|
||||
if !state.properties.contains_key("waterlogged") || outside_chunk(settings, info.pos) {
|
||||
return Ok(Some(info));
|
||||
}
|
||||
let here = world.block_state(info.pos)?;
|
||||
let water = registry
|
||||
.state(here)
|
||||
.and_then(|s| FluidState::from_block(s).ok())
|
||||
.is_some_and(|f| f.kind().same_family(FluidKind::Water));
|
||||
let water = world_water(world, registry, info.pos)?;
|
||||
// The mod's height check (min to max build height) holds for every
|
||||
// block of the chunk.
|
||||
if water && world.inside_build_height(info.pos)? {
|
||||
@@ -172,6 +172,56 @@ impl WaterlogInWorldWater {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the world's block at `pos` holds water (still or flowing, or a
|
||||
/// waterlogged block): `getFluidState().is(FluidTags.WATER)`.
|
||||
fn world_water<W: PlacementContext>(
|
||||
world: &mut W,
|
||||
registry: &BlockRegistry,
|
||||
pos: [i32; 3],
|
||||
) -> Result<bool, crate::worldgen::placement::PlacementQueryError> {
|
||||
let here = world.block_state(pos)?;
|
||||
Ok(registry
|
||||
.state(here)
|
||||
.and_then(|s| FluidState::from_block(s).ok())
|
||||
.is_some_and(|f| f.kind().same_family(FluidKind::Water)))
|
||||
}
|
||||
|
||||
/// `horizon:mineshaft_sky_view`: MineshaftSkyViewProcessor. A plain rail
|
||||
/// whose world block below can occlude is placed, waterlogged where the
|
||||
/// world holds water; any other block at or above the world's
|
||||
/// `OCEAN_FLOOR_WG` height in its column is not placed, so a mineshaft cut
|
||||
/// by a valley or a ravine is not built in the open.
|
||||
pub struct MineshaftSkyView;
|
||||
impl MineshaftSkyView {
|
||||
pub(super) fn process<W: PlacementContext>(
|
||||
world: &mut W,
|
||||
registry: &BlockRegistry,
|
||||
info: BlockInfo,
|
||||
) -> ProcessResult {
|
||||
let [x, y, z] = info.pos;
|
||||
let rail = registry
|
||||
.state(info.state)
|
||||
.filter(|s| s.name == "minecraft:rail");
|
||||
if let Some(rail) = rail {
|
||||
let below = world.block_state([x, y - 1, z])?;
|
||||
if world.can_occlude(below)? {
|
||||
let mut set = rail.clone();
|
||||
let water = world_water(world, registry, info.pos)?;
|
||||
set.properties
|
||||
.insert("waterlogged".into(), water.to_string());
|
||||
return Ok(Some(BlockInfo {
|
||||
state: registry.id(&set).unwrap_or(info.state),
|
||||
..info
|
||||
}));
|
||||
}
|
||||
}
|
||||
if y >= world.height(HeightmapType::OceanFloorWg, x, z)? {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(info))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -198,8 +248,19 @@ mod tests {
|
||||
fn min_y(&mut self) -> Result<i32, PlacementQueryError> {
|
||||
Ok(-64)
|
||||
}
|
||||
fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result<i32, PlacementQueryError> {
|
||||
Err(PlacementQueryError::Unavailable)
|
||||
/// The ocean floor is at 64 everywhere.
|
||||
fn height(
|
||||
&mut self,
|
||||
kind: HeightmapType,
|
||||
_: i32,
|
||||
_: i32,
|
||||
) -> Result<i32, PlacementQueryError> {
|
||||
assert_eq!(kind, HeightmapType::OceanFloorWg);
|
||||
Ok(64)
|
||||
}
|
||||
/// Only stone can occlude.
|
||||
fn can_occlude(&mut self, state: BlockStateId) -> Result<bool, PlacementQueryError> {
|
||||
Ok(state == BlockStateId(6))
|
||||
}
|
||||
fn sea_level(&mut self) -> Result<i32, PlacementQueryError> {
|
||||
Ok(63)
|
||||
@@ -226,12 +287,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// 0 air, 1 cave air, 2 water, 3/4 slab dry/wet, 5 purpur slab, 6 stone.
|
||||
// 0 air, 1 cave air, 2 water, 3/4 slab dry/wet, 5 purpur slab, 6 stone,
|
||||
// 7/8 rail dry/wet.
|
||||
fn registry() -> BlockRegistry {
|
||||
let row = |name: &str, props: Value| json!([name, false, false, "", {"id": name, "properties": props}]);
|
||||
let facts = json!({"defaults": {"minecraft:air": 0, "minecraft:cave_air": 1,
|
||||
"minecraft:water": 2, "minecraft:prismarine_slab": 3, "minecraft:purpur_slab": 5,
|
||||
"minecraft:stone": 6},
|
||||
"minecraft:stone": 6, "minecraft:rail": 7},
|
||||
"states": [
|
||||
["minecraft:air", false, false, "", "minecraft:air"],
|
||||
["minecraft:cave_air", false, false, "", "minecraft:cave_air"],
|
||||
@@ -239,7 +301,9 @@ mod tests {
|
||||
row("minecraft:prismarine_slab", json!({"waterlogged": "false"})),
|
||||
row("minecraft:prismarine_slab", json!({"waterlogged": "true"})),
|
||||
["minecraft:purpur_slab", false, false, "", "minecraft:purpur_slab"],
|
||||
["minecraft:stone", false, false, "", "minecraft:stone"]]});
|
||||
["minecraft:stone", false, false, "", "minecraft:stone"],
|
||||
row("minecraft:rail", json!({"shape": "north_south", "waterlogged": "false"})),
|
||||
row("minecraft:rail", json!({"shape": "north_south", "waterlogged": "true"}))]});
|
||||
BlockRegistry::from_facts_json(facts.to_string().as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
@@ -356,4 +420,29 @@ mod tests {
|
||||
assert_eq!(run(&mut sea, info(6, [3, 40, 3])), BlockStateId(6));
|
||||
assert_eq!(run(&mut sea, info(4, [16, 40, 3])), BlockStateId(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mineshafts_stop_at_the_ocean_floor_but_keep_grounded_rails() {
|
||||
let registry = registry();
|
||||
let mut sea = Sea {
|
||||
world: BlockStateId(6),
|
||||
marked: vec![],
|
||||
ticks: vec![],
|
||||
};
|
||||
let run = |sea: &mut Sea, i: BlockInfo| {
|
||||
MineshaftSkyView::process(sea, ®istry, i)
|
||||
.unwrap()
|
||||
.map(|i| i.state)
|
||||
};
|
||||
// Over stone a rail stays, above the floor too, dry as the world is.
|
||||
assert_eq!(run(&mut sea, info(8, [3, 80, 3])), Some(BlockStateId(7)));
|
||||
// Anything else stops at the floor (64).
|
||||
assert_eq!(run(&mut sea, info(6, [3, 63, 3])), Some(BlockStateId(6)));
|
||||
assert_eq!(run(&mut sea, info(6, [3, 64, 3])), None);
|
||||
assert_eq!(run(&mut sea, info(0, [3, 90, 3])), None);
|
||||
// Over water a rail is like any block.
|
||||
sea.world = BlockStateId(2);
|
||||
assert_eq!(run(&mut sea, info(7, [3, 70, 3])), None);
|
||||
assert_eq!(run(&mut sea, info(8, [3, 40, 3])), Some(BlockStateId(8)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,13 +149,24 @@ pub struct StructureSet {
|
||||
/// and none within `chunk_count` chunks of any of several sets
|
||||
/// (`"horizon:exclusion_zone"`: `other_sets`, `chunk_count`).
|
||||
min_distance: Option<i64>,
|
||||
avoid: Option<(Vec<String>, i32)>,
|
||||
avoid: Option<Avoid>,
|
||||
/// `"horizon:ring_sections"`: starts only in odd rings around the origin.
|
||||
rings: Option<RingSections>,
|
||||
/// `"horizon:avoid_biomes"`: no start with one of these biomes near.
|
||||
avoid_biomes: Option<AvoidBiomes>,
|
||||
}
|
||||
|
||||
/// `"horizon:exclusion_zone"`: no start within `chunk_count` chunks of a
|
||||
/// start of any of `sets`. With `"their_zones": false` those sets' own
|
||||
/// exclusion zones are not checked (Mo' Structures' ModStructurePlacement
|
||||
/// tests the sets it avoids by their spread and frequency alone).
|
||||
#[derive(Debug, Clone)]
|
||||
struct Avoid {
|
||||
sets: Vec<String>,
|
||||
chunk_count: i32,
|
||||
their_zones: bool,
|
||||
}
|
||||
|
||||
/// YUNG's Better Strongholds' placement (BetterStrongholdsPlacement
|
||||
/// .isPlacementChunk): the world is cut into rings `thickness` chunks wide,
|
||||
/// the first one starting `distance_to_first_ring` chunks out; a start is
|
||||
@@ -444,16 +455,15 @@ impl StructureRegistry {
|
||||
min_distance: p
|
||||
.get("horizon:min_distance_from_world_origin")
|
||||
.and_then(Value::as_i64),
|
||||
avoid: p.get("horizon:exclusion_zone").map(|z| {
|
||||
(
|
||||
z["other_sets"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|s| Some(s.as_str()?.to_owned()))
|
||||
.collect(),
|
||||
z["chunk_count"].as_i64().unwrap_or(0) as i32,
|
||||
)
|
||||
avoid: p.get("horizon:exclusion_zone").map(|z| Avoid {
|
||||
sets: z["other_sets"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|s| Some(s.as_str()?.to_owned()))
|
||||
.collect(),
|
||||
chunk_count: z["chunk_count"].as_i64().unwrap_or(0) as i32,
|
||||
their_zones: z["their_zones"].as_bool().unwrap_or(true),
|
||||
}),
|
||||
rings: p.get("horizon:ring_sections").map(RingSections::decode),
|
||||
avoid_biomes: p
|
||||
@@ -534,6 +544,19 @@ impl StructureRegistry {
|
||||
x: i32,
|
||||
z: i32,
|
||||
rings: &Rings,
|
||||
) -> bool {
|
||||
self.structure_chunk(set, seed, x, z, rings, true)
|
||||
}
|
||||
/// [`Self::is_structure_chunk`]; without the set's exclusion zones when
|
||||
/// `zones` is false.
|
||||
fn structure_chunk(
|
||||
&self,
|
||||
set: &StructureSet,
|
||||
seed: i64,
|
||||
x: i32,
|
||||
z: i32,
|
||||
rings: &Rings,
|
||||
zones: bool,
|
||||
) -> bool {
|
||||
let placed = match set.placement {
|
||||
Placement::RandomSpread {
|
||||
@@ -576,24 +599,28 @@ impl StructureRegistry {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some((others, range)) = &set.avoid {
|
||||
if others
|
||||
.iter()
|
||||
.any(|other| self.has_start_in_range(other, seed, x, z, *range, rings))
|
||||
{
|
||||
if let Some(avoid) = set.avoid.as_ref().filter(|_| zones) {
|
||||
if avoid.sets.iter().any(|other| {
|
||||
let range = avoid.chunk_count;
|
||||
self.has_start_in_range(other, seed, x, z, range, rings, avoid.their_zones)
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if set.frequency < 1. && !reduce(set.reduction, seed, set.salt, x, z, set.frequency) {
|
||||
return false;
|
||||
}
|
||||
match &set.exclusion {
|
||||
Some((other, range)) => !self.has_start_in_range(other, seed, x, z, *range, rings),
|
||||
match set.exclusion.as_ref().filter(|_| zones) {
|
||||
Some((other, range)) => {
|
||||
!self.has_start_in_range(other, seed, x, z, *range, rings, true)
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
/// ChunkGeneratorStructureState.hasStructureChunkInRange: whether set
|
||||
/// `other` places a structure within `range` chunks of (`x`, `z`).
|
||||
/// `other` places a structure within `range` chunks of (`x`, `z`),
|
||||
/// checking its own exclusion zones when `zones` is true.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn has_start_in_range(
|
||||
&self,
|
||||
other: &str,
|
||||
@@ -602,12 +629,14 @@ impl StructureRegistry {
|
||||
z: i32,
|
||||
range: i32,
|
||||
rings: &Rings,
|
||||
zones: bool,
|
||||
) -> bool {
|
||||
let Some(other) = self.sets.iter().find(|s| s.name == other) else {
|
||||
return false;
|
||||
};
|
||||
(x - range..=x + range).any(|tx| {
|
||||
(z - range..=z + range).any(|tz| self.is_structure_chunk(other, seed, tx, tz, rings))
|
||||
(z - range..=z + range)
|
||||
.any(|tz| self.structure_chunk(other, seed, tx, tz, rings, zones))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1144,7 +1173,7 @@ fn try_generate(
|
||||
(position, legacy(vec![piece]))
|
||||
}
|
||||
StructureKind::Formations(formations) => {
|
||||
let (position, piece) = super::formations::generate(
|
||||
let (position, pieces) = super::formations::generate(
|
||||
formations,
|
||||
context,
|
||||
®istry.pools,
|
||||
@@ -1153,7 +1182,7 @@ fn try_generate(
|
||||
&mut random,
|
||||
chunk,
|
||||
)?;
|
||||
(position, vec![Piece::Pool(piece)])
|
||||
(position, pieces.into_iter().map(Piece::Pool).collect())
|
||||
}
|
||||
StructureKind::Unsupported(_) => return None,
|
||||
};
|
||||
@@ -1429,6 +1458,41 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclusion_zones_may_skip_the_other_sets_own() {
|
||||
let set = |avoid: Value| {
|
||||
json!({"structures": [{"structure": "t:s", "weight": 1}],
|
||||
"placement": {"type": "minecraft:random_spread", "spacing": 1, "separation": 0,
|
||||
"salt": 1, "horizon:exclusion_zone": avoid}})
|
||||
};
|
||||
let r = registry(
|
||||
&[("t:s", json!({"type": "minecraft:igloo", "biomes": []}))],
|
||||
&[
|
||||
("t:c", set(json!({"other_sets": [], "chunk_count": 0}))),
|
||||
// Every chunk is b's spread chunk, and c keeps b out of all.
|
||||
("t:b", set(json!({"other_sets": ["t:c"], "chunk_count": 1}))),
|
||||
(
|
||||
"t:full",
|
||||
set(json!({"other_sets": ["t:b"], "chunk_count": 1})),
|
||||
),
|
||||
(
|
||||
"t:spread",
|
||||
set(json!({"other_sets": ["t:b"], "chunk_count": 1, "their_zones": false})),
|
||||
),
|
||||
],
|
||||
);
|
||||
let chunk = |name: &str| {
|
||||
let s = r.sets.iter().find(|s| s.name == name).unwrap();
|
||||
r.is_structure_chunk(s, 0, 5, -3, &Rings::new())
|
||||
};
|
||||
assert!(!chunk("t:b"));
|
||||
assert!(
|
||||
chunk("t:full"),
|
||||
"b places nothing once its own zone is checked"
|
||||
);
|
||||
assert!(!chunk("t:spread"), "b's spread alone is in range");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_sections_keep_the_odd_rings() {
|
||||
let rings = RingSections::decode(
|
||||
|
||||
+17
-1
@@ -1,6 +1,6 @@
|
||||
# Horizon extras
|
||||
|
||||
Optional conveniences built into the client: fullbright, zoom, a minimap, an FPS counter, a
|
||||
Optional conveniences built into the client: fullbright, dynamic lights, zoom, a minimap, an FPS counter, a
|
||||
keystroke overlay, auto-reconnect, Mouse Tweaks-style inventory controls and
|
||||
inventory sorting. **Every one is off by default**: a fresh
|
||||
install looks and behaves exactly like vanilla 26.3, and turning an extra off
|
||||
@@ -12,6 +12,7 @@ again restores vanilla's behaviour completely.
|
||||
|---|---|
|
||||
| Settings, parsing and saving | `crates/horizon-client/src/extras.rs` |
|
||||
| Zoom curve, FPS and click counters | `extras.rs` (pure logic, unit tested) |
|
||||
| Dynamic lights: item glow, nearest sources | `crates/horizon-client/src/dynamic_light.rs` (unit tested), `game/dynamic_lights.rs`, `terrain.wgsl` and `entity.wgsl` (`dynamic_block_light`) |
|
||||
| HUD drawing (FPS, keystrokes, minimap frame) | `crates/horizon-client/src/extras_hud.rs` |
|
||||
| Minimap colours, tiles and image | `crates/horizon-client/src/minimap.rs` |
|
||||
| Reconnect policy and backoff | `crates/horizon-client/src/reconnect.rs` |
|
||||
@@ -45,6 +46,21 @@ Horizon category in Controls, and adding one would put a non-vanilla mapping int
|
||||
- Turning it off restores the normal lightmap using the current brightness,
|
||||
time of day and effects. The brightness slider keeps its normal range.
|
||||
|
||||
### Dynamic lights (`dynamicLights`, default off)
|
||||
- A light source held by a player or mob (main or off hand), dropped as an item, or an entity on
|
||||
fire lights the blocks, entities and hand around it, as LambDynamicLights and OptiFine do. Not
|
||||
in vanilla; the idea is ported, not a mod's code (issue #814).
|
||||
- An item glows like its block's default state (`getLightEmission`): torches 14, lanterns,
|
||||
glowstone, sea lanterns and jack o'lanterns 15, soul torches 10, a redstone torch 7; a lava bucket
|
||||
15. An entity on fire gives 15.
|
||||
- Client-only, at render time: the light engine, meshes, saves and other players never see it.
|
||||
Each frame the game picks the 16 sources nearest the camera (within 96 blocks,
|
||||
`dynamic_light::select`); terrain.wgsl and entity.wgsl raise each vertex's block light to the
|
||||
source's level minus its distance in blocks when that is brighter, then light it through the
|
||||
lightmap as usual. The light doesn't stop at walls.
|
||||
- Off: nothing is gathered and the shaders' loop runs zero times (the count is 0), so it costs
|
||||
nothing measurable (numbers in the pull request, #814).
|
||||
|
||||
### Zoom (`zoom`, default off)
|
||||
- Hold the zoom key (default **Z**, unused by every vanilla 26.3 key mapping; C
|
||||
is `key.saveToolbarActivator`) to zoom. The key does nothing while zoom is off.
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ python3 tools/graphics_bench.py --compare baseline-4080 mine-gpu # markdown ta
|
||||
|
||||
vscreen is a headless compositor whose frames are software-rendered (lavapipe), so its frame times measure the CPU, rasterisation included. `--offscreen` (`horizon-client --offscreen`) renders into a texture on the most powerful GPU instead of the window, which measures the RTX 4080 under the same compositor. `--distances`, `--scenes` and `--build` pick a subset or another build. Results go to `benchmarks/graphics/<label>.json`, with the load average before and after: the desktop is shared, and other sessions' builds move the numbers.
|
||||
|
||||
Two tools find where a slow frame goes: `HORIZON_SPIKES=MS` prints the timed spans (ticks by system, streaming, uploads, saving, renderer) of every frame slower than MS milliseconds, and a frame-pointer build (`RUSTFLAGS="-C force-frame-pointers=yes"`) profiles with `perf record --call-graph fp`.
|
||||
Two tools find where a slow frame goes: `HORIZON_SPIKES=MS` prints the timed spans (ticks by system, streaming, uploads, saving, renderer) of every frame slower than MS milliseconds, with the render thread's CPU time in the frame and, after a span that mostly waited (for the GPU, a lock or a core), its CPU time (`submit 30.2/0.1`), and a frame-pointer build (`RUSTFLAGS="-C force-frame-pointers=yes"`) profiles with `perf record --call-graph fp`.
|
||||
|
||||
## Results
|
||||
|
||||
|
||||
+29
-3
@@ -444,6 +444,18 @@ Two cases the oracle fills in:
|
||||
also spreads its structures 1.65 times as far apart as its files say, which carry now
|
||||
applies. MVS went from 829 starts to 90 in a 128×128-chunk square (seed 1234): 294 from the
|
||||
spacing, the rest from the start checks.
|
||||
- **Mo' Structures** (LGPL-3.0; 38 files). Its `mostructures:generic` is vanilla's jigsaw
|
||||
that starts only where the terrain under the 5×5 chunks around it varies by no more than
|
||||
its `heightRange`: carry writes `minecraft:jigsaw` with `horizon:start_checks`
|
||||
(`terrain_radius` 2, `terrain_range`). Its placement `mostructures:type` takes spacing and
|
||||
separation from the mod's config, not its files; carry writes the config's defaults
|
||||
(keyed by `config_key`) and the sets it avoids within 3 chunks as `horizon:exclusion_zone`
|
||||
with `"their_zones": false`: like the mod, the game tests those sets by their spread and
|
||||
frequency alone, not by their own exclusion zones. Its two block-ageing processors
|
||||
(`jungle_rot_processor`, `simple_cobblestone`, 3 uses) are still dropped, as is its
|
||||
mixin that keeps lakes out of its structures. Over chunks -64..63 that adds 13 starts at
|
||||
seed 1234 (pirate ships, churches, a tavern, the castle in the sky...) and 16 at seed 2,
|
||||
and every other start stays as it was.
|
||||
- **Processors written in Java** are taken out of their lists (#822). The game, like
|
||||
vanilla, refuses a list holding a type it does not know, and with it every pool naming the
|
||||
list. The structures now generate undecorated (no pillars under them, spawners as the
|
||||
@@ -482,7 +494,11 @@ Two cases the oracle fills in:
|
||||
plus the name's hash, at the block, piece or structure). In a CTOV plains village at seed
|
||||
1234 the farms now grow carrots, potatoes and beetroot besides wheat, and 1,655
|
||||
cobblestone blocks become paths, grass, mossy cobblestone and planks. No Lithostitched processor is
|
||||
dropped now (130 before), only CTOV's compat hooks for other mods inside them (142 copies).
|
||||
dropped now (130 before). CTOV's compat hooks for other mods inside them (its
|
||||
`modular_compat`, 142 copies) run a list of their own only when the mod they name is
|
||||
loaded: carry writes that list in when the mod is ported along and takes the hook out (a
|
||||
no-op, as in the mod) when it is not. In ATM10 all 142 name Nature's Spirit, which the
|
||||
pack does not have.
|
||||
The processors that build outside their template are carried too: Repurposed's and
|
||||
Moog's pillar processors become the game's `horizon:pillar` (a column from a placeholder
|
||||
block down to the ground, with the processor list they run on each of its blocks written
|
||||
@@ -517,6 +533,11 @@ Two cases the oracle fills in:
|
||||
the world is air, keep it" rules: around the ocean mineshaft at chunk (-18, -54), seed
|
||||
1234, 650 blocks of air and cave air become prismarine and 614 more template water blocks
|
||||
stay water (1,303 blocks change in its 81 chunks).
|
||||
Its mineshafts' sky view processor (71 lists) is `horizon:mineshaft_sky_view`: a block
|
||||
of the template at or above the world's `OCEAN_FLOOR_WG` height in its column is not
|
||||
placed, so a mineshaft cut by a valley or a ravine is not built in the open, except
|
||||
plain rails over a block that can occlude, which stay (waterlogged where the world holds
|
||||
water). Repurposed's dropped processors go from 253 to 182.
|
||||
Still taken out: Formations' biome replacements, blocks aged or propped up.
|
||||
In the 128×128-chunk square (seed 1234), every spawner of a mod structure now has its mob:
|
||||
in the Overworld 83 Better Dungeons spawners held the template's placeholder pig and 17 of
|
||||
@@ -622,12 +643,10 @@ Two cases the oracle fills in:
|
||||
- When Dungeons Arise, Structory and Towns and Towers use vanilla's types already (T&T's
|
||||
namespaces are carried since the namespaces rule above).
|
||||
- Still lost, written in Java:
|
||||
- Formations' pieced structure (1, its one jigsaw-like type);
|
||||
- Repurposed's mineshafts, mansions and monuments, Better Mineshafts and two Better
|
||||
Dungeons types: Java structure types;
|
||||
- the block processors written in Java
|
||||
(YUNG's banners and decorations, Better Strongholds' legs, Lithostitched's block swaps);
|
||||
- MO Structures (38; its library is only on CurseForge).
|
||||
- **Formations** (Overworld and Nether: 50 structures, 128 pool elements) places one
|
||||
template per start at a height found in the noise columns under its corners and centre: on
|
||||
the surface, on water or lava, or in a cave (on its floor, under its ceiling, buried in
|
||||
@@ -638,6 +657,13 @@ Two cases the oracle fills in:
|
||||
39 Overworld and 672 Nether starts at seed 1234 (51 and 643 at seed 2), and leaves every
|
||||
other start as it was. Its processors (biome replacements, aged blocks, bed colours,
|
||||
plants) are still dropped, so its structures keep their templates' blocks.
|
||||
Its one PiecedStructure, the fountain, starts the same way and then lays out the element's
|
||||
jigsaw children with vanilla's jigsaw: carry writes it as `horizon:formations` with
|
||||
`horizon:pieced` (`max_depth`, `max_distance_from_center`), and the game's assembler takes
|
||||
the placed start piece (`jigsaw::add_children`), the children kept within that distance of
|
||||
the start's centre, one block above the height found. It shares Formations' "uncommon"
|
||||
structure set, so where the set now picks it, it takes the place of a statue or a house:
|
||||
1 fountain at seed 1234 and 3 at seed 2 in chunks -64..63, one with a child piece.
|
||||
|
||||
With every structure PR above, the same square (seed 1234, chunks -64..63) holds 362
|
||||
overworld starts with 22,026 pieces. CTOV has 7, Better Dungeons 72 and Better Ocean
|
||||
|
||||
@@ -94,7 +94,8 @@ run at once there, and each must finish within 10 seconds however slowly its byt
|
||||
- **A relay** (only if one is configured) sees the IP addresses of the host and the guests, the short
|
||||
code's first half, when sessions start and end and the size of encrypted frames. It can't see the
|
||||
secret, the key or the game (names, chat, the world). It logs counts every five minutes, nothing else.
|
||||
- **Horizon** sees nothing: there is no Horizon service.
|
||||
- **Horizon** runs no service for it. The game's anonymous "I'm playing" ping says only whether a
|
||||
LAN or friends world is open, never its address, code or name ([telemetry.md](telemetry.md)).
|
||||
|
||||
## Identity
|
||||
|
||||
|
||||
+50
-9
@@ -13,10 +13,10 @@ Both are off by default. With no pack selected the renderer draws exactly what i
|
||||
| Part | State |
|
||||
| --- | --- |
|
||||
| Renderer layout (below) | today's code |
|
||||
| Horizon shader packs: `composite` stage, uniforms, hot reload, Shader Packs screen | first slice planned |
|
||||
| Horizon shader packs: `composite` stage, uniforms, hot reload, Shader Packs page | done (the page: list, pick, open the folder) |
|
||||
| Horizon shader packs: `deferred`, `gbuffer`, `shadow` stages, custom textures | planned |
|
||||
| Java shader packs: preprocessing + GLSL parse coverage | spike done: 450 of 470 programs reach valid WGSL (below) |
|
||||
| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros) | done: every program of the three test packs preprocesses |
|
||||
| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros, JCPP's `#if` and `#define` rules) | done: every program of the three test packs preprocesses; ten packs tested (Compatibility, below) |
|
||||
| Java shader packs: GLSL → WGSL (`horizon_shaderpack::translate`: syntax-tree legaliser, naga) | done: the 464 programs the three test packs enable by default translate (below) |
|
||||
| Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes) | done, no screen yet: read like Iris for the three test packs |
|
||||
| Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips) | done: planned for the three test packs |
|
||||
@@ -56,15 +56,19 @@ The lightmap, fog and sky colours are computed on the CPU (`environment.rs`, `fo
|
||||
### Where packs live and how one is picked
|
||||
|
||||
- Packs go in `shaderpacks/` beside `options.txt` in the game folder (the same folder Iris uses, so one folder
|
||||
holds both kinds). A pack is a folder (zips planned). A pack with a `pack.toml` at its root is a Horizon pack; a pack
|
||||
with a `shaders/` folder is a Java pack.
|
||||
- **Options → Video Settings → Shader Packs...** (Classic screens, laid out like Iris's: the packs on the left with
|
||||
"(off)" first, Apply and Done, *Open Shader Pack Folder*, *Shader Pack Settings...*) and a **Shader Packs** row in
|
||||
the Horizon menus' Video section open the same list.
|
||||
holds both kinds). That is the game home the launcher starts the game in (`%APPDATA%\horizon` on Windows,
|
||||
`~/Library/Application Support/horizon` on macOS, `~/.local/share/horizon` on Linux), not the launcher's version
|
||||
folder. A pack with a `pack.toml` at its root is a Horizon pack; a folder with `shaders/`, or a `.zip`, is a Java
|
||||
pack.
|
||||
- The **Shader Packs** page lists them: a sidebar section in the Horizon menus, **Video Settings → Shader Packs...**
|
||||
in the Classic ones, and the Shader Pack row of the graphics settings leads to it. It shows the folder's full path
|
||||
and an *Open Folder* button (the folder is made if it is missing), then one switch per pack: turning one on picks
|
||||
it, turning it off is the vanilla picture. With no pack, it says so under the path. The list is read again every
|
||||
second while the page is open, so a pack dropped into the folder shows up.
|
||||
- The choice is kept in `horizon-graphics.txt` (`shaderPack:<folder or zip name>`, empty = off). A pack's option
|
||||
values are kept in `shaderpacks/<pack>.txt`, as Iris does.
|
||||
- A pack that fails to load or compile leaves the vanilla picture on and shows why, in red, on its row (and in the
|
||||
log). Nothing a pack does can stop the game from starting.
|
||||
- A pack that fails to load or compile leaves the vanilla picture (or the last pack that worked) on and says why on
|
||||
its row ("Failed", with the error), in chat and in the log. Nothing a pack does can stop the game from starting.
|
||||
- Benchmarks (`--benchmark`) and the parity harnesses never load a pack.
|
||||
|
||||
### Layout
|
||||
@@ -378,6 +382,43 @@ shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far.
|
||||
compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but
|
||||
ignored), custom textures, the option screen; shadow matrices are identity.
|
||||
|
||||
### Compatibility
|
||||
|
||||
Tested on 2026-10-22 on the Mac mini (M4 Pro, Metal) with each pack's default options, the 26.3 builds from Modrinth or
|
||||
the authors' pages (dev-only test inputs, kept outside the repository). "Loads" means every pass the pack enables for
|
||||
the overworld, Nether and End is preprocessed, translated and validated, as the game does when the pack is picked
|
||||
(`java_pack::tests::real_packs_load` with `HORIZON_TEST_SHADERPACKS`); "drawn" means it was also picked in the game
|
||||
and screenshotted. Only full-screen passes run (above), so no pack has its own terrain, water, shadows or sky yet.
|
||||
|
||||
| Pack | Version | Result | First thing that stops it |
|
||||
| --- | --- | --- | --- |
|
||||
| BSL | v10.1.8 | drawn: 26 passes | |
|
||||
| Complementary Reimagined | r5.9.3 | drawn: 27 passes | |
|
||||
| Complementary Unbound | r5.8 | loads: 27 passes | |
|
||||
| Sildur's Vibrant Extreme | 2.02 | drawn: 18 passes, only its sky (above) | |
|
||||
| Steadfast | 0.8.0 | drawn: 3 passes | |
|
||||
| Bliss | 2.1.2 | fails | `world0/deferred.vsh`: an operation naga forbids in a vertex shader |
|
||||
| Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses |
|
||||
| Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) |
|
||||
| Photon | v1.4 | fails | `world0/prepare.vsh`: a struct varying (`CloudsParameters`) |
|
||||
| Rethinking Voxels | r0.1-beta9 | fails | `world0/prepare.fsh`: `1 << 31` overflows naga's constant folding; it also needs images |
|
||||
|
||||
What the translator does for these packs, as Iris (JCPP and its GLSL transformer) does:
|
||||
|
||||
- **`#if` reads floats as JCPP does**: a float in a condition, written there or through a macro, counts as its
|
||||
integer part, and an empty operand as 0. The same holds in `shaders.properties`, where Steadfast's
|
||||
`#elif ATMOSPHERE_FOG_STRENGTH_NOON == 0.5` stopped the pack (`UnexpectedToken(Float(0.5))`).
|
||||
- **A later `#define` replaces an earlier one** instead of failing (Bloop's `DefineRedefined`), and an unterminated
|
||||
`#if` runs to the end of the file.
|
||||
- **`shaders.properties`** keeps its empty lines and backslashes through the preprocessor, as Iris's does, so a
|
||||
continued line doesn't swallow the next one.
|
||||
- **16-bit and 8-bit types** (`float16_t`, `u16vec2`, `packFloat2x16`...), which Noble uses when the GPU reports
|
||||
NVIDIA (`NV_gpu_shader5`), become their 32-bit types: WGSL has none.
|
||||
- **What naga refuses**: `%` with a scalar and a vector operand goes through overloads, a `const` naga can't fold
|
||||
(`mix`, `?:`, `smoothstep`) becomes a global set at the start of `main`, `sqrt` of a negative constant is
|
||||
evaluated at run time, and a fragment output narrower than four channels (`out vec3`, Steadfast's `final`) is
|
||||
written through a `vec4` with alpha 1 as OpenGL fills it.
|
||||
|
||||
### Order to implement
|
||||
|
||||
1. **Translator crate** (`horizon-shaderpack`): the preprocessor (includes, option `#define`s with the player's
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Horizon collects nothing unless the player says yes. The launcher asks once, with four separate switches that are all off until the player turns one on, and the same switches stay in Settings. The game and the launcher obey the same answer. The code is in `crates/horizon-telemetry`.
|
||||
|
||||
The one exception is the anonymous ["I'm playing" ping](#the-im-playing-ping) behind the launcher's "N playing now": it holds nothing about the player, and the launcher says so next to the switches.
|
||||
|
||||
## Consent
|
||||
|
||||
`telemetry/consent.json` in the game folder (`HORIZON_HOME`, else `horizon` in the platform data folder):
|
||||
@@ -46,10 +48,33 @@ Never sent: account names or UUIDs, world names, server or LAN addresses, chat,
|
||||
- `HORIZON_TELEMETRY_URL` sets the server. There is none by default: until there is, nothing is sent and the outbox stays within its caps.
|
||||
- `SCHEMA` versions the format. New optional fields keep it. A field that changes meaning or goes bumps it, and the server keeps reading the older ones.
|
||||
|
||||
## The "I'm playing" ping
|
||||
|
||||
Ludovic decided on 2026-10-22 to count every player, with or without consent, and to tell them. The launcher's first-run question and Settings → Data collection show it as an "Always on" row next to the switches. Players who answered the question before the ping existed see the same text once on the Play page. The privacy page on playhorizon.dev says the same.
|
||||
|
||||
While the game runs (not a dedicated server, a benchmark or a run that quits by itself), a thread of its own (`crates/horizon-client/src/heartbeat.rs`) sends `POST /v1/live` once a minute. It also sends one at once when a world is opened to or closed from LAN or friends:
|
||||
|
||||
```json
|
||||
{ "session": "9b1c…", "version": "v2026.10.22", "platform": "macos", "lan": false }
|
||||
```
|
||||
|
||||
- `session` is 128 random bits made when the game starts. It is kept only in the game's memory and is not the install ID, so two sessions of one player can't be linked.
|
||||
- `version` is the release, `platform` is `linux`, `macos`, `windows` or `other`, and `lan` says whether a LAN or play-with-friends world is open.
|
||||
- Nothing else: no account, install ID, world, server, settings or hardware. The server checks each field (`live::Ping::check`) and refuses anything more.
|
||||
|
||||
The server keeps sessions in memory only, never on disk, and never with the sender's address. A session counts while its last ping is under 2 minutes old. `GET /v1/live` gives the count, rounded (`live::round`: exact under 10, then to 5, 10 and 100):
|
||||
|
||||
```json
|
||||
{ "playing": 1240, "lan": 85, "versions": { "v2026.10.22": 1100, "other": 140 }, "platforms": { "linux": 300, "macos": 240, "windows": 700 } }
|
||||
```
|
||||
|
||||
The launcher reads it when it opens and every minute after, and shows "N playing now" on the Play page. It shows nothing when the server can't be reached. Like the rest, there is no server by default (`HORIZON_TELEMETRY_URL`): until there is one, the game sends no ping and the launcher shows no count. `HORIZON_NO_HEARTBEAT=1` keeps automated runs out of the count.
|
||||
|
||||
## Server
|
||||
|
||||
- `POST /v1/batch`
|
||||
- `DELETE /v1/installs/<install_id>`: deletes everything sent under that ID.
|
||||
- `GET /v1/aggregate`: the anonymous totals the website's results page reads.
|
||||
- `POST /v1/live` and `GET /v1/live`: the "I'm playing" ping and the live count.
|
||||
|
||||
`crates/horizon-telemetry-server` is the server. Its [README](../crates/horizon-telemetry-server/README.md) covers storage (about 190 bytes per play session), retention (180 days of raw rows, anonymous daily totals kept), rate limits and hosting.
|
||||
|
||||
@@ -592,6 +592,32 @@ pub fn is_prepared(tag: &str) -> bool {
|
||||
resources(tag).join(RESOURCES_MANIFEST).exists()
|
||||
}
|
||||
|
||||
/// Whether a version's resources hold Minecraft's sounds, which `sounds` copies from the player's own
|
||||
/// install beside the preparation. A version prepared while that copy failed (Mojang's republished 26.3
|
||||
/// asset index, #1076), or one that reused such a version's resources, plays no sound at all (#1035).
|
||||
pub fn has_sounds(tag: &str) -> bool {
|
||||
sounds_in(&resources(tag))
|
||||
}
|
||||
|
||||
fn sounds_in(resources: &Path) -> bool {
|
||||
// What the game's sound registry reads (horizon-client sound_events.rs).
|
||||
resources.join("assets/minecraft/sounds.json").is_file()
|
||||
}
|
||||
|
||||
/// What the Play page says of a version's resources.
|
||||
pub fn resources_summary(prepared: bool, sounds: bool, version: &str) -> String {
|
||||
match (prepared, sounds) {
|
||||
(false, _) => {
|
||||
format!("Not prepared. Horizon needs the files of your own Minecraft {version}.")
|
||||
}
|
||||
(true, true) => format!("Prepared for Minecraft {version}"),
|
||||
(true, false) => format!(
|
||||
"Prepared for Minecraft {version}, without its sounds: the game will be silent. \
|
||||
Prepare again to copy them from your Minecraft install."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the resources `from` prepared are the ones preparing `to` would make. The output
|
||||
/// depends on the Horizon version, not only on Minecraft's: the manifest records the hashes of
|
||||
/// the vanilla exporters it was made with (mods/horizon/src/test/java/.../parity), and the
|
||||
@@ -2040,6 +2066,8 @@ pub enum Msg {
|
||||
PackLine(String),
|
||||
/// A modpack step ended: the pack as it now is.
|
||||
PackDone(Result<Box<crate::modpacks::Imported>, String>),
|
||||
/// How many play Horizon now, or none when the server can't be reached (`telemetry`).
|
||||
Playing(Option<u64>),
|
||||
}
|
||||
|
||||
/// A running process; its output arrives as `Msg::Line`, its end as `Msg::Exit`.
|
||||
@@ -2130,6 +2158,10 @@ pub struct Settings {
|
||||
/// Whether new versions include betas (releases not promoted to stable yet). Off by default.
|
||||
#[serde(default)]
|
||||
pub beta_builds: bool,
|
||||
/// The player has read what the "I'm playing" ping holds (`telemetry::PING`): on the
|
||||
/// first-run question, or on the Play page once if they answered that before it existed.
|
||||
#[serde(default)]
|
||||
pub ping_notice_seen: bool,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
@@ -2165,6 +2197,30 @@ mod tests {
|
||||
use super::*;
|
||||
use std::cmp::Ordering::*;
|
||||
|
||||
#[test]
|
||||
fn resources_without_sounds_are_reported() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-no-sounds-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(dir.join("assets/minecraft/textures")).unwrap();
|
||||
fs::write(dir.join(RESOURCES_MANIFEST), "{}").unwrap();
|
||||
assert!(!sounds_in(&dir));
|
||||
fs::write(dir.join("assets/minecraft/sounds.json"), "{}").unwrap();
|
||||
assert!(sounds_in(&dir));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
resources_summary(true, true, "26.3"),
|
||||
"Prepared for Minecraft 26.3"
|
||||
);
|
||||
let silent = resources_summary(true, false, "26.3");
|
||||
assert!(silent.contains("without its sounds") && silent.contains("Prepare again"));
|
||||
// Not prepared says only that, sounds or not.
|
||||
assert_eq!(
|
||||
resources_summary(false, false, "26.3"),
|
||||
resources_summary(false, true, "26.3")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_game_plays_under_its_own_audio_stream_name() {
|
||||
if std::env::var_os("PIPEWIRE_PROPS").is_some() {
|
||||
|
||||
+4
-2
@@ -422,10 +422,12 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
} else {
|
||||
" "
|
||||
};
|
||||
let state = if backend::is_prepared(tag) {
|
||||
let state = if !backend::is_prepared(tag) {
|
||||
"not prepared"
|
||||
} else if backend::has_sounds(tag) {
|
||||
"prepared"
|
||||
} else {
|
||||
"not prepared"
|
||||
"prepared, no sounds (prepare again)"
|
||||
};
|
||||
println!("{mark} {tag} {state}");
|
||||
}
|
||||
|
||||
@@ -45,6 +45,41 @@ fn kind_id(prefix: &str, kind: DataKind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a switch would be: the ping has none.
|
||||
fn always_on(t: &Theme) -> Div {
|
||||
caps("Always on").flex_none().text_color(t.muted)
|
||||
}
|
||||
|
||||
/// The "I'm playing" ping on the first-run question, laid out as the switches' rows.
|
||||
fn ping_row(t: &Theme) -> Div {
|
||||
div()
|
||||
.flex()
|
||||
.items_start()
|
||||
.gap(px(16.))
|
||||
.py(px(10.))
|
||||
.border_b_1()
|
||||
.border_color(t.rule)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.gap(px(2.))
|
||||
.child(
|
||||
text(theme::UI)
|
||||
.text_color(t.ink)
|
||||
.child(telemetry::PING_NAME),
|
||||
)
|
||||
.child(
|
||||
text(theme::CAPTION)
|
||||
.text_color(t.muted)
|
||||
.child(telemetry::PING),
|
||||
),
|
||||
)
|
||||
.child(always_on(t))
|
||||
}
|
||||
|
||||
/// The exact JSON, in mono, scrolling inside a plate.
|
||||
fn json_view(view: &(String, String), t: &Theme, scroll: &Scrollbar) -> Div {
|
||||
div()
|
||||
@@ -87,6 +122,11 @@ impl Launcher {
|
||||
Ok(consent) => self.collection.consent = consent,
|
||||
Err(e) => self.collection.note = Some(format!("Could not save your choice: {e}")),
|
||||
}
|
||||
// The question and Settings say what the "I'm playing" ping holds, beside the switches.
|
||||
if !self.settings.ping_notice_seen {
|
||||
self.settings.ping_notice_seen = true;
|
||||
self.settings.save();
|
||||
}
|
||||
self.collection.view = None;
|
||||
}
|
||||
|
||||
@@ -148,9 +188,17 @@ impl Launcher {
|
||||
.child("Help make Horizon faster and steadier?"),
|
||||
)
|
||||
.child(text(theme::UI).text_color(t.muted).child(
|
||||
"Horizon can send a few things to its developers. Everything is off until you turn it on, and Settings can change it any time.",
|
||||
"Horizon can send a few things to its developers. Each switch is off until you turn it on, and Settings can change it any time.",
|
||||
))
|
||||
.child(div().flex().flex_col().border_t_1().border_color(t.rule).children(rows))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.border_t_1()
|
||||
.border_color(t.rule)
|
||||
.children(rows)
|
||||
.child(ping_row(&t)),
|
||||
)
|
||||
.child(text(theme::CAPTION).text_color(t.muted).child(telemetry::NEVER))
|
||||
.child(
|
||||
div()
|
||||
@@ -244,6 +292,13 @@ impl Launcher {
|
||||
&t,
|
||||
));
|
||||
}
|
||||
list = list.child(index_row(
|
||||
telemetry::SWITCHES.len() + 1,
|
||||
telemetry::PING_NAME,
|
||||
Some(div().child(telemetry::PING).into_any_element()),
|
||||
Some(always_on(&t).into_any_element()),
|
||||
&t,
|
||||
));
|
||||
let waiting = horizon_telemetry::outbox::pending(&telemetry::home()).len();
|
||||
let id = match consent.install_id.as_str() {
|
||||
"" => "No install ID: nothing has been collected".to_string(),
|
||||
@@ -299,7 +354,7 @@ impl Launcher {
|
||||
})),
|
||||
);
|
||||
list = list.child(index_row(
|
||||
telemetry::SWITCHES.len() + 1,
|
||||
telemetry::SWITCHES.len() + 2,
|
||||
"Your data",
|
||||
Some(
|
||||
div()
|
||||
@@ -316,7 +371,7 @@ impl Launcher {
|
||||
.gap(px(16.))
|
||||
.child(text(theme::HEADING).text_color(t.ink).child("Data collection"))
|
||||
.child(text(theme::UI).max_w(px(600.)).text_color(t.muted).child(
|
||||
"Off unless you turn it on. What each switch sends is below it; the privacy page on playhorizon.dev says how long it is kept.",
|
||||
"Each switch is off unless you turn it on. What it sends is below it; the privacy page on playhorizon.dev says how long it is kept.",
|
||||
))
|
||||
.child(list)
|
||||
.child(text(theme::CAPTION).text_color(t.muted).child(telemetry::NEVER))
|
||||
|
||||
+87
-5
@@ -163,6 +163,8 @@ struct Launcher {
|
||||
args_focus: FocusHandle,
|
||||
/// Opt-in data collection: the player's answer and Settings' section (`collection`).
|
||||
collection: collection::Collection,
|
||||
/// How many play Horizon now, while the server answers ("N playing now" on the Play page).
|
||||
playing: Option<u64>,
|
||||
tx: Sender<Msg>,
|
||||
rx: Receiver<Msg>,
|
||||
_appearance: Subscription,
|
||||
@@ -280,6 +282,7 @@ impl Launcher {
|
||||
friend_focus: cx.focus_handle(),
|
||||
joining: None,
|
||||
collection: collection::Collection::load(),
|
||||
playing: None,
|
||||
tx,
|
||||
rx,
|
||||
_appearance: appearance,
|
||||
@@ -317,6 +320,7 @@ impl Launcher {
|
||||
this.fetch_links();
|
||||
// What the game and the launcher kept, if the player allows it and there is a server.
|
||||
telemetry::send_in_background();
|
||||
telemetry::watch_playing(this.tx.clone());
|
||||
this
|
||||
}
|
||||
|
||||
@@ -426,6 +430,7 @@ impl Launcher {
|
||||
// The page reads is_prepared when drawn; `changed` redraws it.
|
||||
Msg::Reused(_) => self.installed = backend::installed(),
|
||||
Msg::Keychain(persistent) => self.keychain = persistent,
|
||||
Msg::Playing(playing) => self.playing = playing,
|
||||
Msg::Session(session) => {
|
||||
if let Some(tag) = self.starting_client.take() {
|
||||
let mut cmd = backend::client_command(&tag);
|
||||
@@ -1146,6 +1151,19 @@ fn centered(text_: &str, t: &Theme) -> Div {
|
||||
.child(text(theme::UI).text_color(t.muted).child(text_.to_string()))
|
||||
}
|
||||
|
||||
/// `1234` as `1,234`.
|
||||
fn thousands(n: u64) -> String {
|
||||
let digits = n.to_string();
|
||||
let mut out = String::new();
|
||||
for (i, c) in digits.chars().enumerate() {
|
||||
if i > 0 && (digits.len() - i).is_multiple_of(3) {
|
||||
out.push(',');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A mono line in upper case: the status above a title, the footer's links.
|
||||
fn caps(s: impl AsRef<str>) -> Div {
|
||||
text(theme::MICRO).child(s.as_ref().to_uppercase())
|
||||
@@ -1388,6 +1406,8 @@ impl Launcher {
|
||||
));
|
||||
};
|
||||
let prepared = backend::is_prepared(&tag);
|
||||
// Prepared without sounds (#1035): Prepare again is the fix, so it stands out.
|
||||
let silent = prepared && !backend::has_sounds(&tag);
|
||||
let version = backend::game_version(&tag);
|
||||
let hero = self.hero(&tag, &version, prepared, cx);
|
||||
let running = self.client.is_some() || self.starting_client.is_some();
|
||||
@@ -1429,15 +1449,13 @@ impl Launcher {
|
||||
|
||||
let resources_value = if self.preparing {
|
||||
"Preparing…".to_string()
|
||||
} else if prepared {
|
||||
format!("Prepared for Minecraft {version}")
|
||||
} else {
|
||||
format!("Not prepared. Horizon needs the files of your own Minecraft {version}.")
|
||||
backend::resources_summary(prepared, !silent, &version)
|
||||
};
|
||||
let mut prepare = button(
|
||||
"prepare",
|
||||
if prepared { "Prepare again" } else { "Prepare" },
|
||||
if prepared {
|
||||
if prepared && !silent {
|
||||
Kind::Ghost
|
||||
} else {
|
||||
Kind::Secondary
|
||||
@@ -1688,9 +1706,11 @@ impl Launcher {
|
||||
_ => None,
|
||||
};
|
||||
let title = "Horizon";
|
||||
// Never squeezed by the rows below: the ping notice can make it tall.
|
||||
let mut hero =
|
||||
div()
|
||||
.flex()
|
||||
.flex_none()
|
||||
.flex_col()
|
||||
.gap(px(14.))
|
||||
.pt(px(24.))
|
||||
@@ -1704,7 +1724,18 @@ impl Launcher {
|
||||
.child(
|
||||
caps(if prepared { "Ready" } else { "Needs preparing" })
|
||||
.text_color(if prepared { t.success } else { t.muted }),
|
||||
),
|
||||
)
|
||||
.children(self.playing.map(|n| {
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(10.))
|
||||
.child(div().size(px(4.)).rounded_full().bg(t.rule))
|
||||
.child(
|
||||
caps(format!("{} playing now", thousands(n)))
|
||||
.text_color(t.muted),
|
||||
)
|
||||
})),
|
||||
)
|
||||
.child(text(theme::DISPLAY).text_color(t.ink).child(title))
|
||||
.child(text(theme::BODY).max_w(px(560.)).text_color(t.muted).child(
|
||||
@@ -1747,6 +1778,45 @@ impl Launcher {
|
||||
),
|
||||
});
|
||||
}
|
||||
// Players who answered the first-run question before the ping existed read about it
|
||||
// once here.
|
||||
if !self.settings.ping_notice_seen && !self.collection.consent.needs_asking() {
|
||||
hero = hero.child(
|
||||
plate(&t)
|
||||
.flex()
|
||||
.flex_none()
|
||||
.flex_col()
|
||||
.gap(px(8.))
|
||||
.p(px(16.))
|
||||
.w_full()
|
||||
.max_w(px(640.))
|
||||
.child(
|
||||
text(theme::UI)
|
||||
.text_color(t.ink)
|
||||
.child(telemetry::PING_NAME),
|
||||
)
|
||||
.child(
|
||||
text(theme::CAPTION)
|
||||
.text_color(t.muted)
|
||||
.child(telemetry::PING),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("ping-notice-ok")
|
||||
.text_size(px(theme::UI.px))
|
||||
.text_color(t.accent)
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.cursor_pointer()
|
||||
.hover(|s| s.opacity(0.8))
|
||||
.child("Got it")
|
||||
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.settings.ping_notice_seen = true;
|
||||
this.settings.save();
|
||||
cx.notify();
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
hero
|
||||
}
|
||||
|
||||
@@ -2918,3 +2988,15 @@ fn main() {
|
||||
cx.activate(true);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn counts_get_thousands_separators() {
|
||||
let shown: Vec<String> = [0, 7, 999, 1000, 12_300, 1_234_500]
|
||||
.into_iter()
|
||||
.map(super::thousands)
|
||||
.collect();
|
||||
assert_eq!(shown, ["0", "7", "999", "1,000", "12,300", "1,234,500"]);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ impl Session {
|
||||
"list_versions" => {
|
||||
let installed = backend::installed();
|
||||
let mut out = json!({
|
||||
"installed": installed.iter().map(|t| json!({ "tag": t, "prepared": backend::is_prepared(t) })).collect::<Vec<_>>(),
|
||||
"installed": installed.iter().map(|t| json!({ "tag": t, "prepared": backend::is_prepared(t), "sounds": backend::has_sounds(t) })).collect::<Vec<_>>(),
|
||||
"selected": backend::resolve_version(None).ok(),
|
||||
});
|
||||
if !args
|
||||
|
||||
@@ -307,7 +307,7 @@ pub fn benchmark(repeats: usize) -> Result<PathBuf, String> {
|
||||
if let Ok(data) = serde_json::to_value(report.for_upload()) {
|
||||
let item = horizon_telemetry::Item::new(
|
||||
horizon_telemetry::Source::Launcher,
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
crate::backend::VERSION,
|
||||
horizon_telemetry::Payload::Benchmark(data),
|
||||
);
|
||||
let _ = horizon_telemetry::outbox::push(&crate::backend::game_home(), &item);
|
||||
@@ -320,7 +320,7 @@ pub fn benchmark(repeats: usize) -> Result<PathBuf, String> {
|
||||
fn app() -> App {
|
||||
App {
|
||||
name: "horizon-launcher".into(),
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
version: crate::backend::VERSION.into(),
|
||||
..App::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Opt-in data collection from the launcher (`horizon_telemetry`): the player's answer, what
|
||||
//! would be sent, deleting it, bug reports and benchmark uploads, and sending the outbox when
|
||||
//! the launcher starts and closes. The window, the CLI and the MCP server all go through here.
|
||||
//! Also the live count's side here: what the "I'm playing" ping holds, in words, and reading
|
||||
//! how many play now (`horizon_telemetry::live`).
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use horizon_telemetry::payload::{Bug, Crash, Perf, System, Timings};
|
||||
@@ -37,6 +39,33 @@ pub const SWITCHES: [(Kind, &str, &str); 4] = [
|
||||
/// Never sent, whatever the switches say.
|
||||
pub const NEVER: &str = "Never sent: your account name or UUID, world names, server addresses, chat, or your IP address. Each report is dated to the day, under a random install ID you can delete.";
|
||||
|
||||
/// The anonymous "I'm playing" ping the game sends whatever the switches say (Ludovic's
|
||||
/// decision, 2026-10-22: count everyone, and tell them). Shown on the first-run question, in
|
||||
/// Settings, and once on the Play page to players who answered before it existed.
|
||||
pub const PING_NAME: &str = "\"I'm playing\" ping";
|
||||
pub const PING: &str = "While you play, the game sends an anonymous \"I'm playing\" ping once a minute, so the launcher can show how many people play Horizon right now. It holds: a random number made when the game starts and forgotten when it closes, the Horizon version, your OS (Linux, macOS or Windows), and whether you have a world open to LAN or friends. It doesn't hold: your account, your install ID, world or server names, or anything you do in the game, and the server doesn't keep your IP address. It is sent whatever the switches say.";
|
||||
|
||||
/// How many play Horizon now (rounded), if the server says.
|
||||
pub fn playing_now() -> Option<u64> {
|
||||
let endpoint = horizon_telemetry::endpoint()?;
|
||||
horizon_telemetry::live::fetch(&endpoint)
|
||||
.ok()
|
||||
.map(|count| count.playing)
|
||||
}
|
||||
|
||||
/// Sends [`playing_now`] to the window as `Msg::Playing` now and every minute, on its own
|
||||
/// thread. Nothing at all when there is no server.
|
||||
pub fn watch_playing(tx: std::sync::mpsc::Sender<backend::Msg>) {
|
||||
if horizon_telemetry::endpoint().is_none() {
|
||||
return;
|
||||
}
|
||||
std::thread::spawn(move || {
|
||||
while tx.send(backend::Msg::Playing(playing_now())).is_ok() {
|
||||
std::thread::sleep(horizon_telemetry::live::INTERVAL);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn home() -> PathBuf {
|
||||
backend::game_home()
|
||||
}
|
||||
@@ -249,6 +278,7 @@ pub fn status_json() -> serde_json::Value {
|
||||
"install_id": consent.install_id,
|
||||
"waiting": outbox::pending(&home()).len(),
|
||||
"server": horizon_telemetry::endpoint(),
|
||||
"ping": PING,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -77,6 +77,7 @@ import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundDisguisedChatPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundLoginPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSystemChatPacket;
|
||||
@@ -124,6 +125,8 @@ import net.minecraft.world.entity.player.ProfilePublicKey;
|
||||
*/
|
||||
public final class SecureChatClient {
|
||||
private static final List<String> LINES = new ArrayList<>();
|
||||
/** A command any player may run, whose reply only its sender gets (RandomCommand: value). */
|
||||
private static final String BARRIER = "random value 1..2";
|
||||
private static PrivateKey services;
|
||||
private static String sessionUrl;
|
||||
|
||||
@@ -203,7 +206,7 @@ public final class SecureChatClient {
|
||||
settle(all, "alice's chain is broken");
|
||||
bob.send(new ServerboundChatAckPacket(50));
|
||||
settle(all, "bob acknowledges too much");
|
||||
for (Client c : all) c.close();
|
||||
leave(all);
|
||||
}
|
||||
|
||||
/** Online mode with enforce-secure-profile: unsigned chat is refused. */
|
||||
@@ -223,13 +226,35 @@ public final class SecureChatClient {
|
||||
// A key the services signed for another player.
|
||||
Client mallory = Client.join(host, port, "Mallory", true, UUID.nameUUIDFromBytes("someone else".getBytes()));
|
||||
settle(List.of(alice, carol, mallory), "mallory's borrowed key");
|
||||
for (Client c : all) c.close();
|
||||
leave(all);
|
||||
mallory.close();
|
||||
}
|
||||
|
||||
/** Lets the server answer, then records what each player received, in player order. */
|
||||
/**
|
||||
* The players still connected leave one at a time, each once the next was
|
||||
* told the one before left (PlayerList.remove broadcasts the removal after
|
||||
* the "lost connection" line): the server logs the departures in this
|
||||
* order, not in the order its network threads notice the closed sockets.
|
||||
*/
|
||||
private static void leave(List<Client> all) throws Exception {
|
||||
List<Client> clients = all.stream().filter(c -> !c.closed).toList();
|
||||
for (int i = 0; i < clients.size(); i++) {
|
||||
clients.get(i).close();
|
||||
if (i + 1 < clients.size()) clients.get(i + 1).awaitRemoved(clients.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets the server answer, then records what each player received, in player order. However slow the
|
||||
* server, a step ends once it handled everything sent so far: each player still connected runs a command
|
||||
* whose reply comes after it, twice (a chat's broadcast is a task the chat's own task queues), and has then
|
||||
* read whatever the server sent it before.
|
||||
*/
|
||||
private static void settle(List<Client> clients, String step) throws Exception {
|
||||
Thread.sleep(1500);
|
||||
for (int round = 0; round < 2; round++) {
|
||||
for (Client c : clients) c.barrier();
|
||||
}
|
||||
LINES.add("step " + step);
|
||||
for (Client c : clients) c.drain();
|
||||
}
|
||||
@@ -249,6 +274,10 @@ public final class SecureChatClient {
|
||||
ProtocolInfo<?> inbound;
|
||||
ProtocolInfo<?> outbound;
|
||||
final BlockingQueue<Packet<?>> queue = new LinkedBlockingQueue<>();
|
||||
/** Replies to BARRIER, kept out of the queue. */
|
||||
final java.util.concurrent.Semaphore barriers = new java.util.concurrent.Semaphore(0);
|
||||
/** The server ended the connection (its reader stopped). */
|
||||
volatile boolean ended;
|
||||
volatile boolean closed;
|
||||
LocalChatSession session;
|
||||
SignedMessageChain.Encoder encoder = SignedMessageChain.Encoder.UNSIGNED;
|
||||
@@ -359,13 +388,21 @@ public final class SecureChatClient {
|
||||
try {
|
||||
while (!closed) {
|
||||
Packet<?> p = read();
|
||||
if (p instanceof ClientboundSystemChatPacket s
|
||||
&& s.content().getContents() instanceof net.minecraft.network.chat.contents.TranslatableContents t
|
||||
&& t.getKey().equals("commands.random.sample.success")) {
|
||||
barriers.release();
|
||||
continue;
|
||||
}
|
||||
queue.put(p);
|
||||
// Nothing follows a disconnect but the closed socket.
|
||||
if (p instanceof ClientboundDisconnectPacket) return;
|
||||
if (p instanceof ClientboundDisconnectPacket) break;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (!closed) queue.add(new ClientboundDisconnectPacket(Component.literal("connection lost: " + e)));
|
||||
}
|
||||
ended = true;
|
||||
barriers.release();
|
||||
}, name + " reader");
|
||||
reader.setDaemon(true);
|
||||
reader.start();
|
||||
@@ -437,6 +474,21 @@ public final class SecureChatClient {
|
||||
send(new ServerboundChatCommandPacket(command));
|
||||
}
|
||||
|
||||
/** Runs BARRIER and waits for its reply (30 s at most), which isn't recorded. */
|
||||
void barrier() throws Exception {
|
||||
if (closed || ended) return;
|
||||
barriers.drainPermits();
|
||||
try {
|
||||
send(new ServerboundChatCommandPacket(BARRIER));
|
||||
} catch (java.io.IOException e) {
|
||||
if (ended) return;
|
||||
throw e;
|
||||
}
|
||||
if (!barriers.tryAcquire(30, TimeUnit.SECONDS) && !ended) {
|
||||
LINES.add("error " + name + " got no reply to /" + BARRIER);
|
||||
}
|
||||
}
|
||||
|
||||
/** Handles and records what arrived. */
|
||||
void drain() throws Exception {
|
||||
Packet<?> p;
|
||||
@@ -489,6 +541,18 @@ public final class SecureChatClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits (10 s at most) until the server removes `gone` from this player's list; records nothing else. */
|
||||
void awaitRemoved(Client gone) throws Exception {
|
||||
long until = System.nanoTime() + 10_000_000_000L;
|
||||
while (System.nanoTime() < until) {
|
||||
Packet<?> p = queue.poll(50, TimeUnit.MILLISECONDS);
|
||||
if (p instanceof ClientboundPlayerInfoRemovePacket r && r.profileIds().contains(gone.id)) return;
|
||||
if (p instanceof ClientboundKeepAlivePacket k) send(new ServerboundKeepAlivePacket(k.getId()));
|
||||
else if (p instanceof ClientboundPingPacket ping) send(new ServerboundPongPacket(ping.getId()));
|
||||
}
|
||||
LINES.add("error " + name + " was never told that " + gone.name + " left");
|
||||
}
|
||||
|
||||
/** ClientPacketListener.handlePlayerChat, then markMessageAsProcessed. */
|
||||
void playerChat(ClientboundPlayerChatPacket p) {
|
||||
int expected = nextChatIndex++;
|
||||
|
||||
@@ -411,6 +411,12 @@ public final class VanillaProtocolClient {
|
||||
/** The entity mode's step, and how long it records the entities for (ms). */
|
||||
private static final int ENTITIES = 1000;
|
||||
private static final long ENTITY_WAIT = 20_000;
|
||||
/**
|
||||
* How long a step waits at most for what it waits on (a villager to trade with, the ingot, a thrown
|
||||
* snowball, the pearl's teleport and hurt): a busy machine can hold a server's ticks back for seconds,
|
||||
* so the steps wait for those, not for a fixed time.
|
||||
*/
|
||||
private static final long PATIENCE = 30_000;
|
||||
|
||||
static int moveEntityId(net.minecraft.network.protocol.game.ClientboundMoveEntityPacket p) {
|
||||
return (int) field(p, net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.class, "entityId");
|
||||
@@ -464,6 +470,9 @@ public final class VanillaProtocolClient {
|
||||
int furnaceState = 0;
|
||||
// Snowballs the server spawned since the last right click.
|
||||
int snowballs = 0;
|
||||
// When the first of them came, and when the furnace's ingot did.
|
||||
long snowballAt = 0;
|
||||
long smeltedAt = 0;
|
||||
// The player's own id, and what the ender pearl it throws does to it.
|
||||
int playerId = -1;
|
||||
boolean pearl = false;
|
||||
@@ -550,6 +559,7 @@ public final class VanillaProtocolClient {
|
||||
&& furnaceWindow > 0 && p.getContainerId() == furnaceWindow) {
|
||||
furnaceState = p.getStateId();
|
||||
record("play-furnace", "slot " + p.getSlot() + " " + p.getItem());
|
||||
if (p.getSlot() == 2 && !p.getItem().isEmpty() && smeltedAt == 0) smeltedAt = now;
|
||||
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundContainerSetDataPacket p
|
||||
&& furnaceWindow > 0 && p.getContainerId() == furnaceWindow && (p.getId() == 1 || p.getId() == 3)) {
|
||||
// Lit total and cooking total; the time left and the cooking timer follow the ticks.
|
||||
@@ -580,6 +590,7 @@ public final class VanillaProtocolClient {
|
||||
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p
|
||||
&& p.getType() == net.minecraft.world.entity.EntityTypes.SNOWBALL) {
|
||||
snowballs++;
|
||||
if (snowballAt == 0) snowballAt = now;
|
||||
// Projectile.getAddEntityPacket: its owner's id.
|
||||
record("play-use", "snowball owner is the player: " + (p.getData() == playerId));
|
||||
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p
|
||||
@@ -666,8 +677,8 @@ public final class VanillaProtocolClient {
|
||||
send(new ServerboundChatCommandPacket(REPLIES[step - 2]));
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step == 2 + REPLIES.length && now - stepAt > 1500) {
|
||||
// Right-click the villager: the trading screen and its offers.
|
||||
} else if (step == 2 + REPLIES.length && now - stepAt > 1500 && (villager >= 0 || now - stepAt > PATIENCE)) {
|
||||
// Right-click the villager (once the server sent it): the trading screen and its offers.
|
||||
record("play-trade", "villager " + (villager >= 0));
|
||||
if (villager >= 0) {
|
||||
send(new net.minecraft.network.protocol.game.ServerboundInteractPacket(villager,
|
||||
@@ -715,8 +726,9 @@ public final class VanillaProtocolClient {
|
||||
net.minecraft.core.Direction.NORTH, furnace, false), 1));
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step >= 8 + REPLIES.length && step <= 10 + REPLIES.length && furnaceWindow > 0
|
||||
&& now - stepAt > (step == 10 + REPLIES.length ? 12_000 : 1500)) {
|
||||
} else if (step >= 8 + REPLIES.length && step <= 10 + REPLIES.length && furnaceWindow > 0 && now - stepAt > 1500
|
||||
// The ingot out once the furnace made it (200 ticks), and its tick's other changes came.
|
||||
&& (step < 10 + REPLIES.length || smeltedAt > 0 && now - smeltedAt > 1000 || now - stepAt > 10_000 + PATIENCE)) {
|
||||
// Shift-click the ore (hotbar 0) into the input, the coal (hotbar 1) into the
|
||||
// fuel slot, and the smelted ingot out of the result; nothing claimed, so the
|
||||
// server sends every slot the click changed.
|
||||
@@ -743,9 +755,10 @@ public final class VanillaProtocolClient {
|
||||
useOn(respawnAt, net.minecraft.world.InteractionHand.MAIN_HAND, 2);
|
||||
use(position, net.minecraft.world.InteractionHand.MAIN_HAND, 3);
|
||||
snowballs = 0;
|
||||
snowballAt = 0;
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step == 14 + REPLIES.length && now - stepAt > 2000) {
|
||||
} else if (step == 14 + REPLIES.length && thrown(snowballAt, stepAt, now)) {
|
||||
record("play-use", "main hand on a block: " + snowballs + " snowball(s)");
|
||||
send(new ServerboundChatCommandPacket("item replace entity @s weapon.mainhand with minecraft:air"));
|
||||
send(new ServerboundChatCommandPacket("item replace entity @s weapon.offhand with minecraft:snowball 16"));
|
||||
@@ -757,9 +770,10 @@ public final class VanillaProtocolClient {
|
||||
useOn(respawnAt, net.minecraft.world.InteractionHand.OFF_HAND, 5);
|
||||
use(position, net.minecraft.world.InteractionHand.OFF_HAND, 6);
|
||||
snowballs = 0;
|
||||
snowballAt = 0;
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step == 16 + REPLIES.length && now - stepAt > 2000) {
|
||||
} else if (step == 16 + REPLIES.length && thrown(snowballAt, stepAt, now)) {
|
||||
record("play-use", "off hand on a block: " + snowballs + " snowball(s)");
|
||||
// An ender pearl thrown at its feet (no endermite: ThrownEnderpearl spawns one 5% of the time).
|
||||
send(new ServerboundChatCommandPacket("gamerule spawn_monsters false"));
|
||||
@@ -773,7 +787,8 @@ public final class VanillaProtocolClient {
|
||||
position.yRot(), 90.0F));
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step == 18 + REPLIES.length && now - stepAt > 2500) {
|
||||
} else if (step == 18 + REPLIES.length && now - stepAt > 2500
|
||||
&& (pearlTeleports > 0 && pearlHealth >= 0 || now - stepAt > PATIENCE)) {
|
||||
// ThrownEnderpearl.onHit: the thrower is teleported and takes 5 damage.
|
||||
record("play-pearl", "teleported " + pearlTeleports + " time(s), health " + pearlHealth);
|
||||
return;
|
||||
@@ -786,6 +801,14 @@ public final class VanillaProtocolClient {
|
||||
record("error", "timed out in play, step " + step + ", chunks " + chunks.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* A right click's snowballs are counted: once the first came and a second could have come with it
|
||||
* (the server spawns each in the tick it handles the click), or once the server had all the time.
|
||||
*/
|
||||
private static boolean thrown(long first, long clicked, long now) {
|
||||
return now - clicked > 2000 && (first > 0 && now - first > 1000 || now - clicked > PATIENCE);
|
||||
}
|
||||
|
||||
/** The death screen's Respawn button: true, the respawn being under way. */
|
||||
private boolean respawn() throws Exception {
|
||||
send(new net.minecraft.network.protocol.game.ServerboundClientCommandPacket(
|
||||
@@ -821,10 +844,12 @@ public final class VanillaProtocolClient {
|
||||
*/
|
||||
private String respawnLine(Received r) {
|
||||
String t = r.type;
|
||||
// Entities moving and the dead player's health land in the window between the death
|
||||
// and the respawn as each server's ticks fall: left out.
|
||||
// Entities moving, blocks the world's ticks change (a lava fall flows again once the game
|
||||
// runs) and the dead player's health land in the window between the death and the respawn
|
||||
// as each server's ticks fall: left out.
|
||||
if (t.startsWith("minecraft:move_entity") || t.equals("minecraft:rotate_head") || t.equals("minecraft:set_entity_motion")
|
||||
|| t.equals("minecraft:set_entity_data") || t.equals("minecraft:entity_position_sync") || t.equals("minecraft:set_health")) {
|
||||
|| t.equals("minecraft:set_entity_data") || t.equals("minecraft:entity_position_sync") || t.equals("minecraft:set_health")
|
||||
|| t.equals("minecraft:block_update") || t.equals("minecraft:section_blocks_update")) {
|
||||
return null;
|
||||
}
|
||||
if (t.equals("minecraft:keep_alive") || t.equals("minecraft:ping") || t.equals("minecraft:level_chunk_with_light")
|
||||
|
||||
+39
-12
@@ -227,11 +227,18 @@ def scenario(d, out):
|
||||
raise Failed('no reachable tree near spawn')
|
||||
assert broke['block_before'].startswith(log_id), broke
|
||||
assert broke['drops'].get(log_id, 0) >= 1, broke
|
||||
if broke['picked_up'].get(log_id, 0) < 1:
|
||||
# On a client of a server (single player's server thread) the drop and its pickup both come from
|
||||
# the server a few ticks later: wait for the logs in the inventory, or walk to the drop.
|
||||
for _ in range(20):
|
||||
if broke['picked_up'].get(log_id, 0) >= 1 or d('inventory')['counts'].get(log_id, 0) >= 1:
|
||||
break
|
||||
items = d('entities', radius=8, type='item')['entities']
|
||||
drop = next(e for e in items if e['item']['item'] == log_id)
|
||||
d('goto', x=drop['pos'][0], y=drop['pos'][1], z=drop['pos'][2], near=1.0, timeout=20) # pickup reaches a block; the drop may lie under the trunk
|
||||
d('wait', ticks=10)
|
||||
drop = next((e for e in items if e['item']['item'] == log_id), None)
|
||||
if drop is not None:
|
||||
d('goto', x=drop['pos'][0], y=drop['pos'][1], z=drop['pos'][2], near=1.0, timeout=20) # pickup reaches a block; the drop may lie under the trunk
|
||||
d('wait', ticks=10)
|
||||
break
|
||||
d('wait', ticks=1)
|
||||
inventory = d('inventory')
|
||||
assert inventory['counts'].get(log_id, 0) >= 1, inventory
|
||||
|
||||
@@ -244,29 +251,38 @@ def scenario(d, out):
|
||||
d('click_slot', slot=log_slot) # pick up the logs
|
||||
d('click_slot', slot=100, right=True) # put one in the crafting grid
|
||||
d('click_slot', slot=log_slot) # put the rest back
|
||||
d('wait', ticks=2) # the server crafts the result (single player's server thread)
|
||||
result = next(s for s in d('screen')['slots'] if s['slot'] == 200)
|
||||
assert result.get('item') == planks_id and result['count'] == 4, result
|
||||
d('click_slot', slot=200, shift=True) # craft into the inventory
|
||||
d('close')
|
||||
d('wait', ticks=2)
|
||||
inventory = d('inventory')
|
||||
assert inventory['counts'].get(planks_id, 0) >= 4, inventory
|
||||
|
||||
# 5. Place a plank beside the player and read it back.
|
||||
p = d('state')['player']['block_pos']
|
||||
target = None
|
||||
hotbar = d('inventory')['hotbar']
|
||||
if not any(s.get('item') == planks_id for s in hotbar):
|
||||
raise Failed(f'{planks_id} did not land in the hotbar: {hotbar}')
|
||||
target = placed = None
|
||||
for dx, dz in [(2, 0), (-2, 0), (0, 2), (0, -2), (2, 1), (1, 2), (-2, -1), (-1, -2)]:
|
||||
at = (p[0] + dx, p[1], p[2] + dz)
|
||||
here = d('block', x=at[0], y=at[1], z=at[2])['block']
|
||||
below = d('block', x=at[0], y=at[1] - 1, z=at[2])['block']
|
||||
if here in ('minecraft:air', 'minecraft:short_grass') and below not in ('minecraft:air', 'minecraft:water'):
|
||||
target = at
|
||||
break
|
||||
if here not in ('minecraft:air', 'minecraft:short_grass') or below in ('minecraft:air', 'minecraft:water'):
|
||||
continue
|
||||
# The tree's trunk above the broken log can hide a spot's faces: try the next one.
|
||||
try:
|
||||
placed = d('place', x=at[0], y=at[1], z=at[2], item=planks_id)
|
||||
except Failed as e:
|
||||
if 'no visible face' in str(e):
|
||||
continue
|
||||
raise
|
||||
target = at
|
||||
break
|
||||
if target is None:
|
||||
raise Failed(f'no free spot beside {p} to place a block')
|
||||
hotbar = d('inventory')['hotbar']
|
||||
if not any(s.get('item') == planks_id for s in hotbar):
|
||||
raise Failed(f'{planks_id} did not land in the hotbar: {hotbar}')
|
||||
placed = d('place', x=target[0], y=target[1], z=target[2], item=planks_id)
|
||||
assert placed['changed'], placed
|
||||
back = d('block', x=target[0], y=target[1], z=target[2])
|
||||
assert back['block'] == planks_id, back
|
||||
@@ -322,6 +338,7 @@ def ui_scenario(d, out):
|
||||
|
||||
# 3. The inventory's slots are widgets too, with their stacks.
|
||||
d('give', item='oak_log', count=2)
|
||||
d('wait', ticks=2) # single player's server thread gives them
|
||||
d('open_inventory')
|
||||
tree = widgets(d)
|
||||
log = next(w for w in tree.values() if w['kind'] == 'slot' and (w.get('stack') or {}).get('item') == 'minecraft:oak_log')
|
||||
@@ -329,6 +346,7 @@ def ui_scenario(d, out):
|
||||
d('click', id=log['id'])
|
||||
d('click', id='slot-100', right=True)
|
||||
d('click', id=log['id'])
|
||||
d('wait', ticks=2)
|
||||
assert widgets(d)['slot-200']['stack']['item'] == 'minecraft:oak_planks'
|
||||
d('close')
|
||||
shot = d('screenshot', path=str(out / f'{d.name}-ui.png'))
|
||||
@@ -489,6 +507,15 @@ def pick_scenario(d, out):
|
||||
d('give', item='oak_log', count=2)
|
||||
assert d('open_inventory')['screen'] == 'inventory'
|
||||
d('click', id='slot-0', middle=True)
|
||||
# The clone of step 2 lived only on this client: ItemPickerMenu's carried stack is the
|
||||
# inventoryMenu's, and AbstractContainerMenu.removed clears it only for a ServerPlayer. With a
|
||||
# stack in hand, mouseReleased sends CLONE, the server finds the carried stack it was told about
|
||||
# wrong and sends the empty one back (broadcastChanges). On the server thread that takes a
|
||||
# round trip, as in vanilla; in the frame, closing the menu already put the clone away.
|
||||
for _ in range(20):
|
||||
if carried() is None:
|
||||
break
|
||||
d('wait', ticks=1)
|
||||
assert carried() is None, carried()
|
||||
assert widgets(d)['slot-0']['stack'] == {'item': 'minecraft:oak_log', 'count': 2}
|
||||
d('close')
|
||||
|
||||
+85
-11
@@ -92,6 +92,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
server's game time after the guest's game stalls for a few seconds (#848).
|
||||
- growth: far from the host, the chunks around the guest tick (#890): water placed there flows
|
||||
and wheat on farmland grows (random ticks), however the host runs its world.
|
||||
- flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival:
|
||||
the guest, and on the server thread the host's window too, take what may fly from the
|
||||
server's abilities (ClientPacketListener.handlePlayerAbilities).
|
||||
- light: the guest's light matches the host's: around a torch placed near it, under a roof and
|
||||
once a block of the roof is removed under the sky, and in the last chunk it tracks next to
|
||||
glowstone in a chunk it doesn't (only the server's light updates bring that one).
|
||||
@@ -130,7 +133,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
# The host plays single player on its server thread (--server-thread).
|
||||
SERVER_THREAD = False
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth']
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -184,6 +187,11 @@ def remote(guest):
|
||||
return guest('status')['server']
|
||||
|
||||
|
||||
def dead(guest):
|
||||
"""Whether the guest is dead: its death screen (the last health it was sent can stay above 0)."""
|
||||
return guest('state').get('screen') == 'dead' or remote(guest)['health'] <= 0
|
||||
|
||||
|
||||
def back_to_game(game):
|
||||
"""Close whatever screen a failed check left open, without opening the pause menu."""
|
||||
try:
|
||||
@@ -243,9 +251,15 @@ def check_armour(host, guest, out):
|
||||
face_each_other(host, guest)
|
||||
host.shot(out, 'armour')
|
||||
guest.shot(out, 'armour')
|
||||
seen = lan_guest(host).get('model_armor')
|
||||
assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \
|
||||
f'the host draws the guest in {seen}'
|
||||
if SERVER_THREAD:
|
||||
# The host's window is a client of its server thread: what it draws is what it was sent.
|
||||
seen = [e for e in remote(host).get('player_equipment', [])]
|
||||
assert all(any(item in json.dumps(e) for e in seen) for item in
|
||||
('diamond_chestplate', 'diamond_leggings')), f'the host draws the guest in {seen}'
|
||||
else:
|
||||
seen = lan_guest(host).get('model_armor')
|
||||
assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \
|
||||
f'the host draws the guest in {seen}'
|
||||
host_gear = [e for e in remote(guest).get('player_equipment', [])]
|
||||
assert any('golden_chestplate' in json.dumps(e) for e in host_gear), f'the guest sees the host in {host_gear}'
|
||||
return 'each in their own'
|
||||
@@ -437,6 +451,20 @@ def check_portals(host, guest, out):
|
||||
if not SERVER_THREAD:
|
||||
return 'skipped (needs --server-thread)'
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
try:
|
||||
return portals(host, guest, out, x, y, z, hx, hy, hz)
|
||||
finally:
|
||||
# The guest comes home into its portal's frame (an obsidian ceiling three blocks up) and the
|
||||
# host onto its End portal at spawn: take both away so the next checks start in the open.
|
||||
home = 'execute in minecraft:overworld run'
|
||||
guest('command', command=f'{home} fill {x - 1} {y} {z + 3} {x + 2} {y + 3} {z + 3} minecraft:air')
|
||||
host('command', command=f'{home} setblock {hx} {hy} {hz} minecraft:air')
|
||||
guest('command', command=f'{home} tp @s {x + 0.5} {y} {z + 0.5}')
|
||||
guest.wait(20)
|
||||
|
||||
|
||||
def portals(host, guest, out, x, y, z, hx, hy, hz):
|
||||
nether_portal(guest, x, y, z + 3)
|
||||
guest.wait(5)
|
||||
guest('command', command=f'tp @s {x + 0.5} {y} {z + 3.5}')
|
||||
@@ -451,7 +479,6 @@ def check_portals(host, guest, out):
|
||||
below = guest.raw('block', arrived[0], arrived[1] - 1, arrived[2])
|
||||
assert below.get('loaded') and below.get('block') != 'minecraft:air', f'under the guest in the Nether: {below}'
|
||||
# The host takes an End portal while the guest is in the Nether: three levels at once.
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
host('command', command=f'setblock {hx} {hy} {hz} minecraft:end_portal')
|
||||
end = wait_dimension(host, 'minecraft:the_end', 600)
|
||||
host.wait(40)
|
||||
@@ -562,7 +589,7 @@ def check_hazards(host, guest, out):
|
||||
x, y, z = hx + 3, hy, hz
|
||||
for name, fill, ticks in (('lava', 'minecraft:lava', 60), ('wall', 'minecraft:stone', 60),
|
||||
('drowning', 'minecraft:water', 500), ('void', None, 60)):
|
||||
if remote(guest)['health'] <= 0:
|
||||
if dead(guest):
|
||||
guest.raw('respawn')
|
||||
guest.wait(40)
|
||||
# A stone box around the guest holds the lava and the water in.
|
||||
@@ -585,7 +612,7 @@ def check_hazards(host, guest, out):
|
||||
host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air')
|
||||
host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y - 1} {z + 1} minecraft:stone')
|
||||
guest.wait(20)
|
||||
if remote(guest)['health'] <= 0:
|
||||
if dead(guest):
|
||||
guest.raw('respawn')
|
||||
guest.wait(40)
|
||||
# [food, saturation, exhaustion]: 8 s of sprint-jumping is about 2 of exhaustion; every 4
|
||||
@@ -598,6 +625,9 @@ def check_hazards(host, guest, out):
|
||||
|
||||
|
||||
def check_pvp(host, guest, out):
|
||||
if dead(guest):
|
||||
guest.raw('respawn')
|
||||
guest.wait(40)
|
||||
for g in (host, guest):
|
||||
g('command', command='gamemode survival')
|
||||
g('command', command='item replace entity @s weapon.mainhand with minecraft:iron_sword')
|
||||
@@ -1171,7 +1201,7 @@ def check_walls(host, guest, out):
|
||||
for g in (host, guest):
|
||||
back_to_game(g)
|
||||
# The trial spawner's zombies may have killed the guest.
|
||||
if guest('state').get('screen') == 'dead' or remote(guest)['health'] <= 0:
|
||||
if dead(guest):
|
||||
guest.raw('respawn')
|
||||
guest.wait(40)
|
||||
face_each_other(host, guest)
|
||||
@@ -1784,6 +1814,50 @@ def same_light(host, guest, lo, hi, what, ticks=100):
|
||||
f'{h["sky"][i]} block {h["block"][i]}, guest sky {g["sky"][i]} block {g["block"][i]}')
|
||||
|
||||
|
||||
def check_flight(host, guest, out):
|
||||
def double_jump(game):
|
||||
# LocalPlayer.aiStep: a second jump press within 7 ticks of the first toggles flight.
|
||||
for hold in (1, 4):
|
||||
game.raw('key', 'space', 'down')
|
||||
game.wait(hold)
|
||||
game.raw('key', 'space', 'up')
|
||||
game.wait(2)
|
||||
game.wait(10)
|
||||
return game('state')['player']
|
||||
|
||||
def set_mode(game, mode):
|
||||
# On a client of a server the mode and its abilities (may fly) come back with the server's
|
||||
# answer, later when the machine is busy: a double jump before them is two plain jumps.
|
||||
game('command', command=f'gamemode {mode}')
|
||||
for _ in range(100):
|
||||
if game('state').get('gamemode') == mode:
|
||||
break
|
||||
game.wait(1)
|
||||
game.wait(10)
|
||||
|
||||
players = [('guest', guest)] + ([('host', host)] if SERVER_THREAD else [])
|
||||
seen = {}
|
||||
try:
|
||||
for name, game in players:
|
||||
set_mode(game, 'creative')
|
||||
ground = game('state')['player']
|
||||
up = double_jump(game)
|
||||
game.wait(20)
|
||||
later = game('state')['player']
|
||||
set_mode(game, 'survival')
|
||||
fell = game('state')['player']
|
||||
seen[name] = {'flying': up['flying'], 'rose': round(up['position'][1] - ground['position'][1], 2),
|
||||
'stayed': round(later['position'][1] - up['position'][1], 2),
|
||||
'survival_flying': fell['flying']}
|
||||
finally:
|
||||
for _, game in players:
|
||||
game('command', command='gamemode survival')
|
||||
for name, s in seen.items():
|
||||
assert s['flying'] and s['rose'] > 1 and abs(s['stayed']) < 0.1, f'{name} does not fly in creative: {seen}'
|
||||
assert not s['survival_flying'], f'{name} still flies in survival: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_growth(host, guest, out):
|
||||
"""Block ticks near a guest 1000 blocks from the host: only the guest's tickets tick them."""
|
||||
x0, y0, z0 = pos_of(guest)
|
||||
@@ -2086,13 +2160,13 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
|
||||
'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast,
|
||||
'light': check_light, 'plates': check_plates,
|
||||
'swings': check_swings, 'cracks': check_cracks,
|
||||
'time': check_time, 'growth': check_growth, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict}
|
||||
'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict}
|
||||
|
||||
|
||||
def run(ctl, out, resources, checks):
|
||||
host, guest = Game('host', ctl, resources), Game('guest', ctl, resources)
|
||||
if SERVER_THREAD:
|
||||
host.d.env['HORIZON_SERVER_THREAD'] = '1'
|
||||
# Either way explicitly: the game's default is the server thread.
|
||||
host.d.env['HORIZON_SERVER_THREAD'] = '1' if SERVER_THREAD else '0'
|
||||
results = {}
|
||||
try:
|
||||
host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid']
|
||||
|
||||
@@ -195,13 +195,34 @@ def run_client(binary, build, port, label, token, discovery):
|
||||
PLAYER_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*(?:Tester|Username|Disconnecting|verify username).*)$')
|
||||
|
||||
|
||||
def player_lines(lines):
|
||||
def player_lines(lines, starts=()):
|
||||
"""The lines about the player, login by login (from each index in `starts` to the next), with two races of
|
||||
vanilla's own taken out:
|
||||
- the server's thread and the login's authenticator each log in their own order, but which of the two logs
|
||||
first is a race (the authenticator disconnects a player, then logs why, while the server thread may already
|
||||
log the lost connection): each login's lines are grouped by thread;
|
||||
- a player the server disconnects ("Disconnecting ...: reason") closes the connection once it reads why, and
|
||||
when that comes before the server closes it, the lost connection is logged as "Disconnected": the kick's
|
||||
reason stands for both."""
|
||||
def thread(line):
|
||||
# `[User Authenticator #2/INFO]`: the thread, without the level; the login's authenticator first.
|
||||
name = (m := PLAYER_LINE.match(line)) and m.group(1).rsplit('/', 1)[0] or ''
|
||||
return name == 'Server thread', name
|
||||
|
||||
bounds = [0, *starts, len(lines)]
|
||||
out = []
|
||||
for line in lines:
|
||||
if m := PLAYER_LINE.match(line):
|
||||
text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2))
|
||||
text = re.sub(r'entity id \d+ at \(.*\)', 'entity id _ at _', text)
|
||||
out.append(f'[{m.group(1)}] {text}')
|
||||
for a, b in zip(bounds, bounds[1:]):
|
||||
login = []
|
||||
for line in sorted(lines[a:b], key=thread):
|
||||
if m := PLAYER_LINE.match(line):
|
||||
text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2))
|
||||
text = re.sub(r'entity id \d+ at \(.*\)', 'entity id _ at _', text)
|
||||
login.append(f'[{m.group(1)}] {text}')
|
||||
kicks = {l.rsplit('): ', 1)[1] for l in login if '] Disconnecting ' in l}
|
||||
if len(kicks) == 1:
|
||||
login = [l.removesuffix('Disconnected') + next(iter(kicks)) if l.endswith(') lost connection: Disconnected')
|
||||
else l for l in login]
|
||||
out += login
|
||||
return out
|
||||
|
||||
|
||||
@@ -228,16 +249,26 @@ def run_side(label, command, binary, build, services, discovery):
|
||||
os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery)
|
||||
server = Server(command, directory, f'{label}-online')
|
||||
checks = []
|
||||
starts = []
|
||||
|
||||
def check(name, actual, expected):
|
||||
checks.append(f'{name}: ' + ('ok' if actual == expected else f'expected {expected!r}, got {actual!r}'))
|
||||
|
||||
def login(name, token):
|
||||
"""One client run, over once the server logged the end of its connection: the server notices the
|
||||
closed connection at its next tick, and the next run's lines must not come before that one."""
|
||||
start = len(server.lines)
|
||||
starts.append(start)
|
||||
got = run_client(binary, build, port, f'{label}-{name}', token, discovery)
|
||||
wait_after(server, start, r'lost connection: ')
|
||||
return got
|
||||
|
||||
try:
|
||||
server.wait_for(r'Done \(', timeout=600)
|
||||
services.take_log()
|
||||
|
||||
# 1. Signed in: the full encrypted handshake, then play.
|
||||
got = run_client(binary, build, port, f'{label}-signed-in', GOOD, discovery)
|
||||
got = login('signed-in', GOOD)
|
||||
server.wait_for(r'Tester left the game', timeout=30)
|
||||
log = services.take_log()
|
||||
joins = [e for e in log if e[0] == 'join']
|
||||
@@ -261,20 +292,20 @@ def run_side(label, command, binary, build, services, discovery):
|
||||
|
||||
# 2. A token the session service rejects: vanilla's message, no key sent.
|
||||
mark = len(server.lines)
|
||||
got = run_client(binary, build, port, f'{label}-rejected', BAD, discovery)
|
||||
got = login('rejected', BAD)
|
||||
check('rejected token: client message', got['error'],
|
||||
'disconnected: Failed to log in: Invalid session (Try restarting your game and the launcher)')
|
||||
check('rejected token: no verification', [e[0] for e in services.take_log()], ['join'])
|
||||
|
||||
# 3. The session service forgets the join: the server refuses the player.
|
||||
got = run_client(binary, build, port, f'{label}-forgotten', FORGET, discovery)
|
||||
got = login('forgotten', FORGET)
|
||||
server.wait_for(r'Failed to verify username', timeout=30)
|
||||
check('forgotten join: client message', got['error'], 'disconnected: Failed to verify username!')
|
||||
check('forgotten join: server verified and refused',
|
||||
[(e[0], e[3]) for e in services.take_log()], [('join', True), ('verify', False)])
|
||||
|
||||
# 4. No account: refused by the client before anything is sent to the services.
|
||||
got = run_client(binary, build, port, f'{label}-no-account', None, discovery)
|
||||
got = login('no-account', None)
|
||||
check('no account: client message', got['error'] or '', 'disconnected: This server is in online mode. '
|
||||
'Sign in with your Microsoft account in the Horizon launcher to join it.')
|
||||
check('no account: no service calls', services.take_log(), [])
|
||||
@@ -283,7 +314,7 @@ def run_side(label, command, binary, build, services, discovery):
|
||||
# 5. Verified, but not on the whitelist.
|
||||
server.console('whitelist on')
|
||||
server.wait_for(r'Whitelist is now turned on', timeout=30)
|
||||
got = run_client(binary, build, port, f'{label}-not-whitelisted', GOOD, discovery)
|
||||
got = login('not-whitelisted', GOOD)
|
||||
server.wait_for(r'Disconnecting Tester', timeout=30)
|
||||
check('not whitelisted: client message', got['error'], 'disconnected: You are not white-listed on this server!')
|
||||
check('not whitelisted: verified first', [(e[0], e[3]) for e in services.take_log()],
|
||||
@@ -295,7 +326,7 @@ def run_side(label, command, binary, build, services, discovery):
|
||||
server.console('whitelist add tester')
|
||||
wait_after(server, mark, r'Added Tester to the whitelist')
|
||||
check('whitelist add: known player, no lookup', services.take_log(), [])
|
||||
got = run_client(binary, build, port, f'{label}-whitelisted', GOOD, discovery)
|
||||
got = login('whitelisted', GOOD)
|
||||
wait_after(server, mark, r'Tester left the game')
|
||||
check('whitelisted: connected throughout', got['error'], None)
|
||||
services.take_log()
|
||||
@@ -309,7 +340,7 @@ def run_side(label, command, binary, build, services, discovery):
|
||||
time.sleep(1)
|
||||
finally:
|
||||
server.stop()
|
||||
return checks, player_lines(server.lines)
|
||||
return checks, player_lines(server.lines, starts)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -68,6 +68,14 @@ IGNORED = {
|
||||
# differently (no worldgen heightmaps, entities in entities/) is accepted.
|
||||
r'^chunk\.promoted\.(Status|Heightmaps\.(OCEAN_FLOOR_WG|WORLD_SURFACE_WG)|entities)$':
|
||||
'a proto chunk vanilla left at its view distance, finished by Horizon',
|
||||
# Single player's server thread sends the chunks its player tracks (view distance 6
|
||||
# and its outer ring), as vanilla's integrated server does, so it finishes some that
|
||||
# vanilla's server (view distance 4) left before their terrain: those had no blocks,
|
||||
# light or heightmaps to compare yet.
|
||||
r'^chunk\.blank\.':
|
||||
'a chunk vanilla left before its terrain (no blocks yet), finished by Horizon',
|
||||
r'^chunk\.unlit\.':
|
||||
'a chunk vanilla left before its light, finished (and lit) by Horizon',
|
||||
# Horizon keeps simulating between loading and saving (it needs a few seconds of
|
||||
# chunk generation first), so counters and positions of live things move on.
|
||||
r'^chunk\.block_entities\.\(2, -60, 5\)\.(cooking_time_spent|lit_time_remaining|Items\[\]\.count)$':
|
||||
@@ -464,6 +472,13 @@ def normalize_chunk(root):
|
||||
return out, sections
|
||||
|
||||
|
||||
# ChunkStatus before NOISE: nothing has filled the chunk's blocks yet.
|
||||
BLANK_STATUSES = {'minecraft:empty', 'minecraft:structure_starts', 'minecraft:structure_references',
|
||||
'minecraft:biomes'}
|
||||
# ChunkStatus LIGHT and later: the chunk's light is saved.
|
||||
LIT_STATUSES = {'minecraft:light', 'minecraft:spawn', 'minecraft:full'}
|
||||
|
||||
|
||||
def compare_chunks(vanilla, horizon, report):
|
||||
for key in sorted(set(vanilla) | set(horizon)):
|
||||
if key not in horizon:
|
||||
@@ -476,9 +491,10 @@ def compare_chunks(vanilla, horizon, report):
|
||||
ha, hs = normalize_chunk(horizon[key])
|
||||
out = []
|
||||
diff(va, ha, 'chunk', out)
|
||||
if va.get('Status') != 'minecraft:full' and ha.get('Status') == 'minecraft:full':
|
||||
promoted = re.compile(r'^chunk\.(Status|Heightmaps\.\w+_WG|entities)$')
|
||||
out = [(path.replace('chunk.', 'chunk.promoted.', 1) if promoted.match(path) else path, p, q)
|
||||
promoted = va.get('Status') != 'minecraft:full' and ha.get('Status') == 'minecraft:full'
|
||||
if promoted:
|
||||
rule = re.compile(r'^chunk\.(Status|Heightmaps\.\w+_WG|entities)$')
|
||||
out = [(path.replace('chunk.', 'chunk.promoted.', 1) if rule.match(path) else path, p, q)
|
||||
for path, p, q in out]
|
||||
for y in sorted(set(vs) | set(hs)):
|
||||
empty = {'blocks': ['minecraft:air'] * 4096, 'biomes': None, 'BlockLight': None, 'SkyLight': None}
|
||||
@@ -493,6 +509,16 @@ def compare_chunks(vanilla, horizon, report):
|
||||
if a[light] != b[light]:
|
||||
out.append((f'chunk.sections.{light}[{y}]', None if a[light] is None else 'present',
|
||||
None if b[light] is None else 'present'))
|
||||
# Before its terrain a chunk has no blocks, light or heightmaps yet.
|
||||
if promoted and va.get('Status') in BLANK_STATUSES:
|
||||
blank = re.compile(r'^chunk\.(Heightmaps|sections)\.')
|
||||
out = [(path.replace('chunk.', 'chunk.blank.', 1) if blank.match(path) else path, p, q)
|
||||
for path, p, q in out]
|
||||
# Before its light step a chunk saves no light; Horizon lights what it finishes.
|
||||
elif promoted and va.get('Status') not in LIT_STATUSES:
|
||||
unlit = re.compile(r'^chunk\.sections\.(SkyLight|BlockLight)\[')
|
||||
out = [(path.replace('chunk.', 'chunk.unlit.', 1) if unlit.match(path) else path, p, q)
|
||||
for path, p, q in out]
|
||||
for path, p, q in out:
|
||||
report.append((f'{path} @{key}', p, q))
|
||||
|
||||
|
||||
@@ -236,10 +236,18 @@ def run_side(label, scenario, command, directory, client):
|
||||
time.sleep(2)
|
||||
out = directory.parent / f'{label}-{scenario}.txt'
|
||||
client(port, scenario, out)
|
||||
# Carol leaves last: stopping before the server saw her go would log another reason.
|
||||
server.wait_for(r'Carol lost connection', timeout=30)
|
||||
transcript = [f'status enforcesSecureChat {enforces}'] + out.read_text(encoding='utf-8').splitlines()
|
||||
finally:
|
||||
server.stop()
|
||||
return transcript, chat_lines(server.lines)
|
||||
# A player the server disconnects (the transcript has the reason it sent, compared there) is logged as
|
||||
# "lost connection: <that reason>", or as "Disconnected" when vanilla's network thread closed the connection
|
||||
# before its disconnect(reason) ran: a race in vanilla, so the log's reason is left out for them.
|
||||
kicked = {m.group(1) for line in transcript if (m := re.match(r'(\w+) disconnected ', line))}
|
||||
log = [re.sub(r'^(\[\w+\] (\w+) lost connection: ).*', lambda m: m.group(1) + '(the reason sent)'
|
||||
if m.group(2) in kicked else m.group(0), line) for line in chat_lines(server.lines)]
|
||||
return transcript, log
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -17,13 +17,13 @@ stops; Horizon's (`horizon-client --dedicated --nogui`) creates its own from
|
||||
the same server.properties and stops; the `spawn` position of both
|
||||
level.dat files is compared.
|
||||
|
||||
Vanilla is not deterministic everywhere: trees of neighbouring chunks
|
||||
overlap on chunk corners, and which one is placed last depends on the order
|
||||
the server's worker threads decorate the chunks. A spawn column on such a
|
||||
corner can then stand on different leaves from one vanilla run to the next.
|
||||
When the spawns differ, vanilla creates the world up to RETRIES more times;
|
||||
Horizon's spawn passes if one of vanilla's runs gives it too, and the seed is
|
||||
reported as varying in vanilla.
|
||||
Trees of neighbouring chunks overlap on chunk corners, and which one is
|
||||
placed first depends on the order the chunks are decorated. With several
|
||||
worker threads vanilla's order changes from run to run (seed
|
||||
-2080727421395798566 spawned at Y 64, 66 or 72), so its server runs with one
|
||||
(`-Dmax.bg.threads`, Util.maxAllowedExecutorThreads): the chunks are then
|
||||
decorated in its scheduler's order, the one Horizon follows
|
||||
(decoration_order::vanilla_order), and every run gives the same spawn.
|
||||
|
||||
Seeds: the player report's seed (1891623539983467248: Horizon spawned at
|
||||
-48 -48, vanilla at 152 145), the chunk generation harness's seeds and
|
||||
@@ -54,7 +54,6 @@ except ImportError:
|
||||
|
||||
NAME = 'world-spawn-parity'
|
||||
REPORT = 1891623539983467248
|
||||
RETRIES = 3
|
||||
SEEDS = [REPORT, 12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777, 0]
|
||||
RESOURCES = lab.RESOURCES
|
||||
|
||||
@@ -132,7 +131,8 @@ def main():
|
||||
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
|
||||
'compile-rust', timeout=3600)
|
||||
binary = target_dir() / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
vanilla_server = ['java', '-Xmx2g', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
# One worker thread: the chunks decorated in a fixed order (see above).
|
||||
vanilla_server = ['java', '-Xmx2g', '-Dmax.bg.threads=1', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui']
|
||||
os.environ['HORIZON_NO_AUDIO'] = '1'
|
||||
|
||||
@@ -140,27 +140,20 @@ def main():
|
||||
t0 = time.time()
|
||||
a = world_spawn(vanilla_server, build / f'vanilla-{seed}', seed, f'vanilla-{seed}')
|
||||
b = world_spawn(horizon_server, build / f'horizon-{seed}', seed, f'horizon-{seed}')
|
||||
runs = [a]
|
||||
while b not in runs and len(runs) <= RETRIES:
|
||||
runs.append(world_spawn(vanilla_server, build / f'vanilla-{seed}-{len(runs)}', seed, f'vanilla-{seed}-{len(runs)}'))
|
||||
return seed, runs, b, time.time() - t0
|
||||
return seed, a, b, time.time() - t0
|
||||
|
||||
spawn_diffs, varying = [], []
|
||||
spawn_diffs = []
|
||||
with ThreadPoolExecutor(args.jobs) as pool:
|
||||
for seed, runs, b, took in pool.map(one, all_seeds):
|
||||
ok = b in runs
|
||||
for seed, a, b, took in pool.map(one, all_seeds):
|
||||
ok = a == b
|
||||
if not ok:
|
||||
spawn_diffs.append(seed)
|
||||
elif len(set(runs)) > 1:
|
||||
varying.append(seed)
|
||||
seen = ', '.join(' '.join(map(str, r)) for r in dict.fromkeys(runs))
|
||||
print(f'{"ok " if ok else "DIFF"} {seed}: vanilla {seen} / horizon {b[0]} {b[1]} {b[2]} '
|
||||
print(f'{"ok " if ok else "DIFF"} {seed}: vanilla {a[0]} {a[1]} {a[2]} / horizon {b[0]} {b[1]} {b[2]} '
|
||||
f'(origin chunk {vanilla[seed][2]} {vanilla[seed][3]}; {took:.0f}s)', flush=True)
|
||||
if ok:
|
||||
for path in build.glob(f'*-{seed}*'):
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
print(f'World spawns: {len(all_seeds) - len(spawn_diffs)}/{len(all_seeds)} seeds match in {time.time() - started:.0f}s'
|
||||
+ (f'; vanilla itself gave several spawns for {len(varying)}: {varying}' if varying else ''))
|
||||
print(f'World spawns: {len(all_seeds) - len(spawn_diffs)}/{len(all_seeds)} seeds match in {time.time() - started:.0f}s')
|
||||
if origin_diffs or spawn_diffs:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ In part. Horizon runs the full-screen effects of Java shader packs, not their ge
|
||||
|
||||
## Does Horizon collect data?
|
||||
|
||||
Only if you say yes, and each kind has its own switch. Everything is off by default. See [Privacy](/privacy).
|
||||
Only if you say yes, and each kind has its own switch. Everything is off by default. The one thing sent without asking is an anonymous "I'm playing" ping, for the count of how many play right now: it holds a random number made each time the game starts, the version, your OS and whether a world is open to LAN, and nothing about you. See [Privacy](/privacy).
|
||||
|
||||
## How often does it update?
|
||||
|
||||
|
||||
@@ -52,4 +52,4 @@ A Horizon bug is any place where it differs from vanilla 26.3, so "vanilla does
|
||||
|
||||
## Data the launcher can send
|
||||
|
||||
The launcher can send performance statistics, crash reports, bug reports and benchmarks, but only the kinds you allow, and everything is off until you say yes. See [Privacy](/privacy) for what is sent, how long it is kept and how to delete it.
|
||||
The launcher can send performance statistics, crash reports, bug reports and benchmarks, but only the kinds you allow, and everything is off until you say yes. The game also sends an anonymous "I'm playing" ping while it runs, for the live player count. See [Privacy](/privacy) for what is sent, how long it is kept and how to delete it.
|
||||
|
||||
@@ -17,8 +17,8 @@
|
||||
<main id="main" class="section">
|
||||
<div class="container">
|
||||
<p class="kicker"><span>Privacy</span>Data collection</p>
|
||||
<h1 class="display">Nothing leaves without your yes.</h1>
|
||||
<p class="lede">The Horizon launcher can send a few things that help make the game faster and steadier. It asks first, each kind has its own switch, and every switch is off until you turn it on.</p>
|
||||
<h1 class="display">Nothing about you leaves without your yes.</h1>
|
||||
<p class="lede">The Horizon launcher can send a few things that help make the game faster and steadier. It asks first, each kind has its own switch, and every switch is off until you turn it on. The only thing sent without asking is an anonymous "I'm playing" ping, which says nothing about you.</p>
|
||||
<div class="prose">
|
||||
<h2>What can be sent</h2>
|
||||
<p>Only the kinds you allow, from the launcher's first-run question or Settings → Data collection:</p>
|
||||
@@ -32,11 +32,16 @@
|
||||
<p>Never sent: your Microsoft or Minecraft account name or UUID, world names, server or LAN addresses, chat, and your user name or home folder in file paths. Before anything is kept, those are replaced with placeholders, along with e-mail and IP addresses. The server does not store the IP address requests come from.</p>
|
||||
<p>The launcher shows exactly what would be sent: Settings → Data collection → View what would be sent, or <code>horizon-launcher data show</code>. Every field is listed in <a href="https://github.com/ludovic111/horizon/blob/main/docs/telemetry.md">docs/telemetry.md</a>.</p>
|
||||
|
||||
<h2>The "I'm playing" ping</h2>
|
||||
<p>While you play, the game sends an anonymous "I'm playing" ping once a minute, so the launcher can show how many people play Horizon right now. It is sent whatever the switches say, and the launcher says so next to them.</p>
|
||||
<p>It holds: a random number made when the game starts and forgotten when it closes, the Horizon version, your operating system (Linux, macOS or Windows), and whether you have a world open to LAN or to friends. It doesn't hold: your account, your install ID, world or server names, your hardware or settings, or anything you do in the game. The random number changes every time you start the game, so two of your sessions can't be linked to each other or to you.</p>
|
||||
<p>The server keeps the pings in memory only, never on disk, and not with the address they came from (that is used only to stop abuse, as below). A session counts while it pinged in the last two minutes and is then forgotten. What it shows is the number playing now, per version and with a world open, rounded.</p>
|
||||
|
||||
<h2>Why</h2>
|
||||
<p>To find what is slow or crashes on which machines, and fix it. Benchmark uploads also show other players how Horizon runs on hardware like theirs. Nothing is sold, shared for advertising, or used to identify you.</p>
|
||||
<p>To find what is slow or crashes on which machines, and fix it. The ping shows players, and Horizon, how many people play right now. Benchmark uploads also show other players how Horizon runs on hardware like theirs. Nothing is sold, shared for advertising, or used to identify you.</p>
|
||||
|
||||
<h2>On what basis</h2>
|
||||
<p>Your consent (Article 6(1)(a) of the EU's General Data Protection Regulation). It is given kind by kind, recorded on your computer with the version of the question you answered and when, and withdrawn at any time with the same switches. Withdrawing deletes what was waiting to be sent. When what is collected changes, the launcher asks again, and nothing new is sent until you answer.</p>
|
||||
<p>For the switches: your consent (Article 6(1)(a) of the EU's General Data Protection Regulation). It is given kind by kind, recorded on your computer with the version of the question you answered and when, and withdrawn at any time with the same switches. Withdrawing deletes what was waiting to be sent. When what is collected changes, the launcher asks again, and nothing new is sent until you answer. The ping holds nothing that identifies you; the address it comes from is used only to limit how often one address may send, kept in memory for an hour at most and never stored.</p>
|
||||
|
||||
<h2>Where and how long</h2>
|
||||
<p>Items wait on your computer (<code>telemetry/</code> in the game folder) and are sent compressed when the launcher starts or closes, to Horizon's own server at <a href="https://railway.com">Railway</a>. The server keeps them for <strong>180 days</strong>, then deletes them. What stays after that are anonymous totals per day, Horizon version, operating system, GPU maker and render distance (for example "120 sessions on macOS with Apple GPUs at render distance 12"). They hold no install ID, and groups too small to be anonymous are never shown.</p>
|
||||
|
||||
Reference in New Issue
Block a user