Merge origin/main: game-bugs and launcher 0.1.2
Villager POI search: main's per-search state classification replaces this branch's state table (same sections skipped, same positions in order). status keeps main's mob and block-entity counts and this branch's pending uploads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,7 +6,7 @@ name: launcher
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [launcher]
|
||||
branches: [launcher, 'launcher-*']
|
||||
tags: ['launcher-v*']
|
||||
|
||||
permissions:
|
||||
@@ -27,7 +27,12 @@ jobs:
|
||||
- os: windows-latest
|
||||
asset: horizon-launcher-windows-x64.zip
|
||||
binary: horizon-launcher.exe
|
||||
# The C runtime linked in: without it the launcher asks for VCRUNTIME140.dll,
|
||||
# which only the Visual C++ redistributable installs.
|
||||
rustflags: -C target-feature=+crt-static
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
RUSTFLAGS: ${{ matrix.rustflags }}
|
||||
defaults:
|
||||
run:
|
||||
working-directory: launcher
|
||||
@@ -48,6 +53,42 @@ jobs:
|
||||
run: grep -qx "version = \"${GITHUB_REF_NAME#launcher-v}\"" Cargo.toml
|
||||
- run: cargo test --release --locked --lib
|
||||
- run: cargo build --release --locked
|
||||
- name: Only system libraries
|
||||
if: runner.os == 'Windows'
|
||||
run: python ../tools/check_imports.py target/release/${{ matrix.binary }}
|
||||
- name: Smoke test
|
||||
env:
|
||||
HORIZON_LAUNCHER_NO_SELF_UPDATE: '1'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
export HORIZON_LAUNCHER_HOME="${RUNNER_TEMP//\\//}/horizon-launcher-smoke"
|
||||
export HORIZON_HOME="$HORIZON_LAUNCHER_HOME/game"
|
||||
launcher="$PWD/target/release/${{ matrix.binary }}"
|
||||
# GitHub's API rate-limits shared runner addresses now and then: try a few times.
|
||||
retry() { for i in 1 2 3 4; do "$@" && return 0; sleep $((i * 15)); done; return 1; }
|
||||
"$launcher" --version
|
||||
retry "$launcher" versions
|
||||
retry "$launcher" install latest
|
||||
"$launcher" versions --installed
|
||||
"$launcher" links --json
|
||||
"$launcher" menu-style classic
|
||||
grep -qx 'menuStyle:classic' "$HORIZON_HOME/horizon.txt"
|
||||
"$launcher" menu-style horizon
|
||||
clients=("$HORIZON_LAUNCHER_HOME"/versions/v*/horizon-client*)
|
||||
client="${clients[0]}"
|
||||
echo "installed client: $client"
|
||||
# The game's Linux build is the game's to keep portable (release.yml checks it): a
|
||||
# release linked to a Nix store is a warning here, not a broken launcher.
|
||||
soft() { if [[ "$RUNNER_OS" == "Linux" ]]; then "$@" || echo "::warning::$* failed"; else "$@"; fi; }
|
||||
if [[ "$RUNNER_OS" == "Windows" ]]; then
|
||||
python ../tools/check_imports.py "$client"
|
||||
python ../tools/check_imports.py "$launcher"
|
||||
elif [[ "$RUNNER_OS" == "Linux" ]]; then
|
||||
soft python3 ../tools/check_imports.py "$client"
|
||||
fi
|
||||
# The client starts: --help prints before any window or GPU is needed.
|
||||
help() { "$client" --help > "$RUNNER_TEMP/help.txt" 2>&1 && head -3 "$RUNNER_TEMP/help.txt" && grep -q -- '--resources' "$RUNNER_TEMP/help.txt"; }
|
||||
soft help
|
||||
- name: Package
|
||||
run: |
|
||||
mkdir -p dist
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
name: release builds
|
||||
# Started by hand: gh workflow run release.yml --ref <branch>
|
||||
# Builds the Windows x64 client and uploads the playable folder as an artifact.
|
||||
# Linux and macOS builds are made on the development machines.
|
||||
# Builds the Windows x64 and Linux x86_64 clients and uploads the playable folders as artifacts.
|
||||
# macOS builds are made on the development machines. Linux is built here, on an older Ubuntu,
|
||||
# so the binary uses the standard loader and runs on any recent distribution (and on NixOS
|
||||
# through nix-ld): a build made on NixOS asks for a /nix/store loader no other system has.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
@@ -18,6 +20,10 @@ jobs:
|
||||
env:
|
||||
RUSTFLAGS: -C target-feature=+crt-static
|
||||
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client
|
||||
- name: Only system DLLs
|
||||
# Vulkan and the rest are loaded at run time; a linked non-system DLL is a
|
||||
# "DLL not found" dialog on some players' machines.
|
||||
run: python tools/check_imports.py target/release/horizon-client.exe
|
||||
- name: Package
|
||||
shell: bash
|
||||
run: packaging/package.sh target/release/horizon-client.exe dist/horizon-windows-x64
|
||||
@@ -25,3 +31,21 @@ jobs:
|
||||
with:
|
||||
name: horizon-windows-x64
|
||||
path: dist/horizon-windows-x64
|
||||
linux:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust toolchain
|
||||
run: rustup toolchain install stable --profile minimal
|
||||
- name: ALSA headers
|
||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev
|
||||
- name: Build the client
|
||||
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client
|
||||
- name: Standard loader and libraries only
|
||||
run: python3 tools/check_imports.py target/release/horizon-client
|
||||
- name: Package
|
||||
run: packaging/package.sh target/release/horizon-client dist/horizon-linux-x86_64
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: horizon-linux-x86_64
|
||||
path: dist/horizon-linux-x86_64
|
||||
|
||||
@@ -61,10 +61,78 @@ pub struct Heard {
|
||||
pub struct MixerBackend {
|
||||
mixer: Arc<Mutex<Mixer>>,
|
||||
root: PathBuf,
|
||||
cache: HashMap<String, Option<(Arc<Vec<f32>>, u32)>>,
|
||||
cache: Arc<Mutex<SoundCache>>,
|
||||
/// The decoder thread for static sounds, started with the first one.
|
||||
decoder: Option<std::sync::mpsc::Sender<Decode>>,
|
||||
next: ChannelId,
|
||||
live: bool,
|
||||
}
|
||||
/// Decoded samples and their rate (`None`: the file did not load).
|
||||
type Samples = Option<(Arc<Vec<f32>>, u32)>;
|
||||
/// Decoded static sounds (`SoundBufferLibrary`'s buffers), dropped least
|
||||
/// recently used first past `CACHE_BYTES`: kept forever, every sound heard in
|
||||
/// a session stayed (up to 1.4 GiB of samples, villages playing hundreds).
|
||||
#[derive(Default)]
|
||||
struct SoundCache {
|
||||
entries: HashMap<String, (Samples, u64)>,
|
||||
bytes: usize,
|
||||
clock: u64,
|
||||
}
|
||||
const CACHE_BYTES: usize = 64 << 20;
|
||||
impl SoundCache {
|
||||
fn get(&mut self, key: &str) -> Option<Samples> {
|
||||
self.clock += 1;
|
||||
let entry = self.entries.get_mut(key)?;
|
||||
entry.1 = self.clock;
|
||||
Some(entry.0.clone())
|
||||
}
|
||||
fn insert(&mut self, key: String, samples: Samples) {
|
||||
self.clock += 1;
|
||||
self.bytes += Self::size(&samples);
|
||||
if let Some((old, _)) = self.entries.insert(key, (samples, self.clock)) {
|
||||
self.bytes -= Self::size(&old);
|
||||
}
|
||||
while self.bytes > CACHE_BYTES && self.entries.len() > 1 {
|
||||
let Some(oldest) = self
|
||||
.entries
|
||||
.iter()
|
||||
.min_by_key(|(_, (_, used))| *used)
|
||||
.map(|(k, _)| k.clone())
|
||||
else {
|
||||
break;
|
||||
};
|
||||
if let Some((gone, _)) = self.entries.remove(&oldest) {
|
||||
self.bytes -= Self::size(&gone);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn size(samples: &Samples) -> usize {
|
||||
samples
|
||||
.as_ref()
|
||||
.map_or(0, |(s, _)| s.len() * std::mem::size_of::<f32>())
|
||||
}
|
||||
}
|
||||
/// A static sound to decode for a channel waiting on it.
|
||||
struct Decode {
|
||||
key: String,
|
||||
file: PathBuf,
|
||||
channel: ChannelId,
|
||||
}
|
||||
/// Give a channel waiting on its sound the decoded samples and start it, as
|
||||
/// the buffer future attaching and playing the source. A source stopped or
|
||||
/// released meanwhile stays so.
|
||||
fn attach(mixer: &Mutex<Mixer>, channel: ChannelId, samples: Samples, looping: bool) {
|
||||
if let Some(samples) = samples
|
||||
&& let Ok(mut m) = mixer.lock()
|
||||
&& let Some(c) = m.channels.get_mut(&channel)
|
||||
&& c.state == State::Initial
|
||||
{
|
||||
c.samples = Some(samples);
|
||||
c.position = 0.0;
|
||||
c.state = State::Playing;
|
||||
c.looping |= looping;
|
||||
}
|
||||
}
|
||||
pub struct Audio {
|
||||
_stream: Option<cpal::Stream>,
|
||||
pub engine: SoundEngine,
|
||||
@@ -176,53 +244,59 @@ impl Backend for MixerBackend {
|
||||
fn set_relative(&mut self, channel: ChannelId, relative: bool) {
|
||||
self.with(channel, |c| c.relative = relative);
|
||||
}
|
||||
/// `getCompleteBuffer` (decoded now, cached) or `getStream` (decoded on a
|
||||
/// worker), then attach and `alSourcePlay`. A sound that cannot load
|
||||
/// leaves its source initial, as a failed buffer future does in vanilla.
|
||||
/// `getCompleteBuffer` (cached, else decoded on the decoder thread) or
|
||||
/// `getStream` (decoded on a thread of its own), then attach and
|
||||
/// `alSourcePlay`. A sound that cannot load leaves its source initial,
|
||||
/// as a failed buffer future does in vanilla.
|
||||
fn start(&mut self, channel: ChannelId, sound: &Sound, looping: bool) {
|
||||
if !self.live {
|
||||
return;
|
||||
}
|
||||
let (namespace, path) = sound.path();
|
||||
let file = self.root.join("assets").join(namespace).join(&path);
|
||||
let attach = move |mixer: &Mutex<Mixer>, samples: Option<(Arc<Vec<f32>>, u32)>| {
|
||||
if let Some(samples) = samples
|
||||
&& let Ok(mut m) = mixer.lock()
|
||||
&& let Some(c) = m.channels.get_mut(&channel)
|
||||
{
|
||||
c.samples = Some(samples);
|
||||
c.position = 0.0;
|
||||
c.state = State::Playing;
|
||||
}
|
||||
};
|
||||
if sound.stream {
|
||||
// A streamed sound loops by restarting its stream.
|
||||
let mixer = self.mixer.clone();
|
||||
std::thread::spawn(move || {
|
||||
let samples = decode(&file).map(|(s, r)| (Arc::new(s), r));
|
||||
if looping
|
||||
&& let Ok(mut m) = mixer.lock()
|
||||
&& let Some(c) = m.channels.get_mut(&channel)
|
||||
{
|
||||
c.looping = true;
|
||||
}
|
||||
attach(&mixer, samples);
|
||||
attach(&mixer, channel, samples, looping);
|
||||
});
|
||||
} else {
|
||||
let samples = self
|
||||
.cache
|
||||
.entry(format!("{namespace}:{path}"))
|
||||
.or_insert_with(|| decode(&file).map(|(s, r)| (Arc::new(s), r)))
|
||||
.clone();
|
||||
attach(&self.mixer, samples);
|
||||
return;
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, channel: ChannelId) {
|
||||
self.with(channel, |c| {
|
||||
if c.state != State::Initial {
|
||||
c.state = State::Stopped;
|
||||
}
|
||||
let key = format!("{namespace}:{path}");
|
||||
let cached = self.cache.lock().ok().and_then(|mut c| c.get(&key));
|
||||
if let Some(samples) = cached {
|
||||
attach(&self.mixer, channel, samples, false);
|
||||
return;
|
||||
}
|
||||
let decoder = self.decoder.get_or_insert_with(|| {
|
||||
let (send, receive) = std::sync::mpsc::channel::<Decode>();
|
||||
let (mixer, cache) = (self.mixer.clone(), self.cache.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("sound decoder".into())
|
||||
.spawn(move || {
|
||||
for job in receive {
|
||||
// Queued twice before the first decode finished.
|
||||
let cached = cache.lock().ok().and_then(|mut c| c.get(&job.key));
|
||||
let samples = cached.unwrap_or_else(|| {
|
||||
let samples = decode(&job.file).map(|(s, r)| (Arc::new(s), r));
|
||||
if let Ok(mut c) = cache.lock() {
|
||||
c.insert(job.key, samples.clone());
|
||||
}
|
||||
samples
|
||||
});
|
||||
attach(&mixer, job.channel, samples, false);
|
||||
}
|
||||
})
|
||||
.expect("sound decoder thread");
|
||||
send
|
||||
});
|
||||
let _ = decoder.send(Decode { key, file, channel });
|
||||
}
|
||||
/// `alSourceStop`: any state becomes stopped, an initial source too (a
|
||||
/// sound still decoding then never starts).
|
||||
fn stop(&mut self, channel: ChannelId) {
|
||||
self.with(channel, |c| c.state = State::Stopped);
|
||||
}
|
||||
fn pause(&mut self, channel: ChannelId) {
|
||||
self.with(channel, |c| {
|
||||
@@ -327,6 +401,71 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
|
||||
*s = s.clamp(-1.0, 1.0);
|
||||
}
|
||||
}
|
||||
/// Why the game should not open an output, if it should not:
|
||||
/// `HORIZON_NO_AUDIO`, or a virtual screen (`vscreen`), where agents and
|
||||
/// harnesses run the game and must stay off the user's speakers.
|
||||
/// `HORIZON_AUDIO=1` opens the output anyway (testing into a null sink).
|
||||
fn output_disabled(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<String> {
|
||||
if var("HORIZON_NO_AUDIO").is_some() {
|
||||
return Some("audio off: HORIZON_NO_AUDIO is set".into());
|
||||
}
|
||||
if var("HORIZON_AUDIO").is_some_and(|v| v == "1") {
|
||||
return None;
|
||||
}
|
||||
let display = var("WAYLAND_DISPLAY")?;
|
||||
Path::new(&display)
|
||||
.components()
|
||||
.any(|c| c.as_os_str() == "vscreen")
|
||||
.then(|| "audio off on a virtual screen (vscreen); HORIZON_AUDIO=1 opens it".into())
|
||||
}
|
||||
/// An output stream on `device` in its default configuration, whatever its
|
||||
/// sample format: the mixer works in f32 and converts.
|
||||
fn open_device(
|
||||
device: &cpal::Device,
|
||||
mixer: Arc<Mutex<Mixer>>,
|
||||
) -> Result<(cpal::Stream, cpal::SupportedStreamConfig)> {
|
||||
use cpal::SampleFormat as F;
|
||||
let config = device.default_output_config()?;
|
||||
let stream = match config.sample_format() {
|
||||
F::F32 => build_stream::<f32>(device, &config, mixer),
|
||||
F::F64 => build_stream::<f64>(device, &config, mixer),
|
||||
F::I16 => build_stream::<i16>(device, &config, mixer),
|
||||
F::I32 => build_stream::<i32>(device, &config, mixer),
|
||||
F::I8 => build_stream::<i8>(device, &config, mixer),
|
||||
F::U16 => build_stream::<u16>(device, &config, mixer),
|
||||
F::U32 => build_stream::<u32>(device, &config, mixer),
|
||||
F::U8 => build_stream::<u8>(device, &config, mixer),
|
||||
other => Err(format!("unsupported sample format {other}").into()),
|
||||
}?;
|
||||
stream.play()?;
|
||||
Ok((stream, config))
|
||||
}
|
||||
fn build_stream<T: cpal::SizedSample + cpal::FromSample<f32>>(
|
||||
device: &cpal::Device,
|
||||
config: &cpal::SupportedStreamConfig,
|
||||
mixer: Arc<Mutex<Mixer>>,
|
||||
) -> Result<cpal::Stream> {
|
||||
let rate = config.sample_rate().0;
|
||||
let channels = config.channels() as usize;
|
||||
let mut scratch = Vec::new();
|
||||
let stream = device.build_output_stream(
|
||||
&config.config(),
|
||||
move |data: &mut [T], _| {
|
||||
scratch.resize(data.len(), 0.0f32);
|
||||
if let Ok(mut m) = mixer.lock() {
|
||||
mix(&mut m, &mut scratch, channels, rate);
|
||||
} else {
|
||||
scratch.fill(0.0);
|
||||
}
|
||||
for (out, s) in data.iter_mut().zip(&scratch) {
|
||||
*out = T::from_sample(*s);
|
||||
}
|
||||
},
|
||||
|e| eprintln!("Horizon: audio stream error: {e}"),
|
||||
None,
|
||||
)?;
|
||||
Ok(stream)
|
||||
}
|
||||
impl Audio {
|
||||
pub fn new(root: &Path) -> Self {
|
||||
Self::with_output(root, true)
|
||||
@@ -347,7 +486,7 @@ impl Audio {
|
||||
Ok(v) => (Some(v), true),
|
||||
Err(e) => {
|
||||
if output {
|
||||
eprintln!("Horizon: audio unavailable: {e}");
|
||||
eprintln!("Horizon: no sound: {e}");
|
||||
}
|
||||
(None, false)
|
||||
}
|
||||
@@ -360,7 +499,8 @@ impl Audio {
|
||||
backend: MixerBackend {
|
||||
mixer,
|
||||
root: root.to_owned(),
|
||||
cache: HashMap::new(),
|
||||
cache: Arc::default(),
|
||||
decoder: None,
|
||||
next: 0,
|
||||
live,
|
||||
},
|
||||
@@ -374,32 +514,40 @@ impl Audio {
|
||||
}
|
||||
}
|
||||
fn open(mixer: Arc<Mutex<Mixer>>) -> Result<cpal::Stream> {
|
||||
// Test runs (harnesses, agents) launch the game on a virtual screen;
|
||||
// keep them off the user's speakers.
|
||||
if std::env::var_os("HORIZON_NO_AUDIO").is_some() {
|
||||
return Err("audio output disabled by HORIZON_NO_AUDIO".into());
|
||||
if let Some(reason) = output_disabled(|name| std::env::var_os(name)) {
|
||||
return Err(reason.into());
|
||||
}
|
||||
let host = cpal::default_host();
|
||||
let device = host
|
||||
.default_output_device()
|
||||
.ok_or("no audio output device")?;
|
||||
let config = device.default_output_config()?;
|
||||
let rate = config.sample_rate().0;
|
||||
let channels = config.channels() as usize;
|
||||
let stream = device.build_output_stream(
|
||||
&config.into(),
|
||||
move |data: &mut [f32], _| {
|
||||
if let Ok(mut m) = mixer.lock() {
|
||||
mix(&mut m, data, channels, rate);
|
||||
} else {
|
||||
data.fill(0.0);
|
||||
let mut errors = Vec::new();
|
||||
// The default device first, then any other output a host lists:
|
||||
// a default that cannot open (busy, or a stale ALSA default) should
|
||||
// not leave the game silent when another device works.
|
||||
let default = host.default_output_device();
|
||||
let others = host.output_devices().into_iter().flatten();
|
||||
let mut tried = Vec::new();
|
||||
for device in default.into_iter().chain(others) {
|
||||
let name = device.name().unwrap_or_else(|_| "unnamed device".into());
|
||||
if tried.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
tried.push(name.clone());
|
||||
match open_device(&device, mixer.clone()) {
|
||||
Ok((stream, config)) => {
|
||||
eprintln!(
|
||||
"Horizon: audio output {name} ({} Hz, {} channels, {})",
|
||||
config.sample_rate().0,
|
||||
config.channels(),
|
||||
config.sample_format()
|
||||
);
|
||||
return Ok(stream);
|
||||
}
|
||||
},
|
||||
|e| eprintln!("Horizon: audio stream error: {e}"),
|
||||
None,
|
||||
)?;
|
||||
stream.play()?;
|
||||
Ok(stream)
|
||||
Err(e) => errors.push(format!("{name}: {e}")),
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
return Err(format!("no audio output device on the {} host", host.id().name()).into());
|
||||
}
|
||||
Err(format!("no audio output device opened ({})", errors.join("; ")).into())
|
||||
}
|
||||
fn bound(&mut self) -> Bound<'_, MixerBackend> {
|
||||
Bound {
|
||||
@@ -525,6 +673,21 @@ impl Audio {
|
||||
self.release(id);
|
||||
}
|
||||
/// Every sound event id (for command completion).
|
||||
/// The engine's table sizes and the mixer's channels (`status`).
|
||||
pub fn census(&self) -> serde_json::Value {
|
||||
let mut census = self.engine.census();
|
||||
census["channels"] = self
|
||||
.backend
|
||||
.mixer
|
||||
.lock()
|
||||
.map_or(0, |m| m.channels.len())
|
||||
.into();
|
||||
if let Ok(cache) = self.backend.cache.lock() {
|
||||
census["decoded"] = cache.entries.len().into();
|
||||
census["decoded_mib"] = (cache.bytes >> 20).into();
|
||||
}
|
||||
census
|
||||
}
|
||||
pub fn event_names(&self) -> Vec<String> {
|
||||
let mut v: Vec<String> = self.engine.registry.names().cloned().collect();
|
||||
v.sort();
|
||||
@@ -590,6 +753,47 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_sounds_stay_within_the_budget_least_recently_used_out() {
|
||||
let mut cache = SoundCache::default();
|
||||
let quarter = CACHE_BYTES / 4 / std::mem::size_of::<f32>();
|
||||
let sound = || Some((Arc::new(vec![0.0f32; quarter]), 44100));
|
||||
for key in ["a", "b", "c", "d"] {
|
||||
cache.insert(key.into(), sound());
|
||||
}
|
||||
assert!(cache.get("a").is_some());
|
||||
cache.insert("e".into(), sound());
|
||||
assert!(cache.bytes <= CACHE_BYTES);
|
||||
assert!(
|
||||
cache.get("b").is_none(),
|
||||
"the least recently used goes first"
|
||||
);
|
||||
assert!(cache.get("a").is_some() && cache.get("e").is_some());
|
||||
// A failed load is remembered without counting.
|
||||
cache.insert("missing".into(), None);
|
||||
assert_eq!(cache.get("missing"), Some(None));
|
||||
}
|
||||
#[test]
|
||||
fn output_stays_off_on_a_virtual_screen_unless_asked() {
|
||||
let env = |pairs: &'static [(&'static str, &'static str)]| {
|
||||
move |name: &str| {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(k, _)| *k == name)
|
||||
.map(|(_, v)| std::ffi::OsString::from(*v))
|
||||
}
|
||||
};
|
||||
assert!(output_disabled(env(&[("WAYLAND_DISPLAY", "wayland-1")])).is_none());
|
||||
assert!(output_disabled(env(&[])).is_none());
|
||||
const VSCREEN: &str = "/run/user/1000/vscreen/main/wayland-1";
|
||||
assert!(output_disabled(env(&[("WAYLAND_DISPLAY", VSCREEN)])).is_some());
|
||||
assert!(
|
||||
output_disabled(env(&[("WAYLAND_DISPLAY", VSCREEN), ("HORIZON_AUDIO", "1")])).is_none()
|
||||
);
|
||||
assert!(
|
||||
output_disabled(env(&[("HORIZON_NO_AUDIO", "1"), ("HORIZON_AUDIO", "1")])).is_some()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn linear_attenuation_reaches_zero_at_the_max_distance() {
|
||||
assert_eq!(distance_gain(None, 100.0), 1.0);
|
||||
|
||||
@@ -547,6 +547,7 @@ impl Game<'_> {
|
||||
"present_mode": format!("{:?}", r.config.present_mode),
|
||||
"drawn_sections": r.drawn_sections,
|
||||
"uploaded_bytes": r.uploaded_bytes,
|
||||
"resident_sections": r.resident_sections(),
|
||||
})
|
||||
});
|
||||
json!({
|
||||
@@ -566,6 +567,7 @@ impl Game<'_> {
|
||||
"ticks": self.ticks,
|
||||
"day_time": self.world.day_time,
|
||||
"music": self.music.current(&self.audio.engine),
|
||||
"sounds": self.audio.census(),
|
||||
"fishing": self.hook_status(),
|
||||
"tridents": self.tridents.len(),
|
||||
"rockets": self.rockets.len(),
|
||||
@@ -575,6 +577,8 @@ impl Game<'_> {
|
||||
"using": self.using,
|
||||
"render_distance": self.streaming.radius,
|
||||
"chunks": self.world.chunks.len(),
|
||||
"mobs": self.mobs.len(),
|
||||
"block_entities": self.world.block_entities.len(),
|
||||
"pending_chunks": self.streaming.pending() + self.pending_uploads.len(),
|
||||
"generated_chunks": self.streaming.generated_total,
|
||||
"meshed_sections": self.streaming.meshed_total,
|
||||
|
||||
@@ -267,6 +267,24 @@ fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec<u8>, u32) {
|
||||
}
|
||||
(out, levels)
|
||||
}
|
||||
/// What to tell a player whose system offers no usable graphics adapter.
|
||||
/// Vulkan is loaded at run time (the game links no graphics library), so a
|
||||
/// missing driver shows here rather than as a missing-DLL dialog.
|
||||
#[cfg(target_os = "windows")]
|
||||
const NO_GPU_DRIVER: &str = "No Vulkan graphics driver found: Horizon needs a GPU driver with Vulkan \
|
||||
(vulkan-1.dll comes with it). Install the latest driver for your NVIDIA, AMD or Intel GPU \
|
||||
and start the game again";
|
||||
#[cfg(target_os = "macos")]
|
||||
const NO_GPU_DRIVER: &str = "No Metal graphics device found";
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
|
||||
const NO_GPU_DRIVER: &str = "No Vulkan graphics driver found: Horizon needs the Vulkan loader \
|
||||
(libvulkan.so.1) and a Vulkan driver for your GPU (Mesa's, or NVIDIA's)";
|
||||
impl Renderer {
|
||||
/// Sections with GPU buffers, for soak tests watching residency.
|
||||
pub fn resident_sections(&self) -> usize {
|
||||
self.sections.len()
|
||||
}
|
||||
}
|
||||
impl Renderer {
|
||||
pub async fn new(
|
||||
window: Arc<Window>,
|
||||
@@ -294,7 +312,8 @@ impl Renderer {
|
||||
force_fallback_adapter: false,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|e| format!("{NO_GPU_DRIVER} ({e})"))?;
|
||||
let info = adapter.get_info();
|
||||
eprintln!(
|
||||
"Horizon renderer: {} ({:?}, {:?})",
|
||||
|
||||
@@ -5,6 +5,13 @@ mod game;
|
||||
fn main() {
|
||||
if let Err(error) = game::run() {
|
||||
eprintln!("Horizon: {error}");
|
||||
// Started from Explorer, the console window closes with the game:
|
||||
// keep the message on screen until it is read.
|
||||
#[cfg(windows)]
|
||||
if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
|
||||
eprintln!("Press Enter to close.");
|
||||
let _ = std::io::stdin().read_line(&mut String::new());
|
||||
}
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ use horizon_core::{
|
||||
geometry::Vec3,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// `MemorySlot.NEVER_EXPIRE`.
|
||||
pub(super) const NEVER: i64 = i64::MAX;
|
||||
@@ -843,12 +844,20 @@ impl Poi {
|
||||
}
|
||||
/// The POI a block state is (`PoiTypes`): job site blocks, bed heads, bells.
|
||||
pub fn poi_at(w: &MobWorld, x: i32, y: i32, z: i32) -> Option<Poi> {
|
||||
let name = w.block_name(x, y, z);
|
||||
poi_of_state(w, w.world.block(x, y, z))
|
||||
}
|
||||
/// The POI a block state is, if any (`PoiTypes.forState`).
|
||||
fn poi_of_state(w: &MobWorld, state: horizon_world::registry::BlockStateId) -> Option<Poi> {
|
||||
let name = &*w.facts.get(state).name;
|
||||
if name == "minecraft:bell" {
|
||||
return Some(Poi::Meeting);
|
||||
}
|
||||
if name.ends_with("_bed") {
|
||||
return (w.prop(x, y, z, "part") == Some("head")).then_some(Poi::Home);
|
||||
let part = w
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("part"));
|
||||
return (part.map(String::as_str) == Some("head")).then_some(Poi::Home);
|
||||
}
|
||||
super::villager::job_site_profession(name).map(Poi::Job)
|
||||
}
|
||||
@@ -920,22 +929,28 @@ fn pois_in_range(
|
||||
let chunks = radius.div_euclid(16) + 1;
|
||||
let y0 = (c[1] - radius).max(crate::chunk::MIN_Y);
|
||||
let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1);
|
||||
let poi = poi_states(w.facts);
|
||||
// The POI each block state is, worked out once per search, and the
|
||||
// sections whose palette holds none skipped whole, as PoiManager only
|
||||
// visits sections with records: the same positions in the same order,
|
||||
// without reading and naming every block of the sphere.
|
||||
let mut kinds: HashMap<u32, Option<Poi>> = HashMap::new();
|
||||
let mut kind = |state: u32| {
|
||||
*kinds
|
||||
.entry(state)
|
||||
.or_insert_with(|| poi_of_state(w, horizon_world::registry::BlockStateId(state)))
|
||||
};
|
||||
for qz in cz - chunks..=cz + chunks {
|
||||
for qx in cx - chunks..=cx + chunks {
|
||||
let Some(chunk) = w.world.chunks.get(&(qx, qz)) else {
|
||||
continue;
|
||||
};
|
||||
// Sections whose palette holds no bell, bed or job site have no
|
||||
// POI: skip them whole (PoiManager indexes POIs instead).
|
||||
let mut may_hold = [false; crate::chunk::SECTIONS];
|
||||
for (slot, section) in may_hold.iter_mut().zip(&chunk.sections) {
|
||||
*slot = section
|
||||
.blocks
|
||||
.maybe_has(|id| poi.get(id as usize).copied().unwrap_or(true));
|
||||
}
|
||||
let holds: Vec<bool> = chunk
|
||||
.sections
|
||||
.iter()
|
||||
.map(|s| s.blocks.maybe_has(|v| kind(v).is_some()))
|
||||
.collect();
|
||||
for y in y0..=y1 {
|
||||
if !may_hold[((y - crate::chunk::MIN_Y) >> 4) as usize] {
|
||||
if !holds[((y - crate::chunk::MIN_Y) >> 4) as usize] {
|
||||
continue;
|
||||
}
|
||||
for z in qz * 16..qz * 16 + 16 {
|
||||
@@ -949,11 +964,11 @@ fn pois_in_range(
|
||||
if d > r2 {
|
||||
continue;
|
||||
}
|
||||
let state = w.world.block(x, y, z);
|
||||
let state = chunk.block(x & 15, y, z & 15);
|
||||
if w.facts.is_air(state) {
|
||||
continue;
|
||||
}
|
||||
let Some(poi) = poi_at(w, x, y, z) else {
|
||||
let Some(poi) = kind(state.0) else {
|
||||
continue;
|
||||
};
|
||||
if !poi_matches(m, f, poi) {
|
||||
@@ -978,28 +993,6 @@ fn pois_in_range(
|
||||
});
|
||||
found
|
||||
}
|
||||
/// Which block states `poi_at` can find a POI in, by state id.
|
||||
fn poi_states(facts: &crate::blocks::BlockFacts) -> std::sync::Arc<Vec<bool>> {
|
||||
static TABLE: std::sync::Mutex<Option<std::sync::Arc<Vec<bool>>>> = std::sync::Mutex::new(None);
|
||||
let mut table = TABLE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(t) = table.as_ref().filter(|t| t.len() == facts.states.len()) {
|
||||
return t.clone();
|
||||
}
|
||||
let t: std::sync::Arc<Vec<bool>> = std::sync::Arc::new(
|
||||
facts
|
||||
.states
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let name = &*f.name;
|
||||
name == "minecraft:bell"
|
||||
|| name.ends_with("_bed")
|
||||
|| super::villager::job_site_profession(name).is_some()
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
*table = Some(t.clone());
|
||||
t
|
||||
}
|
||||
/// `PoiManager.exists(pos, predicate)`.
|
||||
fn poi_exists(m: &Mob, w: &MobWorld, p: [i32; 3], f: PoiFilter) -> bool {
|
||||
poi_at(w, p[0], p[1], p[2]).is_some_and(|poi| poi_matches(m, f, poi))
|
||||
|
||||
@@ -445,6 +445,17 @@ impl SoundEngine {
|
||||
self.instances.remove(&id);
|
||||
}
|
||||
}
|
||||
/// Table sizes, for soak tests watching what the engine holds.
|
||||
pub fn census(&self) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"instances": self.instances.len(),
|
||||
"playing": self.instance_to_channel.len(),
|
||||
"handles": self.handles.len(),
|
||||
"ticking": self.ticking.len(),
|
||||
"queued": self.queued.len(),
|
||||
"used": self.used,
|
||||
})
|
||||
}
|
||||
pub fn instance(&self, id: InstanceId) -> Option<&SoundInstance> {
|
||||
self.instances.get(&id)
|
||||
}
|
||||
|
||||
@@ -359,20 +359,24 @@ impl Streaming {
|
||||
}
|
||||
Done::Generated(mut chunk) => {
|
||||
let key = (chunk.x, chunk.z);
|
||||
world
|
||||
.block_entities
|
||||
.extend(std::mem::take(&mut chunk.block_entities));
|
||||
world
|
||||
.block_names
|
||||
.extend(std::mem::take(&mut chunk.block_names));
|
||||
let entities = std::mem::take(&mut chunk.entities);
|
||||
if !entities.is_empty() {
|
||||
world.loaded_entities.push(((chunk.x, chunk.z), entities));
|
||||
}
|
||||
self.generating.remove(&key);
|
||||
self.finishing.remove(&key);
|
||||
self.decorated.insert(key);
|
||||
// A column that finished after the player moved away is
|
||||
// dropped whole: its block entities and saved entities
|
||||
// too, or they would stay in the world (and the entities
|
||||
// spawn again, duplicated, when the column loads later).
|
||||
if self.in_range(key.0, key.1, 2) || self.near_finished(key.0, key.1, 1) {
|
||||
world
|
||||
.block_entities
|
||||
.extend(std::mem::take(&mut chunk.block_entities));
|
||||
world
|
||||
.block_names
|
||||
.extend(std::mem::take(&mut chunk.block_names));
|
||||
let entities = std::mem::take(&mut chunk.entities);
|
||||
if !entities.is_empty() {
|
||||
world.loaded_entities.push(((chunk.x, chunk.z), entities));
|
||||
}
|
||||
self.generated_total += 1;
|
||||
// A chunk saved with its light needs no light job; its
|
||||
// unlit neighbours still light themselves from it.
|
||||
@@ -425,6 +429,12 @@ impl Streaming {
|
||||
if self.meshing.get(&(x, sy, z)) != Some(&seq) {
|
||||
continue;
|
||||
}
|
||||
// Its column unloaded while it was meshed: nothing would
|
||||
// ever remove the uploaded section.
|
||||
if !world.chunks.contains_key(&(x, z)) {
|
||||
self.meshing.remove(&(x, sy, z));
|
||||
continue;
|
||||
}
|
||||
self.meshing.remove(&(x, sy, z));
|
||||
self.meshed_total += 1;
|
||||
uploads.push(((x, sy, z), mesh));
|
||||
@@ -450,6 +460,13 @@ impl Streaming {
|
||||
}
|
||||
self.lit.remove(key);
|
||||
self.meshed.remove(key);
|
||||
self.lighting.remove(key);
|
||||
self.light_snapshots.remove(key);
|
||||
}
|
||||
if !far.is_empty() {
|
||||
let far: HashSet<(i32, i32)> = far.iter().copied().collect();
|
||||
self.meshing.retain(|k, _| !far.contains(&(k.0, k.2)));
|
||||
world.dirty_sections.retain(|k| !far.contains(&(k.0, k.2)));
|
||||
}
|
||||
// Drop far proto chunks that are not checked out.
|
||||
let areas: Vec<((i32, i32), i64)> =
|
||||
|
||||
@@ -55,6 +55,15 @@ Worlds autosave every 6000 ticks (5 minutes), when chunks unload and on quit.
|
||||
On headless Linux use `vscreen start ./target/release/horizon-client` and
|
||||
`vscreen shot`.
|
||||
|
||||
Sound: the game prints the output it opened (`Horizon: audio output ...`) or
|
||||
why it has none (`Horizon: no sound: ...`). It opens none with
|
||||
`HORIZON_NO_AUDIO` set, nor on a `vscreen`, where tests run beside someone
|
||||
listening; `HORIZON_AUDIO=1` opens it there anyway, so send it to a null sink
|
||||
(`PIPEWIRE_PROPS='{ target.object=<sink> node.dont-fallback=true }'`). Don't
|
||||
mute a test run's stream in the mixer: PipeWire remembers the mute for every
|
||||
later `horizon-client`. The launcher starts the game as "Horizon" for that
|
||||
reason.
|
||||
|
||||
### Drive the game from scripts (`horizon-ctl`)
|
||||
|
||||
`--control` opens a local Unix socket (`$XDG_RUNTIME_DIR/horizon-control.sock`,
|
||||
|
||||
Generated
+1
-1
@@ -2565,7 +2565,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "horizon-launcher"
|
||||
version = "0.1.1"
|
||||
version = "0.1.2"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"dirs 5.0.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "horizon-launcher"
|
||||
version = "0.1.1"
|
||||
version = "0.1.2"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
description = "Downloads, prepares and starts Horizon builds"
|
||||
|
||||
+20
-8
@@ -17,16 +17,23 @@ The opening, then Play ([clip](docs/opening.webm)):
|
||||
- **Play**: prepares resources as `PLAY.txt` describes (your launcher's 26.3 install, the
|
||||
26.3 server jar from that version's own json, Python 3.10+ and Java 25), then starts the
|
||||
client, or a server (`--dedicated --nogui`) in a folder you choose, with a live console.
|
||||
- **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors.
|
||||
- **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. A quiet "Join Discord" link sits in the sidebar footer.
|
||||
- **What's next**: the README's roadmap, from main.
|
||||
|
||||
Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux,
|
||||
`~/Library/Application Support/horizon-launcher` on macOS, `%APPDATA%\horizon-launcher` on
|
||||
Windows): `versions/<tag>/`, `server-jars/`, `server/` and `settings.json`.
|
||||
|
||||
- **Settings**: install new Horizon versions automatically (off by default; the selected
|
||||
version only moves to the new one if you were on the newest), the opening animation, and the
|
||||
launcher's own version and update state.
|
||||
- **Settings**: install new Horizon versions automatically (on unless you turn it off; the
|
||||
selected version only moves to the new one if you were on the newest), the opening animation,
|
||||
the game's menu style, and the launcher's own version and update state.
|
||||
- **Menu style**: Horizon's own menus or Classic (vanilla's screens). Classic has no way back
|
||||
inside the game, so the launcher is where you return to Horizon's. It is the `menuStyle:` line
|
||||
of `horizon.txt` in the game's home folder (`HORIZON_HOME`, else `horizon` in the data
|
||||
directory), which the game reads when it starts.
|
||||
- **Links**: the Discord invite and the Sponsors page come from `launcher/links.json` on main
|
||||
(`{"discord": "...", "sponsor": "..."}`), so they change without a launcher release. Offline,
|
||||
the launcher uses the same values built in; an empty address hides its button.
|
||||
|
||||
## Updates
|
||||
|
||||
@@ -56,10 +63,12 @@ The same binary is a command-line tool; without a subcommand it opens the window
|
||||
horizon-launcher server [--dir <dir>] [--version <tag>] [--accept-eula]
|
||||
horizon-launcher notes [<tag>] patch notes as plain text
|
||||
horizon-launcher next the roadmap
|
||||
horizon-launcher links the Discord and sponsor links
|
||||
horizon-launcher menu-style [horizon|classic] show or set the game's menu style
|
||||
horizon-launcher update [--check] Horizon and the launcher
|
||||
|
||||
`--json` prints JSON where there is something to report (`versions`, `install`, `notes`,
|
||||
`next`, `update --check`). Errors go to stderr with exit code 1. `server` runs in the terminal,
|
||||
`next`, `links`, `menu-style`, `update --check`). Errors go to stderr with exit code 1. `server` runs in the terminal,
|
||||
so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for
|
||||
scripts and tests).
|
||||
|
||||
@@ -71,7 +80,7 @@ scripts and tests).
|
||||
|
||||
(with the full path to the binary if it is not on your `PATH`). Its tools: `list_versions`,
|
||||
`install_version`, `remove_version`, `prepare_resources`, `launch_client`, `start_server`,
|
||||
`server_command`, `server_log`, `stop_server`, `patch_notes`, `roadmap` and `check_updates`.
|
||||
`server_command`, `server_log`, `stop_server`, `patch_notes`, `roadmap`, `links`, `menu_style` and `check_updates`.
|
||||
A server started through MCP stops (cleanly, with `stop`) when the session ends. Starting one
|
||||
needs `accept_eula`, which an agent should only pass with the player's consent.
|
||||
|
||||
@@ -83,9 +92,12 @@ The window, the command line and the MCP server all call the same core, `src/bac
|
||||
|
||||
On NixOS, `nix-shell` in this folder provides the libraries GPUI links to (Wayland, X11,
|
||||
xkbcommon, Vulkan, fontconfig). macOS needs Xcode's command line tools. The `launcher`
|
||||
workflow builds all three platforms on every push to the `launcher` branch.
|
||||
workflow builds all three platforms on every push to the `launcher` branch (or a
|
||||
`launcher-*` one), then installs the latest Horizon into a temporary folder and checks that the
|
||||
client starts (`--help`) and that the binaries import only system libraries (Windows).
|
||||
|
||||
cargo test --lib # tag separation, version order, update selection, notes as text
|
||||
cargo test --lib # tag separation, version order, update selection, notes as text,
|
||||
# the auto-install default, the links fallback, the menu style file
|
||||
|
||||
Geist, Geist Mono and Instrument Serif (SIL Open Font License, `crates/horizon-theme/fonts/OFL-*.txt`, shared with the game's menus) are
|
||||
bundled so the type is the same on every platform.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 498 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 408 KiB |
@@ -0,0 +1 @@
|
||||
{"discord": "https://discord.gg/HcTeMZxe5E", "sponsor": "https://github.com/sponsors/ludovic111"}
|
||||
+167
-6
@@ -9,7 +9,6 @@ use std::sync::mpsc::Sender;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub const REPO: &str = "ludovic111/horizon";
|
||||
pub const SPONSOR_URL: &str = "https://github.com/sponsors/ludovic111";
|
||||
pub const README_URL: &str = "https://github.com/ludovic111/horizon/blob/main/launcher/README.md";
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
/// Launcher releases are tagged `launcher-vX.Y.Z`; Horizon's own are `vYYYY.MM.DD`.
|
||||
@@ -163,6 +162,43 @@ pub fn roadmap() -> Result<String, String> {
|
||||
Err("The README has no roadmap section yet.".into())
|
||||
}
|
||||
|
||||
/// The community and sponsor links, from `launcher/links.json` on main, so they can change
|
||||
/// without a launcher release. An empty address hides its button.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
|
||||
pub struct Links {
|
||||
pub discord: String,
|
||||
pub sponsor: String,
|
||||
}
|
||||
|
||||
impl Default for Links {
|
||||
/// What the launcher uses until (or unless) it can read links.json.
|
||||
fn default() -> Self {
|
||||
Self { discord: "https://discord.gg/HcTeMZxe5E".into(), sponsor: "https://github.com/sponsors/ludovic111".into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Links {
|
||||
/// Reads links.json. A key that is missing keeps its default, an empty one hides the link,
|
||||
/// and text that is not a JSON object gives the defaults.
|
||||
pub fn parse(text: &str) -> Self {
|
||||
let mut links = Self::default();
|
||||
if let Ok(serde_json::Value::Object(map)) = serde_json::from_str(text) {
|
||||
for (key, slot) in [("discord", &mut links.discord), ("sponsor", &mut links.sponsor)] {
|
||||
if let Some(url) = map.get(key).and_then(|v| v.as_str()) {
|
||||
*slot = url.trim().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
links
|
||||
}
|
||||
}
|
||||
|
||||
/// The links from main, or the built-in ones when offline.
|
||||
pub fn links() -> Links {
|
||||
let url = format!("https://raw.githubusercontent.com/{REPO}/main/launcher/links.json");
|
||||
get(&url).ok().and_then(|r| r.into_string().ok()).map_or_else(Links::default, |text| Links::parse(&text))
|
||||
}
|
||||
|
||||
/// The launcher's data folder; `HORIZON_LAUNCHER_HOME` overrides it (for tests and scripts).
|
||||
pub fn data_dir() -> PathBuf {
|
||||
if let Some(home) = std::env::var_os("HORIZON_LAUNCHER_HOME").filter(|h| !h.is_empty()) {
|
||||
@@ -346,11 +382,72 @@ pub fn game_home() -> PathBuf {
|
||||
dirs::data_dir().unwrap_or_else(std::env::temp_dir).join("horizon")
|
||||
}
|
||||
|
||||
/// Which drawing the game's menus use. Classic is vanilla's own screens, which have no way to
|
||||
/// switch back, so the launcher is where the player returns to Horizon's.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MenuStyle {
|
||||
Horizon,
|
||||
Classic,
|
||||
}
|
||||
|
||||
impl MenuStyle {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
MenuStyle::Horizon => "horizon",
|
||||
MenuStyle::Classic => "classic",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
match name {
|
||||
"horizon" => Some(MenuStyle::Horizon),
|
||||
"classic" => Some(MenuStyle::Classic),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The style `horizon.txt` holds: Horizon unless it has the line `menuStyle:classic`, as the
|
||||
/// game reads it (crates/horizon-client/src/ui_theme.rs).
|
||||
fn from_file(text: &str) -> Self {
|
||||
if text.lines().any(|l| l.trim() == "menuStyle:classic") {
|
||||
MenuStyle::Classic
|
||||
} else {
|
||||
MenuStyle::Horizon
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` with its `menuStyle:` line set to this style and every other line kept.
|
||||
fn into_file(self, text: &str) -> String {
|
||||
let mut out: Vec<String> = text.lines().filter(|l| !l.trim().starts_with("menuStyle:")).map(String::from).collect();
|
||||
out.insert(0, format!("menuStyle:{}", self.name()));
|
||||
out.join("\n") + "\n"
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu style saved in the game home's `horizon.txt` (Horizon when there is none).
|
||||
pub fn menu_style() -> MenuStyle {
|
||||
MenuStyle::from_file(&fs::read_to_string(game_home().join("horizon.txt")).unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn set_menu_style(style: MenuStyle) -> Result<(), String> {
|
||||
let home = game_home();
|
||||
fs::create_dir_all(&home).map_err(|e| e.to_string())?;
|
||||
let file = home.join("horizon.txt");
|
||||
let text = style.into_file(&fs::read_to_string(&file).unwrap_or_default());
|
||||
fs::write(file, text).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn client_command(tag: &str) -> Command {
|
||||
let home = game_home();
|
||||
let _ = fs::create_dir_all(&home);
|
||||
let mut cmd = Command::new(version_dir(tag).join(CLIENT));
|
||||
cmd.current_dir(home).arg("--resources").arg(resources(tag));
|
||||
// PipeWire remembers volume and mute per application name. The game's own name is
|
||||
// "PipeWire ALSA [horizon-client]", shared with development and test runs, where
|
||||
// muting it once left every later game silent: played from here it is "Horizon".
|
||||
if std::env::var_os("PIPEWIRE_PROPS").is_none() {
|
||||
cmd.env("PIPEWIRE_PROPS", "{ application.name = \"Horizon\" media.role = \"Game\" }");
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
@@ -701,6 +798,7 @@ pub enum Job {
|
||||
pub enum Msg {
|
||||
Releases(Result<Vec<Release>, String>),
|
||||
Roadmap(Result<String, String>),
|
||||
Links(Links),
|
||||
Progress(String, f32),
|
||||
Installed(String, Result<(), String>),
|
||||
Line(Job, String),
|
||||
@@ -774,8 +872,10 @@ pub struct Settings {
|
||||
pub selected: Option<String>,
|
||||
pub minecraft_dir: Option<PathBuf>,
|
||||
pub server_dir: Option<PathBuf>,
|
||||
/// Unset means on: only a player who turned it off has `false` here. 0.1.1 wrote its
|
||||
/// `auto_install` (off by default) for everyone, so this is a new key and that one is ignored.
|
||||
#[serde(default)]
|
||||
pub auto_install: bool,
|
||||
pub install_new_versions: Option<bool>,
|
||||
/// Off by default, so the opening animation shows unless the player turns it off.
|
||||
#[serde(default)]
|
||||
pub skip_opening: bool,
|
||||
@@ -783,10 +883,14 @@ pub struct Settings {
|
||||
|
||||
impl Settings {
|
||||
pub fn load() -> Self {
|
||||
fs::read_to_string(data_dir().join("settings.json"))
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default()
|
||||
Self::parse(&fs::read_to_string(data_dir().join("settings.json")).unwrap_or_default())
|
||||
}
|
||||
pub fn parse(text: &str) -> Self {
|
||||
serde_json::from_str(text).unwrap_or_default()
|
||||
}
|
||||
/// Whether new Horizon versions are installed automatically.
|
||||
pub fn auto_install(&self) -> bool {
|
||||
self.install_new_versions.unwrap_or(true)
|
||||
}
|
||||
pub fn save(&self) {
|
||||
let _ = fs::create_dir_all(data_dir());
|
||||
@@ -799,6 +903,16 @@ mod tests {
|
||||
use super::*;
|
||||
use std::cmp::Ordering::*;
|
||||
|
||||
#[test]
|
||||
fn the_game_plays_under_its_own_audio_stream_name() {
|
||||
if std::env::var_os("PIPEWIRE_PROPS").is_some() {
|
||||
return;
|
||||
}
|
||||
let cmd = client_command("v2026.10.13");
|
||||
let props = cmd.get_envs().find(|(k, _)| *k == "PIPEWIRE_PROPS").and_then(|(_, v)| v);
|
||||
assert!(props.is_some_and(|v| v.to_string_lossy().contains("application.name = \"Horizon\"")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tags_never_mix() {
|
||||
assert!(is_game_tag("v2026.10.13"));
|
||||
@@ -843,6 +957,53 @@ mod tests {
|
||||
assert!(select_after_update(None, &installed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_versions_install_automatically_unless_turned_off() {
|
||||
// No settings file, an old one that never mentioned it, and 0.1.1's default `false`.
|
||||
assert!(Settings::parse("").auto_install());
|
||||
assert!(Settings::parse("{}").auto_install());
|
||||
assert!(Settings::parse(r#"{"selected": "v2026.10.13", "auto_install": false}"#).auto_install());
|
||||
assert!(Settings::parse(r#"{"install_new_versions": true}"#).auto_install());
|
||||
assert!(!Settings::parse(r#"{"install_new_versions": false}"#).auto_install());
|
||||
// Saving after the player turned it off keeps it off.
|
||||
let off = Settings { install_new_versions: Some(false), ..Settings::default() };
|
||||
assert!(!Settings::parse(&serde_json::to_string(&off).unwrap()).auto_install());
|
||||
// The selection rule is unchanged: the new version is selected only from the newest.
|
||||
let installed = ["v2026.10.12".to_string(), "v2026.10.1".to_string()];
|
||||
assert!(select_after_update(Some("v2026.10.12"), &installed));
|
||||
assert!(!select_after_update(Some("v2026.10.1"), &installed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_fall_back_to_the_built_in_ones() {
|
||||
let defaults = Links::default();
|
||||
assert_eq!(defaults.discord, "https://discord.gg/HcTeMZxe5E");
|
||||
assert_eq!(defaults.sponsor, "https://github.com/sponsors/ludovic111");
|
||||
// The file on main says the same thing as the defaults.
|
||||
let file = Links::parse(r#"{"discord": "https://discord.gg/HcTeMZxe5E", "sponsor": "https://github.com/sponsors/ludovic111"}"#);
|
||||
assert_eq!(file, defaults);
|
||||
// Unreadable or missing, offline included: the defaults.
|
||||
assert_eq!(Links::parse(""), defaults);
|
||||
assert_eq!(Links::parse("<html>404</html>"), defaults);
|
||||
assert_eq!(Links::parse("[1]"), defaults);
|
||||
assert_eq!(Links::parse(r#"{"discord": 5}"#), defaults);
|
||||
// A key that is missing keeps its default; a new address replaces it; empty hides it.
|
||||
assert_eq!(Links::parse(r#"{"discord": "https://x.y/z"}"#), Links { discord: "https://x.y/z".into(), ..defaults.clone() });
|
||||
assert_eq!(Links::parse(r#"{"discord": "", "sponsor": " "}"#), Links { discord: String::new(), sponsor: String::new() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_style_file_matches_the_games() {
|
||||
assert_eq!(MenuStyle::from_file(""), MenuStyle::Horizon);
|
||||
assert_eq!(MenuStyle::from_file("menuStyle:horizon\n"), MenuStyle::Horizon);
|
||||
assert_eq!(MenuStyle::from_file("menuStyle:classic\n"), MenuStyle::Classic);
|
||||
assert_eq!(MenuStyle::from_file("other:1\nmenuStyle:classic\n"), MenuStyle::Classic);
|
||||
assert_eq!(MenuStyle::Classic.into_file(""), "menuStyle:classic\n");
|
||||
assert_eq!(MenuStyle::Horizon.into_file("menuStyle:classic\nother:1\n"), "menuStyle:horizon\nother:1\n");
|
||||
assert_eq!(MenuStyle::parse("classic"), Some(MenuStyle::Classic));
|
||||
assert_eq!(MenuStyle::parse("vanilla"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_notes() {
|
||||
let text = markdown_to_text("# Title\n\nSome *words* and [a link](https://x.y).\n\n- one\n- two\n");
|
||||
|
||||
@@ -57,6 +57,14 @@ enum Cmd {
|
||||
Notes { tag: Option<String> },
|
||||
/// Show the roadmap
|
||||
Next,
|
||||
/// Show the Discord and sponsor links
|
||||
Links,
|
||||
/// Show or set the game's menu style (classic is vanilla's own screens)
|
||||
MenuStyle {
|
||||
/// Omit to show the current style
|
||||
#[arg(value_parser = ["horizon", "classic"])]
|
||||
style: Option<String>,
|
||||
},
|
||||
/// Look for a newer Horizon release and launcher, and install them
|
||||
Update {
|
||||
/// Only report what is available
|
||||
@@ -198,6 +206,27 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
print!("{}", backend::markdown_to_text(&roadmap));
|
||||
}
|
||||
}
|
||||
Cmd::Links => {
|
||||
let links = backend::links();
|
||||
if as_json {
|
||||
json(serde_json::to_value(&links).unwrap());
|
||||
} else {
|
||||
for (name, url) in [("Discord", &links.discord), ("Sponsor", &links.sponsor)] {
|
||||
println!("{name:<8} {}", if url.is_empty() { "(none)" } else { url });
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::MenuStyle { style } => {
|
||||
if let Some(style) = style.as_deref().and_then(backend::MenuStyle::parse) {
|
||||
backend::set_menu_style(style)?;
|
||||
}
|
||||
let style = backend::menu_style().name();
|
||||
if as_json {
|
||||
json(serde_json::json!({ "menu_style": style }));
|
||||
} else {
|
||||
println!("Menu style: {style}");
|
||||
}
|
||||
}
|
||||
Cmd::Update { check } => update(check, as_json)?,
|
||||
Cmd::Mcp => unreachable!(),
|
||||
}
|
||||
|
||||
+77
-11
@@ -124,6 +124,9 @@ struct Launcher {
|
||||
confirm_remove: Option<String>,
|
||||
picker_open: bool,
|
||||
settings: Settings,
|
||||
/// The Discord and sponsor links: built in until links.json on main has been read.
|
||||
links: backend::Links,
|
||||
menu_style: backend::MenuStyle,
|
||||
preparing: bool,
|
||||
prepare_log: VecDeque<String>,
|
||||
prepare_error: Option<String>,
|
||||
@@ -192,6 +195,8 @@ impl Launcher {
|
||||
confirm_remove: None,
|
||||
picker_open: false,
|
||||
settings,
|
||||
links: backend::Links::default(),
|
||||
menu_style: backend::menu_style(),
|
||||
preparing: false,
|
||||
prepare_log: VecDeque::new(),
|
||||
prepare_error: None,
|
||||
@@ -210,6 +215,7 @@ impl Launcher {
|
||||
};
|
||||
this.fetch_releases();
|
||||
this.fetch_roadmap();
|
||||
this.fetch_links();
|
||||
this.check_updates();
|
||||
this
|
||||
}
|
||||
@@ -262,6 +268,11 @@ impl Launcher {
|
||||
std::thread::spawn(move || tx.send(Msg::Releases(backend::releases())));
|
||||
}
|
||||
|
||||
fn fetch_links(&self) {
|
||||
let tx = self.tx.clone();
|
||||
std::thread::spawn(move || tx.send(Msg::Links(backend::links())));
|
||||
}
|
||||
|
||||
fn fetch_roadmap(&mut self) {
|
||||
self.roadmap = Load::Loading;
|
||||
let tx = self.tx.clone();
|
||||
@@ -275,6 +286,7 @@ impl Launcher {
|
||||
match msg {
|
||||
Msg::Releases(r) => self.releases = r.map_or_else(Load::Failed, Load::Ready),
|
||||
Msg::Roadmap(r) => self.roadmap = r.map_or_else(Load::Failed, Load::Ready),
|
||||
Msg::Links(links) => self.links = links,
|
||||
Msg::Progress(tag, p) => {
|
||||
self.bar = (self.bar.1, p);
|
||||
self.installing = Some((tag, p));
|
||||
@@ -300,7 +312,7 @@ impl Launcher {
|
||||
Msg::Updates(Ok(updates)) => {
|
||||
self.update_error = None;
|
||||
self.updates = updates;
|
||||
if self.settings.auto_install {
|
||||
if self.settings.auto_install() {
|
||||
self.install_update();
|
||||
}
|
||||
if let Some(release) = self.updates.launcher.clone() {
|
||||
@@ -752,6 +764,17 @@ impl Launcher {
|
||||
),
|
||||
_ => div().child(format!("Launcher {}", backend::VERSION)),
|
||||
};
|
||||
let discord = (!self.links.discord.is_empty()).then(|| {
|
||||
let url = self.links.discord.clone();
|
||||
div()
|
||||
.id("discord")
|
||||
.mb(px(4.))
|
||||
.text_color(t.muted)
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.text_color(t.text))
|
||||
.child("Join Discord")
|
||||
.on_click(move |_, _, cx| cx.open_url(&url))
|
||||
});
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
@@ -774,7 +797,7 @@ impl Launcher {
|
||||
)
|
||||
.child(nav)
|
||||
.child(div().flex_1())
|
||||
.child(div().px(px(10.)).text_size(px(theme::SMALL)).text_color(t.faint).child(footer))
|
||||
.child(div().px(px(10.)).text_size(px(theme::SMALL)).text_color(t.faint).children(discord).child(footer))
|
||||
}
|
||||
|
||||
fn segmented(&self, cx: &mut Context<Self>) -> Div {
|
||||
@@ -1134,11 +1157,11 @@ impl Launcher {
|
||||
|
||||
fn settings_page(&mut self, cx: &mut Context<Self>) -> Div {
|
||||
let t = self.theme;
|
||||
let toggle = switch("auto-install", self.settings.auto_install, &t).on_click(cx.listener(
|
||||
let toggle = switch("auto-install", self.settings.auto_install(), &t).on_click(cx.listener(
|
||||
|this, _: &ClickEvent, _, cx| {
|
||||
this.settings.auto_install = !this.settings.auto_install;
|
||||
this.settings.install_new_versions = Some(!this.settings.auto_install());
|
||||
this.settings.save();
|
||||
if this.settings.auto_install {
|
||||
if this.settings.auto_install() {
|
||||
this.install_update();
|
||||
}
|
||||
cx.notify();
|
||||
@@ -1151,6 +1174,46 @@ impl Launcher {
|
||||
cx.notify();
|
||||
},
|
||||
));
|
||||
let menus = div()
|
||||
.id("menu-style")
|
||||
.flex()
|
||||
.flex_none()
|
||||
.p(px(2.))
|
||||
.gap(px(2.))
|
||||
.rounded(px(theme::RADIUS_GROUP))
|
||||
.bg(t.raised)
|
||||
.border_1()
|
||||
.border_color(t.border)
|
||||
.children([(backend::MenuStyle::Horizon, "Horizon"), (backend::MenuStyle::Classic, "Classic")].map(
|
||||
|(style, label)| {
|
||||
let active = self.menu_style == style;
|
||||
div()
|
||||
.id(label)
|
||||
.flex()
|
||||
.items_center()
|
||||
.h(px(theme::SEGMENT))
|
||||
.px(px(14.))
|
||||
.rounded(px(theme::RADIUS_SEGMENT))
|
||||
.text_size(px(13.))
|
||||
.cursor_pointer()
|
||||
.when(active, |d| {
|
||||
d.bg(t.bg).border_1().border_color(t.border).text_color(t.text).font_weight(FontWeight::MEDIUM)
|
||||
})
|
||||
.when(!active, |d| d.text_color(t.muted).hover(move |s| s.text_color(t.text)))
|
||||
.child(label)
|
||||
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
|
||||
if backend::set_menu_style(style).is_ok() {
|
||||
this.menu_style = style;
|
||||
}
|
||||
cx.notify();
|
||||
}))
|
||||
},
|
||||
));
|
||||
let menu_note = div().flex().flex_col().gap(px(2.)).child("Menu style").child(
|
||||
div().text_size(px(theme::SMALL)).text_color(t.muted).child(
|
||||
"Classic is vanilla's own screens, with no way back inside the game: switch back here. Applies the next time the game starts.",
|
||||
),
|
||||
);
|
||||
let auto = div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
@@ -1225,7 +1288,7 @@ impl Launcher {
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(24.))
|
||||
.child(page_header("Settings", "Updates, and the launcher itself.", &t))
|
||||
.child(page_header("Settings", "Updates, menus, and the launcher itself.", &t))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
@@ -1235,6 +1298,8 @@ impl Launcher {
|
||||
.child(divider(&t))
|
||||
.child(row("Opening", div().child("Show opening animation"), Some(opening), &t))
|
||||
.child(divider(&t))
|
||||
.child(row("Game menus", menu_note, Some(menus), &t))
|
||||
.child(divider(&t))
|
||||
.child(row("Horizon", horizon, horizon_action, &t))
|
||||
.child(divider(&t))
|
||||
.child(row("Launcher", div().child(launcher), launcher_action, &t))
|
||||
@@ -1484,7 +1549,7 @@ impl Launcher {
|
||||
|
||||
fn notes_page(&mut self, cx: &mut Context<Self>) -> Div {
|
||||
let t = self.theme;
|
||||
let sponsor = div()
|
||||
let sponsor = (!self.links.sponsor.is_empty()).then(|| div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
@@ -1506,15 +1571,16 @@ impl Launcher {
|
||||
.child("Horizon is built in the open. Sponsors fund the next release."),
|
||||
),
|
||||
)
|
||||
.child(button("sponsor", "Sponsor on GitHub", Kind::Secondary, &t).on_click(cx.listener(
|
||||
|_, _: &ClickEvent, _, cx| cx.open_url(backend::SPONSOR_URL),
|
||||
)));
|
||||
.child(button("sponsor", "Sponsor on GitHub", Kind::Secondary, &t).on_click({
|
||||
let url = self.links.sponsor.clone();
|
||||
move |_: &ClickEvent, _, cx| cx.open_url(&url)
|
||||
})));
|
||||
let page = div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(24.))
|
||||
.child(page_header("Patch notes", "What changed in each release, newest first.", &t))
|
||||
.child(sponsor);
|
||||
.children(sponsor);
|
||||
let releases = match &self.releases {
|
||||
Load::Loading => return page.child(centered("Loading patch notes…", &t)),
|
||||
Load::Failed(e) => {
|
||||
|
||||
@@ -38,6 +38,9 @@ fn tools() -> Value {
|
||||
{ "name": "patch_notes", "description": "A release's patch notes as markdown.",
|
||||
"inputSchema": { "type": "object", "properties": { "tag": { "type": "string", "description": "Default: the newest release." } } } },
|
||||
{ "name": "roadmap", "description": "What's planned next for Horizon, from the README's roadmap.", "inputSchema": none },
|
||||
{ "name": "links", "description": "The Horizon community links: the Discord invite and the GitHub Sponsors page (an empty one is not offered).", "inputSchema": none },
|
||||
{ "name": "menu_style", "description": "Show or set the game's menu style. \"horizon\" is Horizon's own menus, \"classic\" is vanilla's screens, which have no way back inside the game. The game reads it when it starts.",
|
||||
"inputSchema": { "type": "object", "properties": { "style": { "type": "string", "enum": ["horizon", "classic"], "description": "Omit to show the current style." } } } },
|
||||
{ "name": "check_updates", "description": "Check GitHub for a Horizon release newer than every installed version, and for a newer launcher.", "inputSchema": none },
|
||||
])
|
||||
}
|
||||
@@ -136,6 +139,14 @@ impl Session {
|
||||
Ok(format!("# {} ({}, {})\n\n{}", if r.name.is_empty() { &r.tag } else { &r.name }, r.tag, r.date, r.body))
|
||||
}
|
||||
"roadmap" => backend::roadmap(),
|
||||
"links" => Ok(serde_json::to_string_pretty(&backend::links()).unwrap()),
|
||||
"menu_style" => {
|
||||
if let Some(name) = arg_str(args, "style") {
|
||||
let style = backend::MenuStyle::parse(name).ok_or("style is \"horizon\" or \"classic\"")?;
|
||||
backend::set_menu_style(style)?;
|
||||
}
|
||||
Ok(format!("Menu style: {}", backend::menu_style().name()))
|
||||
}
|
||||
"check_updates" => {
|
||||
let u = backend::check_updates()?;
|
||||
Ok(serde_json::to_string_pretty(&json!({
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail when a release binary needs a library its players may not have.
|
||||
|
||||
Windows .exe: every DLL in the import and delay-import tables must ship with
|
||||
Windows (no VCRUNTIME140.dll, vulkan-1.dll, ...): Vulkan and the like are
|
||||
loaded at run time, so a missing driver is an error message, not a dialog.
|
||||
Linux ELF: the loader must be the standard one (not a /nix/store path) and the
|
||||
needed libraries the ones every desktop distribution has.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# DLLs that are part of Windows 10 and 11. api-ms-win-* and ext-ms-win-* API
|
||||
# sets resolve inside Windows too.
|
||||
WINDOWS_SYSTEM = {
|
||||
"advapi32.dll", "bcrypt.dll", "bcryptprimitives.dll", "cfgmgr32.dll", "combase.dll",
|
||||
"comctl32.dll", "comdlg32.dll", "crypt32.dll", "d2d1.dll", "d3d11.dll", "d3d12.dll",
|
||||
"d3dcompiler_47.dll", "dbghelp.dll", "dcomp.dll", "dwmapi.dll", "dwrite.dll", "dxgi.dll",
|
||||
"gdi32.dll", "hid.dll", "icuuc.dll", "imm32.dll", "iphlpapi.dll", "kernel32.dll",
|
||||
"kernelbase.dll", "mfplat.dll", "mmdevapi.dll", "msvcrt.dll", "ncrypt.dll", "ntdll.dll",
|
||||
"ole32.dll", "oleaut32.dll", "opengl32.dll", "propsys.dll", "secur32.dll", "setupapi.dll",
|
||||
"shcore.dll", "shell32.dll", "shlwapi.dll", "ucrtbase.dll", "user32.dll", "userenv.dll",
|
||||
"uxtheme.dll", "version.dll", "winmm.dll", "ws2_32.dll", "xinput1_4.dll",
|
||||
}
|
||||
LINUX_LOADER = "/lib64/ld-linux-x86-64.so.2"
|
||||
LINUX_SYSTEM = {
|
||||
"libc.so.6", "libm.so.6", "libgcc_s.so.1", "libdl.so.2", "libpthread.so.0", "librt.so.1",
|
||||
"ld-linux-x86-64.so.2", "libasound.so.2",
|
||||
}
|
||||
|
||||
|
||||
def windows_allowed(name):
|
||||
name = name.lower()
|
||||
return name in WINDOWS_SYSTEM or name.startswith(("api-ms-win-", "ext-ms-win-"))
|
||||
|
||||
|
||||
def pe_imports(data):
|
||||
"""DLL names in a PE32+ file's import and delay-import tables."""
|
||||
pe = struct.unpack_from("<I", data, 0x3C)[0]
|
||||
if data[pe:pe + 4] != b"PE\0\0":
|
||||
raise ValueError("not a PE file")
|
||||
sections_count, optional_size = struct.unpack_from("<H12xH", data, pe + 6)
|
||||
optional = pe + 24
|
||||
magic = struct.unpack_from("<H", data, optional)[0]
|
||||
directories = optional + (112 if magic == 0x20B else 96)
|
||||
sections = [struct.unpack_from("<8xIIII", data, optional + optional_size + 40 * i)
|
||||
for i in range(sections_count)]
|
||||
|
||||
def offset(rva):
|
||||
for size, address, raw_size, raw in sections:
|
||||
if address <= rva < address + max(size, raw_size):
|
||||
return rva - address + raw
|
||||
raise ValueError(f"RVA {rva:#x} outside every section")
|
||||
|
||||
def name_at(rva):
|
||||
start = offset(rva)
|
||||
return data[start:data.index(b"\0", start)].decode("ascii")
|
||||
|
||||
names = []
|
||||
# Directory 1: imports (20-byte descriptors, name at +12); 13: delay imports (32 bytes, name at +4).
|
||||
for index, size, name_field in ((1, 20, 12), (13, 32, 4)):
|
||||
rva = struct.unpack_from("<I", data, directories + 8 * index)[0]
|
||||
if not rva:
|
||||
continue
|
||||
at = offset(rva)
|
||||
while any(data[at:at + size]):
|
||||
names.append(name_at(struct.unpack_from("<I", data, at + name_field)[0]))
|
||||
at += size
|
||||
return names
|
||||
|
||||
|
||||
def elf_needs(data):
|
||||
"""The interpreter and DT_NEEDED libraries of a little-endian ELF64 file."""
|
||||
if data[:4] != b"\x7fELF" or data[4] != 2:
|
||||
raise ValueError("not an ELF64 file")
|
||||
phoff, phentsize, phnum = struct.unpack_from("<Q", data, 32)[0], *struct.unpack_from("<HH", data, 54)
|
||||
interpreter, dynamic, loads = None, None, []
|
||||
for i in range(phnum):
|
||||
kind, _, offset, vaddr, _, filesz = struct.unpack_from("<IIQQQQ", data, phoff + i * phentsize)
|
||||
if kind == 3:
|
||||
interpreter = data[offset:offset + filesz].rstrip(b"\0").decode()
|
||||
elif kind == 2:
|
||||
dynamic = (offset, filesz)
|
||||
elif kind == 1:
|
||||
loads.append((vaddr, offset, filesz))
|
||||
|
||||
def file_offset(address):
|
||||
for vaddr, offset, size in loads:
|
||||
if vaddr <= address < vaddr + size:
|
||||
return address - vaddr + offset
|
||||
raise ValueError(f"address {address:#x} outside every segment")
|
||||
|
||||
entries = []
|
||||
if dynamic:
|
||||
for at in range(dynamic[0], dynamic[0] + dynamic[1], 16):
|
||||
tag, value = struct.unpack_from("<qQ", data, at)
|
||||
if tag == 0:
|
||||
break
|
||||
entries.append((tag, value))
|
||||
strtab = next((file_offset(v) for t, v in entries if t == 5), None)
|
||||
|
||||
def string(index):
|
||||
start = strtab + index
|
||||
return data[start:data.index(b"\0", start)].decode()
|
||||
|
||||
needed = [string(v) for t, v in entries if t == 1]
|
||||
runpath = [string(v) for t, v in entries if t in (15, 29)]
|
||||
return interpreter, needed, runpath
|
||||
|
||||
|
||||
def check(path):
|
||||
data = Path(path).read_bytes()
|
||||
problems = []
|
||||
if data[:2] == b"MZ":
|
||||
names = pe_imports(data)
|
||||
problems += [f"imports {n}, which Windows does not ship" for n in names if not windows_allowed(n)]
|
||||
summary = ", ".join(sorted(set(n.lower() for n in names)))
|
||||
else:
|
||||
interpreter, needed, runpath = elf_needs(data)
|
||||
if interpreter not in (None, LINUX_LOADER):
|
||||
problems.append(f"loader is {interpreter}, not {LINUX_LOADER}")
|
||||
problems += [f"needs {n}, which not every distribution has" for n in needed if n not in LINUX_SYSTEM]
|
||||
problems += [f"has a run path to {p}" for p in runpath if "/nix/store" in p]
|
||||
summary = f"{interpreter}; " + ", ".join(needed)
|
||||
print(f"{path}: {summary}")
|
||||
for problem in problems:
|
||||
print(f" {path} {problem}", file=sys.stderr)
|
||||
return not problems
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("binaries", nargs="+")
|
||||
args = parser.parse_args()
|
||||
ok = all([check(path) for path in args.binaries])
|
||||
sys.exit(0 if ok else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user