Merge origin/main into refactor/horizon-items

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 02:27:09 +01:00
58 changed files with 1758 additions and 166 deletions
+41 -1
View File
@@ -1,6 +1,46 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-client-core", "crates/horizon-command", "crates/horizon-items", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "crates/horizon-mod-sdk/examples/beacons", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask", "mods/official/recipes"]
members = [
"crates/horizon-core",
"crates/horizon-dualsense",
"crates/horizon-threads",
"crates/horizon-hdr",
"crates/horizon-world",
"crates/horizon-client",
"crates/horizon-client-core",
"crates/horizon-command",
"crates/horizon-items",
"crates/horizon-server-files",
"crates/horizon-server",
"crates/horizon-bots",
"crates/horizon-assets",
"crates/horizon-protocol",
"crates/horizon-theme",
"crates/horizon-prepare",
"crates/horizon-telemetry",
"crates/horizon-bench",
"crates/horizon-friends",
"crates/horizon-relay",
"crates/horizon-mod-sdk",
"crates/horizon-mods",
"crates/horizon-mods/tests/guest",
"crates/horizon-mods/tests/ui_guest",
"crates/cargo-horizon-mod",
"crates/horizon-port-pack",
"crates/horizon-shaders",
"crates/horizon-shader-api",
"crates/horizon-release-sign",
"crates/horizon-mod-sdk/examples/coords-hud",
"crates/horizon-mod-sdk/examples/predator-missile",
"crates/horizon-mod-sdk/examples/welcome",
"crates/horizon-mod-sdk/examples/beacons",
"mods/official/fps-overlay",
"mods/official/keystrokes",
"mods/official/minimap",
"mods/official/zoom",
"xtask",
"mods/official/recipes",
]
resolver = "2"
[workspace.package]
+12 -2
View File
@@ -375,7 +375,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 --width N, --height N Window size (default 1280 x 720)\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 --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\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 --width N, --height N Window size (default 1280 x 720)\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 --quickPlaySingleplayer WORLD Open this world of saves/ at start, only if it exists (vanilla's)\n --quickPlayMultiplayer HOST[:PORT] The same as --server (vanilla's name)\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 --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\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);
@@ -430,6 +430,16 @@ impl Options {
"--width" => o.window_size[0] = value.parse::<u32>()?.max(1),
"--height" => o.window_size[1] = value.parse::<u32>()?.max(1),
"--world" => o.world = Some(value),
// Vanilla's quick play (Main, QuickPlay.joinSingleplayerWorld): only a
// world that exists opens; else the title screen. --world also creates one.
"--quickPlaySingleplayer" => {
let folder = std::env::current_dir()?.join("saves").join(&value);
if folder.join("level.dat").is_file() {
o.world = Some(value);
} else {
eprintln!("Quick play: there is no world {value} in saves/");
}
}
"--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?),
"--benchmark" => {
if horizon_client::benchmark::scenes(&value).is_none() {
@@ -440,7 +450,7 @@ impl Options {
}
o.benchmark = Some(value);
}
"--server" => o.server = Some(value),
"--server" | "--quickPlayMultiplayer" => o.server = Some(value),
"--name" => o.player_name = Some(value),
"--session-file" => session_file = Some(value),
"--control-socket" => o.control = Some(value.into()),
+63
View File
@@ -50,6 +50,7 @@ Start the client.
horizon-launcher play
- `--instance`: The instance to play (its name or id; default: the selected one)
- `--world`: Open or create this world (a folder under saves) at once
- `--creative`: Creative mode for a new world
- `--join`: Join a friend's world with its invite code
@@ -257,6 +258,68 @@ Upload a benchmark report (docs/benchmark-report.md); it is printed first.
MCP: `data_benchmark`, only when the player asks.
## `horizon-launcher instance list`
The instances, each with its game folder (* = the one Play starts).
horizon-launcher instance list
MCP: `instance_list`.
## `horizon-launcher instance create`
Make an instance: empty but for your options and name, or a copy of another one's worlds, options and packs.
horizon-launcher instance create <NAME>
- `NAME`
- `--copy`: The instance to copy (its name or id)
MCP: `instance_create`.
## `horizon-launcher instance rename`
Rename an instance (its folder stays).
horizon-launcher instance rename <INSTANCE> <NAME>
- `INSTANCE`
- `NAME`
MCP: `instance_rename`.
## `horizon-launcher instance icon`
Set an instance's icon: a block or item name from your prepared files (grass_block), a colour (#3fa7d6), or none.
horizon-launcher instance icon <INSTANCE> <ICON>
- `INSTANCE`
- `ICON`
MCP: `instance_icon`.
## `horizon-launcher instance group`
Put an instance in a sidebar group, or take it out with no group.
horizon-launcher instance group <INSTANCE> [GROUP]
- `INSTANCE`
- `GROUP`
MCP: `instance_group`.
## `horizon-launcher instance select`
Make Play start this instance.
horizon-launcher instance select <INSTANCE>
- `INSTANCE`
MCP: `instance_select`.
## `horizon-launcher modpack list`
The imported packs and their coverage (the default).
+1 -1
View File
@@ -64,7 +64,7 @@ A harness can declare, at the top level of its script:
### Which harnesses a change affects
`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses.
`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. With `--changed`, `Cargo.lock` and `Cargo.toml` changes that only add, remove or move workspace crates (a crate split: no registry or git package, version, feature, dependency or build setting changed across them, compared with the merge base) don't count: the moved code counts through its sources. A workspace crate's feature that such a change defines or turns on is allowed only where every source naming it changed too (the new crate's own files). #2160's split went from 352 harnesses to 123 this way (its own changes to the runner still select them all). On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses.
## The gate
+15 -1
View File
@@ -69,6 +69,16 @@ The opening, then Play ([clip](docs/opening.webm)):
access controls, one click changes them so friends you share with reach only the server's
port (Remove the limit undoes it); custom access controls are never rewritten, the page gives
the rule to add instead. Horizon never turns on Funnel.
- **Instances**: separate game folders, each with its own worlds, options and packs. The game's
folder stays the first one, "Horizon", exactly where it was; imported and registry modpacks are
instances too, in their own folders as before; new ones go to `instances/<name>/` in the game's
folder, empty but for the player's options and name, or a copy of another instance (never its
sign-in sessions, logs or data collection state). Names, icons (a block or item texture from the
player's prepared files, or a colour) and groups are kept in `instances.json` in the launcher's
data folder, so renaming moves nothing. Every instance follows the launcher's data collection
answer and No AI. In the window, **+** beside Instances makes one, the sidebar lists them by
group (click one to play it), and Home's Instance row has Edit (name, group, icon), Copy and
Open folder.
- **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer.
Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux,
@@ -152,7 +162,7 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code
horizon-launcher install <tag|latest>
horizon-launcher remove <tag>
horizon-launcher prepare [--minecraft <dir>] [--version <tag>]
horizon-launcher play [--version <tag>] [--arg <ARG>]... start the client; --arg passes an extra argument through (repeatable)
horizon-launcher play [--version <tag>] [--instance <name>] [--arg <ARG>]... start the client; --arg passes an extra argument through (repeatable)
horizon-launcher server [--dir <dir>] [--version <tag>] [--accept-eula]
horizon-launcher notes [<tag>] patch notes as plain text
horizon-launcher links the Discord, sponsor and website links
@@ -164,6 +174,10 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code
horizon-launcher account sign-out <name>
horizon-launcher account select <name> play as this account
horizon-launcher account offline play without an account
horizon-launcher instance [list] the instances and their game folders (* = Play starts it)
horizon-launcher instance create <name> [--copy <instance>] empty, or a copy of one's worlds, options and packs
horizon-launcher instance rename|icon|group <instance> <value> icon: a block or item name, #rrggbb or none
horizon-launcher instance select <instance> make Play start it
horizon-launcher modpack [list] the imported packs and their coverage
horizon-launcher modpack import <pack> a .mrpack, CurseForge zip or instance folder
horizon-launcher modpack port <pack> [--from <dir>] [--version <tag>] get the jars and carry them over
+7 -3
View File
@@ -1585,9 +1585,10 @@ pub fn newest_crash_report() -> Option<PathBuf> {
crash_reports_in(&crash_reports_dir()).pop()
}
/// The newest crash report written at or after `since` (one from the run that started then).
pub fn crash_report_since(since: std::time::SystemTime) -> Option<PathBuf> {
crash_report_in_since(&crash_reports_dir(), since)
/// The newest crash report the game playing in `home` wrote at or after `since` (one from the
/// run that started then).
pub fn crash_report_since(home: &Path, since: std::time::SystemTime) -> Option<PathBuf> {
crash_report_in_since(&home.join("crash-reports"), since)
}
fn crash_report_in_since(dir: &Path, since: std::time::SystemTime) -> Option<PathBuf> {
@@ -2517,6 +2518,9 @@ pub enum Appearance {
#[derive(Default, serde::Serialize, serde::Deserialize)]
pub struct Settings {
pub selected: Option<String>,
/// The instance Play starts (`instances`), by id. Unset means Horizon, the game's home.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instance: 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
+1 -1
View File
@@ -37,7 +37,7 @@ pub fn list() -> Vec<Installed> {
list_in(&packs_dir())
}
fn list_in(dir: &Path) -> Vec<Installed> {
pub(crate) fn list_in(dir: &Path) -> Vec<Installed> {
let mut packs: Vec<Installed> = fs::read_dir(dir)
.into_iter()
.flatten()
+97
View File
@@ -3,6 +3,7 @@
use clap::{Parser, Subcommand};
use horizon_launcher::account::{self, Accounts};
use horizon_launcher::backend::{self, Release};
use horizon_launcher::instances;
use std::io::{IsTerminal, Write};
use std::path::PathBuf;
use std::process::Command;
@@ -155,6 +156,32 @@ enum ModpackCmd {
Remove { pack: String },
}
#[derive(Subcommand)]
enum InstanceCmd {
/// The instances, each with its game folder (* = the one Play starts)
List,
/// Make an instance: empty but for your options and name, or a copy of another one's
/// worlds, options and packs
Create {
name: String,
/// The instance to copy (its name or id)
#[arg(long)]
copy: Option<String>,
},
/// Rename an instance (its folder stays)
Rename { instance: String, name: String },
/// Set an instance's icon: a block or item name from your prepared files (grass_block),
/// a colour (#3fa7d6), or none
Icon { instance: String, icon: String },
/// Put an instance in a sidebar group, or take it out with no group
Group {
instance: String,
group: Option<String>,
},
/// Make Play start this instance
Select { instance: String },
}
#[derive(Subcommand)]
enum ModsCmd {
/// What the browser installed (the default)
@@ -261,6 +288,9 @@ enum Cmd {
Play {
#[arg(long)]
version: Option<String>,
/// The instance to play (its name or id; default: the selected one)
#[arg(long)]
instance: Option<String>,
/// Open or create this world (a folder under saves) at once
#[arg(long)]
world: Option<String>,
@@ -341,6 +371,11 @@ enum Cmd {
#[command(subcommand)]
action: Option<DataCmd>,
},
/// Instances: separate game folders, each with its own worlds, options and packs
Instance {
#[command(subcommand)]
action: Option<InstanceCmd>,
},
/// Modpacks: import a Java pack, see its coverage report, port what this computer can and
/// play it as its own profile (docs/modpacks.md)
Modpack {
@@ -606,12 +641,18 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
}
Cmd::Play {
version,
instance,
world,
creative,
join,
arg,
} => {
let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?;
let instance = match instance {
Some(name) => instances::find(&name)?,
None => instances::selected(),
};
instances::apply(&mut cmd, &instance)?;
if let Some(code) = join {
backend::join_friend(&mut cmd, &code)?;
}
@@ -784,6 +825,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
println!("Horizon is in the applications menu.");
}
}
Cmd::Instance { action } => instance(action.unwrap_or(InstanceCmd::List), as_json)?,
Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?,
Cmd::Mods { action } => mods(action.unwrap_or(ModsCmd::List), as_json)?,
Cmd::Servers { action } => servers(action.unwrap_or(ServersCmd::List), as_json)?,
@@ -1337,6 +1379,61 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> {
Ok(())
}
fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
use instances::Icon;
let value = |i: &instances::Instance, selected: bool| {
serde_json::json!({
"id": i.id, "name": i.name, "kind": format!("{:?}", i.kind).to_lowercase(),
"home": i.home, "icon": i.icon, "group": i.group, "selected": selected,
})
};
let line = |i: &instances::Instance, selected: bool| {
let mark = if selected { "*" } else { " " };
let group = i
.group
.as_ref()
.map(|g| format!(" [{g}]"))
.unwrap_or_default();
println!(
"{mark} {} ({}){group}\n {}",
i.name,
i.id,
i.home.display()
);
};
let changed = |i: instances::Instance| {
let selected = i.id == instances::selected().id;
match as_json {
true => json(value(&i, selected)),
false => line(&i, selected),
}
};
match action {
InstanceCmd::List => {
let selected = instances::selected().id;
let all = instances::list();
if as_json {
json(all.iter().map(|i| value(i, i.id == selected)).collect());
} else {
all.iter().for_each(|i| line(i, i.id == selected));
}
}
InstanceCmd::Create { name, copy } => changed(instances::create(&name, copy.as_deref())?),
InstanceCmd::Rename { instance, name } => {
changed(instances::edit(&instance, |m| m.name = Some(name))?)
}
InstanceCmd::Icon { instance, icon } => {
let icon = (icon != "none").then(|| Icon::parse(&icon)).transpose()?;
changed(instances::edit(&instance, |m| m.icon = icon)?)
}
InstanceCmd::Group { instance, group } => {
changed(instances::edit(&instance, |m| m.group = group)?)
}
InstanceCmd::Select { instance } => changed(instances::select(&instance)?),
}
Ok(())
}
fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::browser::horizon;
use horizon_launcher::modpacks::{self, Imported};
+414
View File
@@ -0,0 +1,414 @@
//! Instances: separate game folders, each with its own worlds, options and packs.
//!
//! Nothing that exists moves. The game's home (`backend::game_home`) stays the default instance,
//! "Horizon", with its saves and options where they are. Imported modpacks (`ports/<pack>/home/`)
//! and registry modpacks (`horizon-packs/<id>/home/`) are instances too, played from their own
//! folders as before. New instances get `instances/<slug>/` in the game's home. What the player
//! chooses about an instance (its name, icon, group) is kept in `instances.json` in the
//! launcher's data folder, so renaming one never moves a folder.
use crate::backend;
use crate::browser::horizon::pack as registry_pack;
use crate::modpacks;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
/// The default instance's id: the game's home itself.
pub const DEFAULT: &str = "horizon";
const FILE: &str = "instances.json";
/// Where new instances live, in the game's home.
const OWN: &str = "instances";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
/// The game's home: what every player had before instances.
Default,
/// Made in the launcher: `instances/<slug>/`.
Own,
/// An imported Java modpack (modpacks.rs).
Port,
/// A modpack from Horizon's registry.
Pack,
}
/// What an instance shows in the sidebar: a block or item texture from the player's prepared
/// files (never shipped), or a colour.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Icon {
/// A texture name: `grass_block` (block/ is looked in first, then item/).
Texture(String),
/// `#rrggbb`.
Colour(String),
}
impl Icon {
/// `#3fa7d6` is a colour; a texture's name is lowercase letters, digits and `_`.
pub fn parse(text: &str) -> Result<Icon, String> {
let text = text.trim();
if let Some(hex) = text.strip_prefix('#') {
if hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit()) {
return Ok(Icon::Colour(format!("#{}", hex.to_ascii_lowercase())));
}
} else if !text.is_empty()
&& text
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
{
return Ok(Icon::Texture(text.into()));
}
Err(format!(
"{text}: give a block or item name (grass_block) or a colour (#3fa7d6)"
))
}
/// The texture's file in prepared resources, if it is a texture they hold.
pub fn texture(&self, resources: &Path) -> Option<PathBuf> {
let Icon::Texture(name) = self else {
return None;
};
let textures = resources.join("assets/minecraft/textures");
["block", "item"]
.iter()
.map(|kind| textures.join(kind).join(format!("{name}.png")))
.find(|p| p.is_file())
}
}
/// The player's choices about one instance.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Meta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<Icon>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub group: Option<String>,
}
/// `instances.json`: each instance's choices, by id.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
struct Store {
#[serde(default)]
instances: BTreeMap<String, Meta>,
}
impl Store {
fn load(data: &Path) -> Store {
fs::read_to_string(data.join(FILE))
.ok()
.and_then(|t| serde_json::from_str(&t).ok())
.unwrap_or_default()
}
fn save(&self, data: &Path) -> Result<(), String> {
fs::create_dir_all(data).map_err(|e| format!("{}: {e}", data.display()))?;
let text = serde_json::to_string_pretty(self).unwrap();
fs::write(data.join(FILE), text).map_err(|e| format!("{FILE}: {e}"))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Instance {
/// `horizon`, an own instance's folder name, `port:<pack>` or `pack:<id>`.
pub id: String,
pub name: String,
pub kind: Kind,
/// The folder the pack's tools work in: the game's home for Default and Own instances.
pub work: PathBuf,
/// The game folder it plays in: saves, options.txt, packs.
pub home: PathBuf,
pub icon: Option<Icon>,
pub group: Option<String>,
}
/// The instances, by the default game home and the launcher's data folder: Horizon first, then
/// by group and name.
pub fn list() -> Vec<Instance> {
list_in(&backend::game_home(), &backend::data_dir())
}
fn list_in(game_home: &Path, data: &Path) -> Vec<Instance> {
let store = Store::load(data);
let mut found = vec![(
DEFAULT.to_string(),
"Horizon".to_string(),
Kind::Default,
game_home.to_path_buf(),
game_home.to_path_buf(),
)];
let mut own: Vec<_> = fs::read_dir(game_home.join(OWN))
.into_iter()
.flatten()
.flatten()
.filter(|e| e.path().is_dir())
.filter_map(|e| e.file_name().into_string().ok())
.collect();
own.sort();
for slug in own {
let dir = game_home.join(OWN).join(&slug);
found.push((slug.clone(), slug, Kind::Own, dir.clone(), dir));
}
for p in modpacks::list_in(&game_home.join("ports")) {
let home = modpacks::profile_home(&p.work);
found.push((
format!("port:{}", p.slug),
p.title().into(),
Kind::Port,
p.work,
home,
));
}
for p in registry_pack::list_in(&game_home.join("horizon-packs")) {
let home = registry_pack::home(&p.work);
found.push((format!("pack:{}", p.id), p.name, Kind::Pack, p.work, home));
}
let mut out: Vec<Instance> = found
.into_iter()
.map(|(id, name, kind, work, home)| {
let meta = store.instances.get(&id).cloned().unwrap_or_default();
Instance {
name: meta.name.unwrap_or(name),
icon: meta.icon,
group: meta.group,
id,
kind,
work,
home,
}
})
.collect();
out[1..].sort_by_key(|i| (i.group.clone(), i.name.to_lowercase()));
out
}
/// The instance an id, a name (any case) or a pack's folder name names.
pub fn find(query: &str) -> Result<Instance, String> {
find_in(&list(), query)
}
fn find_in(all: &[Instance], query: &str) -> Result<Instance, String> {
let q = query.trim();
let bare = |id: &str| id.split_once(':').map_or(id, |(_, rest)| rest).to_string();
all.iter()
.find(|i| i.id == q)
.or_else(|| all.iter().find(|i| i.name.eq_ignore_ascii_case(q)))
.or_else(|| all.iter().find(|i| bare(&i.id) == q))
.cloned()
.ok_or_else(|| format!("No instance {q}: horizon-launcher instance list shows them"))
}
/// The instance Play starts: the one picked in the launcher, else Horizon.
pub fn selected() -> Instance {
let all = list();
backend::Settings::load()
.instance
.and_then(|id| all.iter().find(|i| i.id == id).cloned())
.unwrap_or_else(|| all[0].clone())
}
pub fn select(query: &str) -> Result<Instance, String> {
let instance = find(query)?;
let mut settings = backend::Settings::load();
settings.instance = (instance.kind != Kind::Default).then(|| instance.id.clone());
settings.save();
Ok(instance)
}
/// What a copy of a game folder leaves out: other instances and packs, logs and crash reports,
/// caches, data collection's state, and sign-in sessions (a session never leaves its folder).
const NOT_COPIED: &[&str] = &[
OWN,
"ports",
"horizon-packs",
"logs",
"crash-reports",
"sessions",
"telemetry",
"mod-browser",
".horizon-cache",
];
/// Files of the player, not of one instance, that a new instance starts with: the keys and video
/// settings, and the offline name (so the player stays the same player in its worlds).
const PLAYER_FILES: &[&str] = &["options.txt", "horizon-player.txt"];
/// Creates an instance named `name`: empty but for the player's options and offline name, or a
/// copy of `from`'s game folder (its worlds, options and packs). Nothing of `from` changes.
pub fn create(name: &str, from: Option<&str>) -> Result<Instance, String> {
let from = from.map(find).transpose()?;
create_in(
&backend::game_home(),
&backend::data_dir(),
name,
from.as_ref(),
)
}
fn create_in(
game_home: &Path,
data: &Path,
name: &str,
from: Option<&Instance>,
) -> Result<Instance, String> {
let name = name.trim();
if name.is_empty() {
return Err("An instance needs a name.".into());
}
let all = list_in(game_home, data);
if all.iter().any(|i| i.name.eq_ignore_ascii_case(name)) {
return Err(format!("There is already an instance called {name}."));
}
if let Some(from) = from.filter(|f| matches!(f.kind, Kind::Port | Kind::Pack)) {
return Err(format!(
"{} plays its pack's mods: import the pack again for a second copy.",
from.name
));
}
let base = modpacks::slug(name);
let taken = |s: &str| s == DEFAULT || game_home.join(OWN).join(s).exists();
let slug = (1..)
.map(|n| {
if n == 1 {
base.clone()
} else {
format!("{base}-{n}")
}
})
.find(|s| !taken(s))
.unwrap();
let dir = game_home.join(OWN).join(&slug);
let made = match from {
Some(from) => copy_home(&from.home, &dir),
None => fs::create_dir_all(&dir).and_then(|()| {
for f in PLAYER_FILES {
let own = game_home.join(f);
if own.is_file() {
fs::copy(own, dir.join(f))?;
}
}
Ok(())
}),
};
if let Err(e) = made {
let _ = fs::remove_dir_all(&dir);
return Err(format!("Could not make {}: {e}", dir.display()));
}
let mut store = Store::load(data);
let meta = store.instances.entry(slug.clone()).or_default();
meta.name = (name != slug).then(|| name.to_string());
meta.icon = from.and_then(|f| f.icon.clone());
meta.group = from.and_then(|f| f.group.clone());
store.save(data)?;
find_in(&list_in(game_home, data), &slug)
}
fn copy_home(from: &Path, to: &Path) -> std::io::Result<()> {
fs::create_dir_all(to)?;
for entry in fs::read_dir(from)? {
let entry = entry?;
let name = entry.file_name();
if NOT_COPIED.iter().any(|n| name == *n) {
continue;
}
let path = entry.path();
if entry.file_type()?.is_dir() {
copy_dir(&path, &to.join(&name))?;
} else {
fs::copy(&path, to.join(&name))?;
}
}
Ok(())
}
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
fs::create_dir_all(to)?;
for entry in fs::read_dir(from)? {
let entry = entry?;
let target = to.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_dir(&entry.path(), &target)?;
} else {
fs::copy(entry.path(), target)?;
}
}
Ok(())
}
/// Changes what the player chose about an instance: its name, icon or group. No folder moves.
pub fn edit(query: &str, change: impl FnOnce(&mut Meta)) -> Result<Instance, String> {
edit_in(&backend::game_home(), &backend::data_dir(), query, change)
}
fn edit_in(
game_home: &Path,
data: &Path,
query: &str,
change: impl FnOnce(&mut Meta),
) -> Result<Instance, String> {
let all = list_in(game_home, data);
let instance = find_in(&all, query)?;
let mut store = Store::load(data);
let meta = store.instances.entry(instance.id.clone()).or_default();
change(meta);
meta.name = meta.name.take().map(|n| n.trim().to_string());
meta.group = meta
.group
.take()
.map(|g| g.trim().to_string())
.filter(|g| !g.is_empty());
if let Some(name) = &meta.name {
if name.is_empty() {
return Err("An instance needs a name.".into());
}
if all
.iter()
.any(|i| i.id != instance.id && i.name.eq_ignore_ascii_case(name))
{
return Err(format!("There is already an instance called {name}."));
}
}
store.save(data)?;
find_in(&list_in(game_home, data), &instance.id)
}
/// Turns the game's command into this instance: its own game folder, and a pack's mods. The
/// player's answers that hold everywhere follow it in: data collection and No AI as the
/// launcher has them, and options.txt and the offline name when it has none yet.
pub fn apply(cmd: &mut Command, instance: &Instance) -> Result<(), String> {
match instance.kind {
Kind::Default => return Ok(()),
Kind::Own => {
fs::create_dir_all(&instance.home)
.map_err(|e| format!("{}: {e}", instance.home.display()))?;
cmd.current_dir(&instance.home)
.env("HORIZON_HOME", &instance.home);
}
Kind::Port | Kind::Pack => modpacks::apply_profile(cmd, &instance.work)?,
}
follow_player(&backend::game_home(), &instance.home);
Ok(())
}
fn follow_player(game_home: &Path, home: &Path) {
for f in PLAYER_FILES {
if !home.join(f).exists() && game_home.join(f).is_file() {
let _ = fs::copy(game_home.join(f), home.join(f));
}
}
let consent = horizon_telemetry::consent::Consent::path(game_home);
if consent.is_file() {
let to = horizon_telemetry::consent::Consent::path(home);
let _ = fs::create_dir_all(to.parent().unwrap());
let _ = fs::copy(consent, to);
}
let no_ai = horizon_core::no_ai::is_on(game_home);
if horizon_core::no_ai::is_on(home) != no_ai {
let _ = horizon_core::no_ai::set(home, no_ai);
}
}
#[cfg(test)]
#[path = "instances/tests.rs"]
mod tests;
+203
View File
@@ -0,0 +1,203 @@
use super::*;
use std::collections::BTreeMap;
fn scratch(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"horizon-launcher-instances-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
root
}
fn put(path: &Path, text: &str) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// Every file under `dir`, relative, with its bytes.
fn files(dir: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<PathBuf, Vec<u8>>) {
for e in fs::read_dir(dir).unwrap().flatten() {
let p = e.path();
if p.is_dir() {
walk(root, &p, out);
} else {
out.insert(p.strip_prefix(root).unwrap().into(), fs::read(&p).unwrap());
}
}
}
let mut out = BTreeMap::new();
walk(dir, dir, &mut out);
out
}
/// A game home as a player has it before instances: worlds, options, packs, a session, an
/// imported modpack and a registry modpack with their own worlds.
fn player_home(home: &Path) {
put(&home.join("saves/World/level.dat"), "world");
put(&home.join("saves/World/region/r.0.0.mca"), "region");
put(&home.join("saves/Other/level.dat"), "other");
put(&home.join("options.txt"), "fov:90\n");
put(&home.join("horizon-player.txt"), "name:Player123\n");
put(&home.join("resourcepacks/faithful.zip"), "pack");
put(&home.join("logs/latest.log"), "log");
put(&home.join("sessions/a.json"), "token");
put(&home.join("telemetry/consent.json"), "{}");
let pack = horizon_port_pack::import::Pack {
name: "Small Pack".into(),
..Default::default()
};
put(
&home.join("ports/small-pack/pack.json"),
&serde_json::to_string(&pack).unwrap(),
);
put(
&home.join("ports/small-pack/home/saves/Modded/level.dat"),
"modded",
);
put(
&home.join("horizon-packs/cozy/pack.json"),
r#"{"id":"cozy","name":"Cozy","version":"1.0.0","sha256":"00","mods":[]}"#,
);
put(
&home.join("horizon-packs/cozy/home/saves/Cozy/level.dat"),
"cozy",
);
}
#[test]
fn existing_worlds_stay_where_they_are_and_every_folder_becomes_an_instance() {
let root = scratch("migrate");
let (home, data) = (root.join("horizon"), root.join("launcher"));
player_home(&home);
let before = files(&home);
// A launcher with instances, on a player's existing folders: no instances.json yet.
let all = list_in(&home, &data);
let ids: Vec<&str> = all.iter().map(|i| i.id.as_str()).collect();
assert_eq!(ids, [DEFAULT, "pack:cozy", "port:small-pack"]);
assert_eq!(all[0].name, "Horizon");
assert_eq!(all[0].home, home);
assert_eq!(all[1].home, home.join("horizon-packs/cozy/home"));
assert_eq!(all[2].name, "Small Pack");
assert_eq!(all[2].home, home.join("ports/small-pack/home"));
// Everything the player can do with instances, then not one byte of theirs has moved.
let empty = create_in(&home, &data, "Survival", None).unwrap();
let copy = create_in(&home, &data, "My copy", Some(&all[0])).unwrap();
edit_in(&home, &data, DEFAULT, |m| m.name = Some("Main".into())).unwrap();
edit_in(&home, &data, "Small Pack", |m| {
m.icon = Some(Icon::Texture("diamond".into()));
m.group = Some("Modded".into());
})
.unwrap();
let after = files(&home);
for (path, bytes) in &before {
assert_eq!(after.get(path), Some(bytes), "{} changed", path.display());
}
assert!(!data.join("settings.json").exists());
// The empty one has only the player's options and name; the copy has the worlds and
// packs, never the sessions, logs, data collection or other instances.
assert_eq!(empty.home, home.join("instances/survival"));
let empty_files: Vec<PathBuf> = files(&empty.home).into_keys().collect();
assert_eq!(
empty_files,
[PathBuf::from("horizon-player.txt"), "options.txt".into()]
);
let copied = files(&copy.home);
for kept in [
"saves/World/region/r.0.0.mca",
"saves/Other/level.dat",
"resourcepacks/faithful.zip",
] {
assert_eq!(copied[Path::new(kept)], before[Path::new(kept)]);
}
assert!(copied.keys().all(|p| {
let top = p.components().next().unwrap().as_os_str().to_str().unwrap();
!NOT_COPIED.contains(&top)
}));
let all = list_in(&home, &data);
assert_eq!(all[0].name, "Main");
let port = find_in(&all, "port:small-pack").unwrap();
assert_eq!(port.group.as_deref(), Some("Modded"));
assert_eq!(port.home, home.join("ports/small-pack/home"));
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn names_stay_unique_and_packs_are_not_copied() {
let root = scratch("names");
let (home, data) = (root.join("horizon"), root.join("launcher"));
player_home(&home);
create_in(&home, &data, "Survival", None).unwrap();
assert!(create_in(&home, &data, "survival", None).is_err());
assert!(create_in(&home, &data, " ", None).is_err());
// Another name with the same folder name gets the next free folder.
let second = create_in(&home, &data, "Survival!", None).unwrap();
assert_eq!(second.id, "survival-2");
assert_eq!(second.name, "Survival!");
assert!(edit_in(&home, &data, "survival-2", |m| m.name =
Some("SURVIVAL".into()))
.is_err());
let port = find_in(&list_in(&home, &data), "small-pack").unwrap();
assert!(create_in(&home, &data, "Pack copy", Some(&port)).is_err());
assert!(!home.join("instances/pack-copy").exists());
// An empty group is no group.
let grouped = edit_in(&home, &data, "Survival", |m| m.group = Some(" ".into())).unwrap();
assert_eq!(grouped.group, None);
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn an_instance_follows_the_players_answers() {
let root = scratch("follow");
let (main, own) = (root.join("main"), root.join("own"));
put(&main.join("options.txt"), "fov:90\n");
put(&main.join("horizon-player.txt"), "name:Player123\n");
put(&main.join("telemetry/consent.json"), r#"{"version":1}"#);
horizon_core::no_ai::set(&main, true).unwrap();
put(&own.join("options.txt"), "fov:70\n");
follow_player(&main, &own);
assert_eq!(
fs::read_to_string(own.join("options.txt")).unwrap(),
"fov:70\n"
);
assert_eq!(
fs::read_to_string(own.join("horizon-player.txt")).unwrap(),
"name:Player123\n"
);
assert_eq!(
fs::read_to_string(own.join("telemetry/consent.json")).unwrap(),
r#"{"version":1}"#
);
assert!(horizon_core::no_ai::is_on(&own));
horizon_core::no_ai::set(&main, false).unwrap();
follow_player(&main, &own);
assert!(!horizon_core::no_ai::is_on(&own));
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn icons_are_a_texture_name_or_a_colour() {
assert_eq!(Icon::parse("#3FA7D6"), Ok(Icon::Colour("#3fa7d6".into())));
assert_eq!(
Icon::parse("grass_block"),
Ok(Icon::Texture("grass_block".into()))
);
for bad in ["#12345", "../x", "Grass", "", "#zzzzzz"] {
assert!(Icon::parse(bad).is_err(), "{bad}");
}
let root = scratch("icon");
put(
&root.join("assets/minecraft/textures/item/diamond.png"),
"png",
);
let diamond = Icon::Texture("diamond".into()).texture(&root).unwrap();
assert!(diamond.ends_with("item/diamond.png"));
assert_eq!(Icon::Texture("stone".into()).texture(&root), None);
fs::remove_dir_all(&root).unwrap();
}
+583
View File
@@ -0,0 +1,583 @@
//! Instances in the window (`horizon_launcher::instances`): the sidebar's list, by group, and the
//! dialog that makes one (empty, or a copy of the selected one) or changes its name, group and
//! icon.
use super::*;
use gpui::RenderImage;
use horizon_launcher::instances::{self, Icon, Instance, Kind as InstanceKind};
use servers_page::Field;
use std::collections::HashMap;
use std::sync::Arc;
/// Textures offered as icons, when the player's prepared files hold them: block faces and items
/// that read well at sidebar size.
const TEXTURES: [&str; 24] = [
"grass_block_side",
"oak_planks",
"oak_log",
"cobblestone",
"bricks",
"bookshelf",
"crafting_table_front",
"tnt_side",
"sand",
"snow",
"ice",
"obsidian",
"netherrack",
"end_stone",
"glowstone",
"diamond_ore",
"diamond",
"emerald",
"apple",
"ender_pearl",
"iron_pickaxe",
"diamond_sword",
"bow",
"book",
];
/// Colours offered as icons: Horizon's accent and a few that sit beside it in both themes.
const COLOURS: [&str; 8] = [
"#5b3fd6", "#3f7fd6", "#2f9e8f", "#4f9e2f", "#c9a227", "#d9732f", "#c4405a", "#7d7591",
];
/// The dialog: a new instance (`editing` None) or one being changed. Its name and group are the
/// text fields `Field::InstanceName` and `Field::InstanceGroup`.
pub(super) struct InstanceDialog {
editing: Option<String>,
/// A new instance copies the selected one's worlds, options and packs.
copy: bool,
icon: Option<Icon>,
error: Option<String>,
busy: bool,
}
/// The instances and their icons as images, kept between frames.
#[derive(Default)]
pub(super) struct Instances {
pub(super) list: Vec<Instance>,
pub(super) dialog: Option<InstanceDialog>,
icons: HashMap<(String, u32), Option<Arc<RenderImage>>>,
}
impl Launcher {
pub(super) fn reload_instances(&mut self) {
self.instances.list = instances::list();
}
/// The instance Play starts.
pub(super) fn selected_instance(&self) -> Option<&Instance> {
let id = self
.settings
.instance
.as_deref()
.unwrap_or(instances::DEFAULT);
let list = &self.instances.list;
list.iter().find(|i| i.id == id).or(list.first())
}
fn select_instance(&mut self, instance: &Instance) {
self.settings.instance =
(instance.kind != InstanceKind::Default).then(|| instance.id.clone());
self.settings.save();
}
/// A texture from the selected version's prepared files, its first frame, drawn as pixels.
fn texture_image(&mut self, name: &str, size: f32) -> Option<Arc<RenderImage>> {
let tag = self.selected().filter(|t| backend::is_prepared(t))?.clone();
let scale = self.scale;
self.instances
.icons
.entry((name.to_string(), (size * scale) as u32))
.or_insert_with(|| {
let path = Icon::Texture(name.into()).texture(&backend::resources(&tag))?;
let png = image::open(path).ok()?.to_rgba8();
let w = png.width() as usize;
// An animated texture is its frames one under another: the first is square.
let texels: Vec<[u8; 4]> = png.pixels().take(w * w).map(|p| p.0).collect();
Some(art::bake(&texels, w, w, size / w as f32, scale))
})
.clone()
}
/// An instance's icon, `size` points square.
pub(super) fn instance_icon(&mut self, instance: &Instance, size: f32) -> AnyElement {
let t = self.theme;
let framed = |d: Div| {
d.flex()
.flex_none()
.items_center()
.justify_center()
.size(px(size))
.border_2()
.border_color(t.outline)
};
match &instance.icon {
Some(Icon::Colour(hex)) => {
let rgb = u32::from_str_radix(&hex[1..], 16).unwrap_or(0);
return framed(div().bg(gpui::rgb(rgb)))
.child(
blocks::pixel((size * 0.42).round(), FontWeight::BOLD)
.text_color(gpui::white())
.child(initial(&instance.name)),
)
.into_any_element();
}
Some(Icon::Texture(name)) => {
if let Some(image) = self.texture_image(name, size - 8.) {
return framed(div().bg(t.well))
.child(gpui::img(image).size(px(size - 8.)))
.into_any_element();
}
}
None if instance.kind == InstanceKind::Default => {
if let Some(grass) = self.vanilla_icon() {
return div()
.flex()
.items_center()
.justify_center()
.size(px(size))
.child(gpui::img(grass).size(px(size - 4.)))
.into_any_element();
}
}
None => {}
}
blocks::slot(None, &instance.name, size, &t).into_any_element()
}
/// The sidebar's instances: those without a group, then each group under its name.
pub(super) fn instance_items(
&mut self,
heading: impl Fn(String) -> Div,
cx: &mut Context<Self>,
) -> Vec<AnyElement> {
let t = self.theme;
let tag = self.selected().cloned();
let prepared = tag.as_deref().is_some_and(backend::is_prepared);
let status = if tag.is_none() {
"No version installed"
} else if prepared {
"Ready"
} else {
"Needs preparing"
};
let selected = self.selected_instance().map(|i| i.id.clone());
let on_packs = self.page == Page::Mods && self.mods.on_modpacks();
let mut out = Vec::new();
let mut group = None;
for i in self.instances.list.clone() {
if i.group != group {
group = i.group.clone();
if let Some(g) = &group {
out.push(heading(g.to_uppercase()).into_any_element());
}
}
let (open, sub) = match i.kind {
InstanceKind::Default | InstanceKind::Own => (
self.page == Page::Play && selected.as_ref() == Some(&i.id),
status.to_string(),
),
InstanceKind::Port => {
let slug = &i.id["port:".len()..];
let summary = self.packs.iter().find(|p| p.slug == slug);
(
on_packs && self.pack_open.as_deref() == Some(slug),
summary.map_or_else(|| "Modpack".into(), |p| p.summary()),
)
}
InstanceKind::Pack => (false, "From Horizon's registry".into()),
};
let dot = matches!(i.kind, InstanceKind::Default | InstanceKind::Own).then(|| {
div()
.absolute()
.left(px(42.))
.top(px(42.))
.size(px(10.))
.bg(if prepared { t.success } else { t.warn })
.border_2()
.border_color(t.side)
});
let icon = self.instance_icon(&i, 44.);
let clicked = i.clone();
out.push(
blocks::side_item(format!("side-instance-{}", i.id).into(), open, &t)
.child(icon)
.children(dot)
.child(
div()
.flex()
.flex_col()
.min_w_0()
.child(
blocks::pixel(15., FontWeight::MEDIUM)
.text_color(t.ink)
.truncate()
.child(i.name.clone()),
)
.child(
text(theme::CAPTION)
.text_color(t.muted)
.truncate()
.child(sub),
),
)
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
match clicked.kind {
InstanceKind::Default | InstanceKind::Own => {
this.select_instance(&clicked);
this.go(Page::Play);
}
InstanceKind::Port => {
this.show_modpack(Some(clicked.id["port:".len()..].into()))
}
InstanceKind::Pack => this.show_modpack(None),
}
cx.notify();
}))
.into_any_element(),
);
}
out
}
/// Opens the dialog for a new instance, or for changing `editing`.
pub(super) fn open_instance_dialog(&mut self, editing: Option<Instance>) {
let (name, group) = editing
.as_ref()
.map(|i| (i.name.clone(), i.group.clone().unwrap_or_default()))
.unwrap_or_default();
*self.servers.text(Field::InstanceName) = name;
*self.servers.text(Field::InstanceGroup) = group;
self.servers.focus_soon = Some(Field::InstanceName);
self.instances.dialog = Some(InstanceDialog {
icon: editing.as_ref().and_then(|i| i.icon.clone()),
editing: editing.map(|i| i.id),
copy: false,
error: None,
busy: false,
});
}
/// Escape closes the dialog. Whether it did.
pub(super) fn instance_escape(&mut self) -> bool {
if self.instances.dialog.as_ref().is_some_and(|d| !d.busy) {
self.instances.dialog = None;
return true;
}
false
}
/// Creates or changes the instance as the dialog says. A copy can be gigabytes of worlds, so
/// the work runs in the background.
pub(super) fn save_instance(&mut self, cx: &mut Context<Self>) {
let selected = self.selected_instance().map(|i| i.id.clone());
let name = self.servers.value(Field::InstanceName).trim().to_string();
let group = Some(self.servers.value(Field::InstanceGroup).to_string());
let Some(d) = self.instances.dialog.as_mut().filter(|d| !d.busy) else {
return;
};
let icon = d.icon.clone();
let editing = d.editing.clone();
let copy = selected.filter(|_| d.copy);
d.busy = true;
d.error = None;
let task = cx.background_executor().spawn(async move {
let id = match editing {
Some(id) => id,
None => instances::create(&name, copy.as_deref())?.id,
};
instances::edit(&id, |m| {
m.name = Some(name);
m.group = group;
m.icon = icon;
})
});
cx.spawn(async move |this, cx| {
let result = task.await;
let _ = this.update(cx, |this, cx| {
match result {
Ok(instance) => {
this.instances.dialog = None;
this.select_instance(&instance);
this.reload_instances();
if matches!(instance.kind, InstanceKind::Default | InstanceKind::Own) {
this.go(Page::Play);
}
}
Err(e) => {
if let Some(d) = &mut this.instances.dialog {
d.busy = false;
d.error = Some(e);
}
}
}
cx.notify();
});
})
.detach();
}
pub(super) fn instance_dialog(&mut self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
let t = self.theme;
let d = self.instances.dialog.as_ref()?;
let (editing, copy, icon, error, busy) = (
d.editing.is_some(),
d.copy,
d.icon.clone(),
d.error.clone(),
d.busy,
);
let from = self
.selected_instance()
.map_or_else(|| "Horizon".into(), |i| i.name.clone());
let row = |label: &'static str, control: AnyElement| {
div()
.flex()
.flex_col()
.gap(px(8.))
.child(caps(label).text_color(t.muted))
.child(control)
};
let mut body = div()
.flex()
.flex_col()
.gap(px(20.))
.p(px(24.))
.child(
blocks::pixel(22., FontWeight::MEDIUM)
.text_color(t.ink)
.child(if editing {
"Edit instance"
} else {
"New instance"
}),
)
.child(row(
"Name",
self.field(Field::InstanceName, "My instance", 400., cx)
.into_any_element(),
));
if !editing {
let weak = cx.entity().downgrade();
body = body.child(row(
"Start from",
segments(
"instance-from",
&[(false, "Empty"), (true, "A copy of the selected one")],
copy,
&t,
move |copy, _, cx| {
let _ = weak.update(cx, |this, cx| {
if let Some(d) = &mut this.instances.dialog {
d.copy = copy;
}
cx.notify();
});
},
)
.into_any_element(),
));
body = body.child(text(theme::CAPTION).text_color(t.muted).child(if copy {
format!("{from}'s worlds, options and packs are copied; {from} stays as it is.")
} else {
"Its own worlds and packs; your options and player name come along.".to_string()
}));
}
body = body.child(row(
"Group",
self.field(Field::InstanceGroup, "No group", 400., cx)
.into_any_element(),
));
let mut tiles = div().flex().flex_wrap().gap(px(6.));
let tile = |id: String, chosen: bool| {
div()
.id(SharedString::from(id))
.flex()
.items_center()
.justify_center()
.size(px(40.))
.border_2()
.border_color(if chosen { t.accent } else { t.rule })
.cursor_pointer()
.hover(move |s| s.border_color(t.outline))
};
let none = icon.is_none();
tiles = tiles.child(
tile("instance-icon-none".into(), none)
.child(text(theme::MICRO).text_color(t.muted).child("NONE"))
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
if let Some(d) = &mut this.instances.dialog {
d.icon = None;
}
cx.notify();
})),
);
for name in TEXTURES {
let Some(image) = self.texture_image(name, 28.) else {
continue;
};
let chosen = icon == Some(Icon::Texture(name.into()));
tiles = tiles.child(
tile(format!("instance-icon-{name}"), chosen)
.bg(t.well)
.child(gpui::img(image).size(px(28.)))
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
if let Some(d) = &mut this.instances.dialog {
d.icon = Some(Icon::Texture(name.into()));
}
cx.notify();
})),
);
}
for hex in COLOURS {
let chosen = icon == Some(Icon::Colour(hex.into()));
let rgb = u32::from_str_radix(&hex[1..], 16).unwrap_or(0);
tiles = tiles.child(
tile(format!("instance-icon-{hex}"), chosen)
.child(div().size(px(28.)).bg(gpui::rgb(rgb)))
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
if let Some(d) = &mut this.instances.dialog {
d.icon = Some(Icon::Colour(hex.into()));
}
cx.notify();
})),
);
}
body = body.child(row("Icon", tiles.into_any_element()));
if self.selected().is_none_or(|t| !backend::is_prepared(t)) {
body = body.child(
text(theme::CAPTION)
.text_color(t.muted)
.child("Block and item icons come from your prepared game files: prepare a version to see them."),
);
}
if let Some(e) = error {
body = body.child(text(theme::CAPTION).text_color(t.danger).child(e));
}
let cancel = button("instance-cancel", "Cancel", Kind::Secondary, &t);
let label = match (editing, busy, copy) {
(_, true, true) => "Copying…",
(true, false, _) => "Save",
_ => "Create",
};
let save = button("instance-save", label, Kind::Primary, &t);
// A modpack becomes an instance by being imported, on the Mods page.
let import = (!editing && !busy).then(|| {
button("instance-import", "Import a modpack…", Kind::Ghost, &t)
.mr_auto()
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.instances.dialog = None;
this.show_modpack(None);
cx.notify();
}))
});
let foot = div()
.flex()
.justify_end()
.gap(px(8.))
.px(px(24.))
.py(px(16.))
.border_t_1()
.border_color(t.rule)
.children(import);
let foot = if busy {
foot.child(disabled(cancel)).child(disabled(save))
} else {
foot.child(cancel.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.instances.dialog = None;
cx.notify();
})))
.child(save.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.save_instance(cx);
cx.notify();
})))
};
let card = plate(&t)
.flex()
.flex_col()
.w_full()
.max_w(px(560.))
.bg(t.page)
.border_1()
.border_color(t.rule)
.child(body)
.child(foot);
Some(
div()
.id("instance-dialog")
.absolute()
.top_0()
.left_0()
.size_full()
.flex()
.flex_col()
.items_center()
.px(px(32.))
.py(px(24.))
.bg(t.page.opacity(0.92))
.on_scroll_wheel(|_, _, cx| cx.stop_propagation())
.occlude()
.child(card),
)
}
/// The Play page's row for the selected instance: its folder, and changing or copying it.
pub(super) fn instance_row(&mut self, n: usize, cx: &mut Context<Self>) -> Option<Div> {
let t = self.theme;
let instance = self.selected_instance()?.clone();
let (home, edit, name) = (
instance.home.clone(),
instance.clone(),
instance.name.clone(),
);
let actions = div()
.flex()
.gap(px(8.))
.child(
button("instance-edit", "Edit…", Kind::Ghost, &t).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.open_instance_dialog(Some(edit.clone()));
cx.notify();
},
)),
)
.child(
button("instance-copy", "Copy…", Kind::Ghost, &t).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.open_instance_dialog(None);
*this.servers.text(Field::InstanceName) = format!("{name} copy");
if let Some(d) = &mut this.instances.dialog {
d.copy = true;
}
cx.notify();
},
)),
)
.child(
button("instance-folder", "Open folder", Kind::Ghost, &t).on_click(
move |_, _, cx| {
let _ = std::fs::create_dir_all(&home);
cx.open_with_system(&home);
},
),
);
Some(index_row(
n,
"Instance",
Some(div().child(instance.name.clone()).into_any_element()),
Some(actions.into_any_element()),
&t,
))
}
}
/// The first letter or digit of a name, for an icon without a picture.
fn initial(name: &str) -> String {
name.chars()
.find(|c| c.is_alphanumeric())
.unwrap_or('?')
.to_uppercase()
.to_string()
}
+1
View File
@@ -7,6 +7,7 @@ pub mod desktop;
#[cfg(unix)]
pub mod game_app;
pub mod heads;
pub mod instances;
pub mod modpacks;
pub mod mojang;
pub mod process;
+34 -74
View File
@@ -12,6 +12,7 @@ mod collection;
mod console;
mod cull;
mod game_tools;
mod instances_page;
mod internet;
mod markdown;
mod mcp;
@@ -33,6 +34,7 @@ use gpui::{
};
use horizon_launcher::account::{self, Accounts, SignIn, SignInState};
use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates};
use horizon_launcher::instances;
use horizon_launcher::telemetry;
use scrollbar::Scrollbar;
use std::borrow::Cow;
@@ -222,6 +224,8 @@ struct Launcher {
starting_pack: Option<std::path::PathBuf>,
/// The Mods page: the browser's search, installs and updates (`mods_page.rs`).
mods: mods_page::Mods,
/// The instances, for the sidebar and Play, and their dialog (`instances_page.rs`).
instances: instances_page::Instances,
/// The name the game made up for an offline player (`horizon-player.txt`), for the top bar.
offline_name: Option<String>,
/// The player's servers, for the sidebar until the Servers page has read them.
@@ -378,11 +382,13 @@ impl Launcher {
pack_error: None,
starting_pack: None,
mods: mods_page::Mods::new(cx),
instances: instances_page::Instances::default(),
offline_name: offline_name(),
side_servers: horizon_launcher::servers::list(),
art: art::Art::default(),
scale: window.scale_factor(),
};
this.reload_instances();
if this.bench.is_some() {
this.perf.keep_local_log(false);
}
@@ -535,13 +541,16 @@ impl Launcher {
Err(e) => self.client_error = Some(format!("Playing offline: {e}")),
}
self.accounts = Accounts::load();
if let Some(work) = self.starting_pack.take() {
if let Err(e) =
// A pack's Play button plays that pack; Play plays the selected instance.
let profile = match self.starting_pack.take() {
Some(work) => {
horizon_launcher::modpacks::apply_profile(&mut cmd, &work)
{
self.client_error = Some(e);
continue;
}
None => instances::apply(&mut cmd, &instances::selected()),
};
if let Err(e) = profile {
self.client_error = Some(e);
continue;
}
if let Some(code) = self.joining.take() {
if let Err(e) = backend::join_friend(&mut cmd, &code) {
@@ -668,10 +677,12 @@ impl Launcher {
}
Job::Client => {
self.client = None;
// The run's own game folder: an instance's or a pack's keeps its reports.
let home = self.client_home.clone().unwrap_or_else(backend::game_home);
let report = self
.client_started
.take()
.and_then(backend::crash_report_since);
.and_then(|since| backend::crash_report_since(&home, since));
if error.is_some() && report.is_none() && self.switched_to_dx12() {
self.client_error = Some(
"Horizon's Vulkan renderer crashed while starting on this \
@@ -1569,7 +1580,7 @@ impl Launcher {
fn sidebar(&mut self, cx: &mut Context<Self>) -> Stateful<Div> {
let t = self.theme;
self.load_packs();
let heading = |label: &'static str| {
let heading = |label: String| {
div()
.flex()
.items_center()
@@ -1600,7 +1611,7 @@ impl Launcher {
.border_2()
.border_color(t.side)
};
let add = keyboard(div().id("add-pack"), &t)
let add = keyboard(div().id("add-instance"), &t)
.flex()
.items_center()
.justify_center()
@@ -1612,79 +1623,23 @@ impl Launcher {
.hover(move |s| s.bg(t.raised))
.child(blocks::icon("plus", 14., t.ink_soft))
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.show_modpack(None);
this.open_instance_dialog(None);
cx.notify();
}));
let mut list = div()
let list = div()
.flex()
.flex_col()
.gap(px(4.))
.child(heading("INSTANCES").child(add));
// Horizon itself, with a grass block from the player's own prepared files.
let tag = self.selected().cloned();
let prepared = tag.as_deref().is_some_and(backend::is_prepared);
let grass = self.vanilla_icon();
let on_play = self.page == Page::Play;
list = list.child(
blocks::side_item("side-horizon".into(), on_play, &t)
.child(match grass {
Some(g) => div()
.flex()
.items_center()
.justify_center()
.size(px(44.))
.child(gpui::img(g).size(px(40.))),
None => blocks::slot(None, "Horizon", 44., &t),
})
.child(dot(if prepared { t.success } else { t.warn }))
.child(
div()
.flex()
.flex_col()
.min_w_0()
.child(title("Horizon".into()))
.child(sub(if tag.is_none() {
"No version installed"
} else if prepared {
"Vanilla · ready"
} else {
"Needs preparing"
}
.into())),
)
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.go(Page::Play);
cx.notify();
})),
);
let on_packs = self.page == Page::Mods && self.mods.on_modpacks();
for p in &self.packs {
let slug = p.slug.clone();
let open = on_packs && self.pack_open.as_ref() == Some(&p.slug);
list = list.child(
blocks::side_item(format!("side-pack-{slug}").into(), open, &t)
.child(blocks::slot(None, p.title(), 44., &t))
.child(
div()
.flex()
.flex_col()
.min_w_0()
.child(title(p.title().to_string()))
.child(sub(p.summary())),
)
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.show_modpack(Some(slug.clone()));
cx.notify();
})),
);
}
.child(heading("INSTANCES".into()).child(add))
.children(self.instance_items(heading, cx));
let servers: Vec<_> = self
.servers
.sidebar_list()
.map(<[_]>::to_vec)
.unwrap_or_else(|| self.side_servers.clone());
let mut list = list;
if !servers.is_empty() {
list = list.child(heading("SERVERS"));
list = list.child(heading("SERVERS".into()));
}
for e in servers {
let up = self.servers.is_up(&e.dir);
@@ -2068,15 +2023,16 @@ impl Launcher {
.flex()
.flex_col()
.child(section_title("Ready to play", "check", &t).mb(px(12.)))
.children(self.instance_row(1, cx))
.child(index_row(
1,
2,
"Resources",
Some(div().child(resources_value).into_any_element()),
Some(prepare.into_any_element()),
&t,
))
.child(index_row(
2,
3,
"Minecraft folder",
Some(minecraft),
Some(
@@ -2092,7 +2048,7 @@ impl Launcher {
// offline, in a build that can sign in.
if self.accounts.selected().is_none() && account::client_id().is_some() {
rows = rows.child(index_row(
4,
5,
"Playing offline",
Some(
div()
@@ -3058,7 +3014,7 @@ impl Launcher {
join = disabled(join);
}
index_row(
3,
4,
"Join a friend",
Some(
div()
@@ -3517,6 +3473,7 @@ impl Render for Launcher {
}
}
"escape" if this.servers_escape() => {}
"escape" if this.instance_escape() => {}
_ => return,
}
cx.stop_propagation();
@@ -3577,6 +3534,9 @@ impl Render for Launcher {
root = root.child(dialog);
}
}
if let Some(dialog) = self.instance_dialog(cx) {
root = root.child(dialog);
}
if self.asking_consent() {
root = root.child(self.consent_screen(cx));
}
+7
View File
@@ -6,6 +6,7 @@ use crate::cli_tools;
use crate::game_tools::{self, GameTools};
use horizon_launcher::account::{self, Accounts, SignIn, SignInState};
use horizon_launcher::backend::{self, Job, Logged};
use horizon_launcher::instances;
use serde_json::{json, Value};
use std::io::{BufRead, Write};
use std::path::PathBuf;
@@ -29,6 +30,7 @@ fn session_tools() -> Value {
json!([
{ "name": "play", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world. CLI: horizon-launcher play",
"inputSchema": { "type": "object", "properties": { "version": version,
"instance": { "type": "string", "description": "The instance to play, by name or id (instance_list). Default: the selected one." },
"world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." },
"creative": { "type": "boolean", "description": "Creative mode for a new world." },
"join": { "type": "string", "description": "Join a friend's world with its invite code. Only when the player asks." },
@@ -68,6 +70,11 @@ impl Session {
}
let tag = backend::resolve_version(arg_str(args, "version"))?;
let mut cmd = backend::client(&tag)?;
let instance = match arg_str(args, "instance") {
Some(name) => instances::find(name)?,
None => instances::selected(),
};
instances::apply(&mut cmd, &instance)?;
cmd.args(game_tools::control_args());
if let Some(world) = arg_str(args, "world") {
cmd.arg("--world").arg(world);
+5 -1
View File
@@ -135,7 +135,11 @@ pub fn load(work: &Path) -> Result<Imported, String> {
/// Every imported pack, by name.
pub fn list() -> Vec<Imported> {
let mut packs: Vec<Imported> = fs::read_dir(ports_dir())
list_in(&ports_dir())
}
pub(crate) fn list_in(ports: &Path) -> Vec<Imported> {
let mut packs: Vec<Imported> = fs::read_dir(ports)
.into_iter()
.flatten()
.flatten()
+1
View File
@@ -132,6 +132,7 @@ impl Launcher {
self.mods.report_list.reset();
self.packs = modpacks::list();
self.registry_packs = horizon_pack::list();
self.reload_instances();
if self.pack_open.is_none() {
self.pack_open = self.packs.first().map(|p| p.slug.clone());
}
+12 -2
View File
@@ -32,10 +32,13 @@ pub(super) enum Field {
Port,
Token,
Email,
/// The instance dialog's (`instances_page.rs`).
InstanceName,
InstanceGroup,
}
impl Field {
const ALL: [Field; 9] = [
const ALL: [Field; 11] = [
Field::Name,
Field::Seed,
Field::Players,
@@ -45,6 +48,8 @@ impl Field {
Field::Port,
Field::Token,
Field::Email,
Field::InstanceName,
Field::InstanceGroup,
];
}
@@ -163,7 +168,7 @@ pub(super) struct Servers {
focus: HashMap<Field, FocusHandle>,
focused: Option<Field>,
/// The field to put the keyboard in on the next frame.
focus_soon: Option<Field>,
pub(super) focus_soon: Option<Field>,
/// A suggested value shown selected: the first key typed replaces it.
selected: Option<Field>,
/// A field whose value was refused, and why: shown under it until it's edited.
@@ -961,11 +966,15 @@ impl Launcher {
command,
);
match typed {
Key::Enter if matches!(f, Field::InstanceName | Field::InstanceGroup) => {
this.save_instance(cx)
}
Key::Enter => this.field_enter(f),
Key::Escape => {
if this.servers.create.is_some() && !this.servers.creating {
this.servers.create = None;
}
this.instance_escape();
window.blur();
}
Key::Paste => {
@@ -1017,6 +1026,7 @@ impl Launcher {
Field::Port => self.save_port(),
Field::Token => self.save_token(),
Field::Email => self.invite_friend(),
Field::InstanceName | Field::InstanceGroup => {}
}
}
+62
View File
@@ -401,3 +401,65 @@ class KnownFlakyTests(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
class WorkspaceManifestTests(unittest.TestCase):
"""A crate split's Cargo.toml and Cargo.lock changes don't select every harness; a dependency change still does."""
CLIENT = '[package]\nname = "horizon-client"\n\n[dependencies]\nserde = "1"\nwgpu = { version = "27", features = ["x"] }\n'
LOCK = ('version = 4\n\n[[package]]\nname = "horizon-client"\nversion = "0.1.0"\ndependencies = [\n "serde",\n]\n\n'
'[[package]]\nname = "serde"\nversion = "1.0.1"\nsource = "registry+https://github.com/rust-lang/crates.io-index"\n')
def verdict(self, base, head):
"""base, head: {path: text or None}; the manifests workspace_only_manifests leaves out."""
with tempfile.TemporaryDirectory() as temp, \
mock.patch.object(parity, "ROOT", Path(temp)), \
mock.patch.object(parity, "git_show", lambda _base, path: base.get(path)):
for path, text in head.items():
if text is not None:
Path(temp, path).parent.mkdir(parents=True, exist_ok=True)
Path(temp, path).write_text(text)
return parity.workspace_only_manifests(set(head) | set(base), "base")
def test_a_crate_split_is_left_out(self):
command = '[package]\nname = "horizon-command"\n\n[dependencies]\nserde = "1"\nhorizon-core = { path = "../horizon-core" }\n'
client = self.CLIENT + 'horizon-command = { path = "../horizon-command" }\n'
lock = self.LOCK.replace('[[package]]\nname = "serde"', '[[package]]\nname = "horizon-command"\nversion = "0.1.0"\n\n'
'[[package]]\nname = "serde"')
base = {"Cargo.toml": '[workspace]\nmembers = ["crates/horizon-client"]\nresolver = "2"\n',
"crates/horizon-client/Cargo.toml": self.CLIENT, "Cargo.lock": self.LOCK}
head = {"Cargo.toml": '[workspace]\nmembers = ["crates/horizon-client", "crates/horizon-command"]\nresolver = "2"\n',
"crates/horizon-client/Cargo.toml": client, "crates/horizon-command/Cargo.toml": command, "Cargo.lock": lock}
self.assertEqual(self.verdict(base, head), set(head))
def test_a_dependency_change_still_counts(self):
base = {"crates/horizon-client/Cargo.toml": self.CLIENT, "Cargo.lock": self.LOCK}
bumped = {"crates/horizon-client/Cargo.toml": self.CLIENT, "Cargo.lock": self.LOCK.replace("1.0.1", "1.0.2")}
self.assertEqual(self.verdict(base, bumped), set())
feature = {"crates/horizon-client/Cargo.toml": self.CLIENT.replace('["x"]', '["x", "y"]')}
self.assertEqual(self.verdict({"crates/horizon-client/Cargo.toml": self.CLIENT}, feature), set())
resolver = {"Cargo.toml": '[workspace]\nmembers = ["a"]\nresolver = "3"\n'}
self.assertEqual(self.verdict({"Cargo.toml": '[workspace]\nmembers = ["a"]\nresolver = "2"\n'}, resolver), set())
def test_a_feature_of_a_workspace_crate_counts_through_its_sources(self):
items = '[package]\nname = "horizon-items"\n\n[features]\ntest-support = []\n'
client = self.CLIENT + '\n[dev-dependencies]\nhorizon-items = { path = "../horizon-items", features = ["test-support"] }\n'
head = {"crates/horizon-items/Cargo.toml": items, "crates/horizon-client/Cargo.toml": client,
"crates/horizon-items/src/lib.rs": '#[cfg(feature = "test-support")]\npub fn for_tests() {}\n'}
base = {"crates/horizon-client/Cargo.toml": self.CLIENT}
# The new crate's files are all changed, the code the feature gates with them.
self.assertEqual(self.verdict(base, head), {"crates/horizon-items/Cargo.toml", "crates/horizon-client/Cargo.toml"})
# Turning on a feature of a crate whose gated code didn't change selects as before.
world = '[package]\nname = "horizon-world"\n\n[features]\nextra = ["more"]\nmore = []\n'
with tempfile.TemporaryDirectory() as temp, mock.patch.object(parity, "ROOT", Path(temp)):
Path(temp, "crates/horizon-world/src").mkdir(parents=True)
Path(temp, "crates/horizon-world/Cargo.toml").write_text(world)
Path(temp, "crates/horizon-world/src/lib.rs").write_text('#[cfg(feature = "more")]\nfn x() {}\n')
self.assertFalse(parity.feature_sources_changed("horizon-world", "extra", {"crates/horizon-client/Cargo.toml"}))
self.assertTrue(parity.feature_sources_changed("horizon-world", "extra", {"crates/horizon-world/src/lib.rs"}))
self.assertFalse(parity.feature_sources_changed("horizon-nothing", "extra", set()))
# A feature that reaches an external package counts.
optional = {"crates/horizon-client/Cargo.toml": self.CLIENT + '\n[features]\nfast = ["wgpu/x"]\n'}
self.assertEqual(self.verdict({"crates/horizon-client/Cargo.toml": self.CLIENT}, optional), set())
def test_without_a_base_everything_counts(self):
self.assertEqual(parity.workspace_only_manifests({"Cargo.lock"}, None), set())
+100 -1
View File
@@ -1246,6 +1246,101 @@ def trace_main(output, script, arguments):
# Files every harness's result depends on (part of environment_key): a change to one affects them all.
SHARED_INPUTS = {"research-lock.json", "Cargo.lock"}
# Manifest sections that say what a crate is and where its targets are, not what it builds with.
MANIFEST_SECTION_KEPT = re.compile(r"\[\[?(?:package|lib|bin|example|test|bench|lints|badges)\b[^\]]*\]\]?$")
WORKSPACE_CRATE = r"(horizon[\w-]*|cargo-horizon-mod|xtask)"
# A workspace crate named as a dependency (by path, or from the workspace's own table) without choosing its features,
# or listed as a member.
WORKSPACE_LINE = re.compile(WORKSPACE_CRATE + r'\s*=\s*(?:\{(?![^}]*\bfeatures\b)[^}]*\b(?:path|workspace)\s*=[^}]*\}|true)'
r'|' + WORKSPACE_CRATE + r'\.workspace\s*=\s*true|"crates/[^"]+",?')
# A workspace crate named as a dependency with some of its features turned on.
WORKSPACE_FEATURES = re.compile(WORKSPACE_CRATE + r'\s*=\s*\{(?=[^}]*\b(?:path|workspace)\s*=)(?![^}]*default-features)'
r'[^}]*\bfeatures\s*=\s*\[([^\]]*)\][^}]*\}')
def git_show(base, path):
"""path's content at commit base, or None where it didn't exist."""
result = subprocess.run(["git", "show", f"{base}:{path}"], cwd=ROOT, capture_output=True, text=True)
return result.stdout if result.returncode == 0 else None
def manifest_lines(text):
"""A Cargo.toml's lines that decide what is built: (section, line) pairs, without its package's identity and
targets, comments, or workspace crates (whose code counts through its own sources)."""
lines, section = set(), ""
name = re.search(r'^\[package\][^\[]*?^name\s*=\s*"([^"]+)"', text or "", re.M | re.S)
for raw in (text or "").splitlines():
line = re.sub(r"\s+", " ", raw.split("#", 1)[0]).strip()
if not line:
continue
if line.startswith("["):
# A crate's features are its own: the same line in two crates means two things.
section = f"[features] of {name.group(1) if name else '?'}" if line == "[features]" else line
continue
if MANIFEST_SECTION_KEPT.match(section) or WORKSPACE_LINE.fullmatch(line) or \
section == "[workspace]" and (line.startswith("members =") or line.startswith('"') or line == "]"):
continue
lines.add((section, line))
return lines
def lock_packages(text):
"""Cargo.lock's packages from a registry or git (with their versions and checksums); workspace crates' entries
only list what their manifests say."""
return {block.strip() for block in (text or "").split("[[package]]") if "\nsource = " in block}
def workspace_only_manifests(changed, base):
"""The changed Cargo.lock and Cargo.toml files whose changes only add, remove or move workspace crates (a crate
split): no external package, version, feature, or build setting changed across them. Their crates' code counts
through its own sources, so these files don't make every harness linking the crates rerun."""
manifests = sorted(path for path in changed if path == "Cargo.lock" or path.endswith("Cargo.toml"))
if not manifests or base is None:
return set()
if "Cargo.lock" in manifests and \
lock_packages(git_show(base, "Cargo.lock")) != lock_packages((ROOT / "Cargo.lock").read_text(encoding="utf-8")):
return set()
tomls = [path for path in manifests if path != "Cargo.lock"]
before = set().union(*(manifest_lines(git_show(base, path)) for path in tomls)) if tomls else set()
after = set().union(*(manifest_lines((ROOT / path).read_text(encoding="utf-8") if (ROOT / path).exists() else None)
for path in tomls)) if tomls else set()
# Workspace crates' features that a changed line defines or turns on: they change what compiles of that crate's
# sources, which is fine only where every source naming them changed too (a split: the crate's files are new).
gated = set()
for section, line in before ^ after:
wanted = WORKSPACE_FEATURES.fullmatch(line)
if wanted:
gated |= {(wanted.group(1), feature) for feature in re.findall(r'"([^"]+)"', wanted.group(2))}
elif section.startswith("[features] of ") and re.fullmatch(r'[\w-]+ = \[(?: ?"[\w-]+",?)*\s*\]', line):
gated.add((section[len("[features] of "):], line.split(" ", 1)[0]))
else:
return set() # an external package, a feature reaching one ("dep:", "crate/feature"), a build setting
return set(manifests) if all(feature_sources_changed(crate, feature, changed) for crate, feature in gated) else set()
def feature_sources_changed(crate, feature, changed):
"""Whether every Rust source of workspace crate `crate` that names `feature`, or a feature it turns on, is in
changed (False where the crate isn't found)."""
listed = subprocess.run(["git", "ls-files", "*Cargo.toml"], cwd=ROOT, capture_output=True, text=True)
manifests = [ROOT / path for path in listed.stdout.split()] if listed.returncode == 0 else list(ROOT.rglob("Cargo.toml"))
for manifest in manifests:
text = manifest.read_text(encoding="utf-8") if manifest.exists() else ""
if re.search(r'^\[package\][^\[]*?^name\s*=\s*"' + re.escape(crate) + '"', text, re.M | re.S):
break
else:
return False
table = re.search(r"^\[features\]\n(.*?)(?=^\[|\Z)", text, re.M | re.S)
implies = {name: re.findall(r'"([^"]+)"', value) for name, value in
re.findall(r'^([\w-]+)\s*=\s*\[([^\]]*)\]', table.group(1) if table else "", re.M)}
names, todo = set(), [feature]
while todo:
name = todo.pop()
if name not in names:
names.add(name)
todo += [implied for implied in implies.get(name, []) if "/" not in implied and ":" not in implied]
named = re.compile(r'feature\s*=\s*"(?:' + "|".join(map(re.escape, sorted(names))) + r')"')
return all(path.relative_to(ROOT).as_posix() in changed for path in manifest.parent.rglob("*.rs")
if named.search(path.read_text(encoding="utf-8", errors="replace")))
def changed_files(ref):
@@ -1449,7 +1544,11 @@ def main():
if args.changed:
merge_base = subprocess.run(["git", "merge-base", "HEAD", args.changed], cwd=ROOT, capture_output=True, text=True)
base = merge_base.stdout.strip() or None
affected = affected_harnesses(found, records, changed, reach=not args.by_crate, base=base)
moved = workspace_only_manifests(changed, base) if not args.by_crate else set()
if moved:
print(f"{', '.join(sorted(moved))}: only workspace crates added, removed or moved; their sources count "
"instead", flush=True)
affected = affected_harnesses(found, records, changed - moved, reach=not args.by_crate, base=base)
chosen = [name for name in found if name in affected and stale(name, state, hasher, environment)]
print(f"{len(changed)} files changed{since}: {len(affected)} harnesses "
f"depend on them, {len(chosen)} without a pass for their current inputs.", flush=True)
+2 -2
View File
@@ -180,9 +180,9 @@ def main():
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work,
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
+2 -2
View File
@@ -79,9 +79,9 @@ def main():
run(['java', '-Xmx3G', '-Duser.timezone=UTC', '-cp', os.pathsep.join([str(classes), str(jars['server']), dependency_path]),
'dev.horizonlab.parity.VanillaCommandExecOracle', vanilla_dir / 'universe', script_path, build / 'vanilla.jsonl', SEED], 'java', cwd=vanilla_dir)
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], 'compile-rust', cwd=lab.ROOT)
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], 'compile-rust', cwd=lab.ROOT)
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
rust_dir = build / 'rust'
shutil.rmtree(rust_dir, ignore_errors=True)
rust_dir.mkdir()
+2 -2
View File
@@ -64,9 +64,9 @@ def main():
registries = json.loads((build / 'registries.json').read_text())
corpus = corpus_module.corpus(tree, registries)
(build / 'corpus.txt').write_text(''.join(line + '\n' for line in corpus), encoding='utf-8')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
resources = lab.RESOURCES
total_failures = 0
summary = []
+2 -2
View File
@@ -122,9 +122,9 @@ def main():
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work,
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
+2 -2
View File
@@ -242,9 +242,9 @@ def main():
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work,
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
+2 -2
View File
@@ -424,11 +424,11 @@ def main():
oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
build, 'compile-java')
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
oh.run_logged(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.RESOURCES, '--dedicated', '--nogui']
+2 -2
View File
@@ -417,9 +417,9 @@ def main():
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work,
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
+2 -2
View File
@@ -56,9 +56,9 @@ def main():
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
run([binary, 'enchanting_fixture',resources, inputs, build / 'rust.txt'], 'rust')
references = []
for side in ['server']:
+2 -2
View File
@@ -139,9 +139,9 @@ def main():
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/client_probe'
binary = Path(metadata['target_directory']) / 'fast/examples/client_probe'
run([binary, 'entity_death_loot_fixture', resources, inputs, build / 'rust.txt'], 'rust')
errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')]
if errors:
+2 -2
View File
@@ -148,9 +148,9 @@ def main():
print(f'{len(vanilla)} oracle lines')
return
halloween = vanilla[0].split()[1]
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/client_probe'
binary = Path(metadata['target_directory']) / 'fast/examples/client_probe'
run([binary, 'finalize_spawn_fixture', resources, inputs, build / 'rust.txt', halloween], 'rust')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
+21 -1
View File
@@ -137,6 +137,24 @@ def guest_pos(host, name):
return next(g['position'] for g in guests if g['name'] == name)
def open_ground(host, guest, name):
"""Puts the guest on a cleared, flat floor beside the host and returns where it stands.
A player new to the world spawns at a random free spot near the world spawn, as in vanilla
(`PlayerSpawnFinder`), often against a hill: walking and aiming need known, open ground.
Commands, not the control socket: the server has the last word on where the guest stands.
"""
hp = host('status')['player']['position']
x, y, z = math.floor(hp[0]) - 6, math.floor(hp[1]), math.floor(hp[2])
host(f'command fill {x - 2} {y - 1} {z - 2} {x + 4} {y - 1} {z + 8} minecraft:stone')
host(f'command fill {x - 2} {y} {z - 2} {x + 4} {y + 3} {z + 8} minecraft:air')
spot = [x + 0.5, float(y), z + 0.5]
host(f'command tp {name} {spot[0]} {spot[1]} {spot[2]} 0 0')
guest.wait('status', lambda v: math.dist(v['player']['position'], spot) < 0.01 and v['player']['on_ground'], 20,
'the guest on its ground')
return spot
def play_together(host, guest, name, round_index):
"""Chat, movement and blocks seen from both sides."""
host.wait('lan status', lambda v: any(g['name'] == name and g['placed'] for g in v['guests']), 60,
@@ -150,6 +168,7 @@ def play_together(host, guest, name, round_index):
guest.wait('status', lambda v: any(f'hello from the host {round_index}' in l for l in v['server']['chat']), 30,
'host chat on the guest')
# The guest walks; the host sees it move.
open_ground(host, guest, name)
before = guest_pos(host, name)
guest('look 0 0')
guest('key w down')
@@ -167,7 +186,8 @@ def play_together(host, guest, name, round_index):
guest.wait('status', lambda v: any(math.dist(p, target) < 0.6 for p in v['server']['player_positions']), 20,
'host movement on the guest')
# A block the host places, which the guest sees and then breaks.
gp = guest('status')['player']['position']
gp = guest.wait('status', lambda v: v['player']['on_ground'] and math.hypot(v['player']['velocity'][0],
v['player']['velocity'][2]) < 1e-3, 10, 'the guest standing still')['player']['position']
feet = [math.floor(gp[0]), math.floor(gp[1]), math.floor(gp[2])]
block = [feet[0] + 2, feet[1] + 1, feet[2]]
# Clear the line of sight (the test terrain has hills), then the block at eye level.
+2 -2
View File
@@ -258,12 +258,12 @@ def sides(name):
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
cwd=lab.ROOT, check=True, capture_output=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
+2 -2
View File
@@ -167,9 +167,9 @@ def main():
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work,
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
+2 -2
View File
@@ -525,7 +525,7 @@ def main():
'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world],
build, 'vanilla', timeout=3600)
if not args.java_only:
command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'client_probe']
command = ['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe']
target, env = lab.cargo_target(), None
if args.trace:
target = lab.LOCAL / 'mob-ai-trace-target'
@@ -533,7 +533,7 @@ def main():
env = dict(os.environ, CARGO_TARGET_DIR=str(target), CARGO_PROFILE_RELEASE_DEBUG='line-tables-only',
CARGO_PROFILE_RELEASE_LTO='false', CARGO_PROFILE_RELEASE_CODEGEN_UNITS='16')
oracle_harness.run_logged(command, build, 'compile-rust', env=env)
binary = target / 'release/examples/client_probe'
binary = target / 'fast/examples/client_probe'
oracle_harness.run_logged([binary, 'mob_ai_probe', lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon')
if args.java_only:
return
+2 -2
View File
@@ -62,8 +62,8 @@ def main():
subprocess.run(list(map(str, cmd)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaMobAttributesOracle', build / 'vanilla.txt'], 'java')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
binary = lab.cargo_target() / 'release/examples/client_probe'
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
binary = lab.cargo_target() / 'fast/examples/client_probe'
resources = lab.RESOURCES
run([binary, 'mob_attributes_fixture', resources, build / 'rust.txt'], 'rust')
vanilla, rust = parse(build / 'vanilla.txt'), parse(build / 'rust.txt')
+2 -2
View File
@@ -568,9 +568,9 @@ def main():
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/client_probe'
binary = Path(metadata['target_directory']) / 'fast/examples/client_probe'
run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
+2 -2
View File
@@ -351,11 +351,11 @@ def main():
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
oh.run_logged(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
services = Services()
+2 -2
View File
@@ -335,9 +335,9 @@ def main():
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaRaidOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/client_probe'
binary = Path(metadata['target_directory']) / 'fast/examples/client_probe'
run([binary, 'raid_fixture', resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
+2 -2
View File
@@ -250,9 +250,9 @@ def main():
inputs = build / 'inputs.jsonl'
inputs.write_text(''.join(json.dumps(c, ensure_ascii=False) + '\n' for c in chosen), encoding='utf-8')
run([*oracle, 'run', inputs, build / 'vanilla.jsonl'], 'vanilla')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
run([binary, 'scoreboard_fixture',build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust')
read = lambda p: [json.loads(l) for l in p.read_text(encoding='utf-8').splitlines()]
vanilla, rust = read(build / 'vanilla.jsonl'), read(build / 'rust.jsonl')
+2 -2
View File
@@ -336,9 +336,9 @@ def main():
'dev.horizonlab.parity.VanillaSculkOracle', inputs, build / 'vanilla.txt'],
build, 'vanilla', timeout=3600)
if not args.java_only:
oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'],
oracle_harness.run_logged(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'],
build, 'compile-rust')
oracle_harness.run_logged([lab.cargo_target() / 'release/horizon-client', '--resources', resources], build, 'horizon',
oracle_harness.run_logged([lab.cargo_target() / 'fast/horizon-client', '--resources', resources], build, 'horizon',
env=lab.game_env(HORIZON_SCULK_FIXTURE=f'{inputs},{build / "horizon.txt"}'))
if args.java_only:
return
+2 -2
View File
@@ -254,11 +254,11 @@ def main():
oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
build, 'compile-java')
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
oh.run_logged(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
java = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.SecureChatClient']
oh.run_logged([*java, 'keys', build], build, 'keys')
@@ -118,12 +118,12 @@ def main():
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
cwd=lab.ROOT, check=True, capture_output=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
+2 -2
View File
@@ -101,12 +101,12 @@ def main():
# SERVER_DRAGON_SIDES=vanilla (or horizon) runs one side and reads the other's last transcript.
sides = [s for s in os.environ.get('SERVER_DRAGON_SIDES', 'vanilla,horizon').split(',') if s]
if 'horizon' in sides:
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies,
+2 -2
View File
@@ -157,12 +157,12 @@ def main():
# SERVER_ENTITIES_SIDES=vanilla (or horizon) runs one side and reads the other's last transcript.
sides = [s for s in os.environ.get('SERVER_ENTITIES_SIDES', 'vanilla,horizon').split(',') if s]
if 'horizon' in sides:
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies,
+2 -2
View File
@@ -334,12 +334,12 @@ def main():
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
cwd=lab.ROOT, check=True, capture_output=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.KnockbackClient']
+2 -2
View File
@@ -118,12 +118,12 @@ def main():
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
cwd=lab.ROOT, check=True, capture_output=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
+2 -2
View File
@@ -169,12 +169,12 @@ def main():
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
cwd=lab.ROOT, check=True, capture_output=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
+2 -2
View File
@@ -134,9 +134,9 @@ def main():
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
cwd=lab.ROOT, check=True, capture_output=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
binary = lab.cargo_target() / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = lab.cargo_target() / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.ServerPackClient']
+2 -2
View File
@@ -130,11 +130,11 @@ def main():
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main',
'nogui']
+2 -2
View File
@@ -155,9 +155,9 @@ def main():
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/client_probe'
binary = Path(metadata['target_directory']) / 'fast/examples/client_probe'
run([binary, 'spawn_rules_fixture', resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
+2 -2
View File
@@ -249,9 +249,9 @@ def main():
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/client_probe'
binary = Path(metadata['target_directory']) / 'fast/examples/client_probe'
run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
+2 -2
View File
@@ -133,9 +133,9 @@ def main():
*(PARITY / f'{n}.java' for n in ('ParityFont', 'VanillaSubtitleOracle'))], 'compile-java')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSubtitleOracle',
inputs, build / 'vanilla.jsonl'], 'vanilla')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
run([binary, 'subtitle_fixture',resources, inputs, build / 'rust.jsonl'], 'rust')
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text(encoding='utf-8').splitlines()]
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text(encoding='utf-8').splitlines()]
+2 -2
View File
@@ -84,9 +84,9 @@ def main():
PARITY / 'VanillaTeamRulesOracle.java'], 'compile-java')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTeamRulesOracle',
inputs, build / 'vanilla.jsonl'], 'vanilla')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
binary = Path(metadata['target_directory']) / 'fast/examples' / ('client_probe.exe' if os.name=='nt' else 'client_probe')
run([binary, 'team_rules_fixture',inputs, build / 'rust.jsonl'], 'rust')
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
+2 -2
View File
@@ -219,8 +219,8 @@ def main():
if args.java_only:
print(f'{len(vanilla)} oracle lines')
return
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
binary = lab.cargo_target() / 'release/examples/client_probe'
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
binary = lab.cargo_target() / 'fast/examples/client_probe'
run([binary, 'trading_fixture', resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
+2 -2
View File
@@ -214,9 +214,9 @@ def main():
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/client_probe'
binary = Path(metadata['target_directory']) / 'fast/examples/client_probe'
run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
+2 -2
View File
@@ -405,9 +405,9 @@ def main():
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
d.run(['cargo', 'build', '-q', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
d.run([str(lab.cargo_target() / 'fast/horizon-client'), '--resources', str(resources)], cwd=work,
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
+2 -2
View File
@@ -205,11 +205,11 @@ def main():
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = Path(metadata['target_directory']) / 'fast' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
services = Services()
discovery = services.url + '/minecraft/client'
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
+2 -2
View File
@@ -190,9 +190,9 @@ def main():
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--example', 'client_probe'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/client_probe'
binary = Path(metadata['target_directory']) / 'fast/examples/client_probe'
run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
+4 -4
View File
@@ -69,10 +69,10 @@ def seeds(count):
return SEEDS + [rng.randrange(-2**63, 2**63) for _ in range(count)]
def target_dir():
def target_dir(profile='release'):
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
return Path(metadata['target_directory']) / 'release'
return Path(metadata['target_directory']) / profile
def origins(build, classes, dependencies, all_seeds):
@@ -134,9 +134,9 @@ def main():
if args.origins_only:
sys.exit(1 if origin_diffs else 0)
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
oh.run_logged(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
'compile-rust', timeout=3600)
binary = target_dir() / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
binary = target_dir('fast') / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
# 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']