Merge remote-tracking branch 'origin/main' into fix/harness-await-flakes
This commit is contained in:
@@ -8,7 +8,7 @@ name: nightly audit
|
||||
# gh workflow run "nightly audit" -f dry_run=true # the audit, without touching issues
|
||||
on:
|
||||
schedule:
|
||||
# GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:00 in Paris.
|
||||
# GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:07 in Paris today.
|
||||
- cron: '7 1 * * *'
|
||||
- cron: '7 2 * * *'
|
||||
workflow_dispatch:
|
||||
@@ -31,14 +31,19 @@ jobs:
|
||||
audit:
|
||||
# The Mac mini's runners only: the audit compares with the previous one, so it stays on one platform.
|
||||
runs-on: [self-hosted, horizon-game, macOS]
|
||||
timeout-minutes: 150
|
||||
timeout-minutes: 240 # every harness (~80 min) plus lan_integration (~40 min an attempt under load, retried)
|
||||
steps:
|
||||
- name: 03:00 in Paris
|
||||
- name: 03:07 in Paris
|
||||
id: when
|
||||
env:
|
||||
SCHEDULE: ${{ github.event.schedule }}
|
||||
run: |
|
||||
hour=$(TZ=Europe/Paris date +%H)
|
||||
if [[ "${{ github.event_name }}" == schedule && "$hour" != 03 ]]; then
|
||||
echo "It is ${hour}:00 in Paris: the other schedule runs the audit."
|
||||
# Which cron is 03:07 in Paris, from Paris's offset today: GitHub can start a schedule hours late, so the
|
||||
# clock at start time can't tell (on 2026-10-26 both started after 04:00 Paris and both skipped).
|
||||
offset=$(TZ=Europe/Paris date +%z)
|
||||
ours=$([ "$offset" = +0200 ] && echo '7 1 * * *' || echo '7 2 * * *')
|
||||
if [[ "${{ github.event_name }}" == schedule && "$SCHEDULE" != "$ours" ]]; then
|
||||
echo "Paris is at UTC${offset} today: the '$ours' schedule runs the audit."
|
||||
echo "run=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "run=true" >> "$GITHUB_OUTPUT"
|
||||
@@ -66,7 +71,8 @@ jobs:
|
||||
run: |
|
||||
echo "since=$(date +%Y-%m-%dT%H:%M:%S)" >> "$GITHUB_OUTPUT"
|
||||
set +e
|
||||
python3 tools/parity.py --all --timeout 1800 2>&1 | tee "$RUNNER_TEMP/audit.log"
|
||||
# lan_integration (the whole lan_e2e suite) takes ~2,400 s under load, past the usual 1,800.
|
||||
python3 tools/parity.py --all --timeout 3000 2>&1 | tee "$RUNNER_TEMP/audit.log"
|
||||
echo "exit=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
{ echo '```'; tail -40 "$RUNNER_TEMP/audit.log"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Issues for the harnesses that regressed
|
||||
|
||||
@@ -66,7 +66,7 @@ cargo build --profile fast -p horizon-client # optimized, quick to link:
|
||||
python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job)
|
||||
python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them
|
||||
python3 tools/parity.py mob_ai sculk # named harnesses
|
||||
python3 tools/lan_e2e.py --check chest # two real games over LAN (host in-frame); --server-thread for the host on its server thread
|
||||
python3 tools/lan_e2e.py --check chest # two real games over LAN (server-thread host); --in-frame compares the fallback
|
||||
python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
|
||||
```
|
||||
|
||||
@@ -156,7 +156,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
|
||||
exactly as a LAN guest or a dedicated server's player does. This is what players run. Open
|
||||
`[server-thread]` issues list the gaps left.
|
||||
2. **In-frame (`--in-frame`, `--no-server-thread` or `HORIZON_SERVER_THREAD=0`):** the window's `Game` ticks
|
||||
the world itself, one level that follows the player (`fn enter_dimension`). Most harnesses test this path.
|
||||
the world itself, one level that follows the player (`fn enter_dimension`). Deterministic rule fixtures still use this path; player-facing integration uses the default server thread.
|
||||
|
||||
LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths
|
||||
when you touch player-facing gameplay:
|
||||
@@ -164,8 +164,8 @@ when you touch player-facing gameplay:
|
||||
```sh
|
||||
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # server thread
|
||||
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --in-frame # in-frame
|
||||
python3 tools/lan_e2e.py --check <name> # host in-frame, guest is a server client
|
||||
python3 tools/lan_e2e.py --server-thread --check <name> # host on its server thread (portals, levels, distance, lava need it)
|
||||
python3 tools/lan_e2e.py --check <name> # host on its server thread, guest is a server client
|
||||
python3 tools/lan_e2e.py --in-frame --check <name> # comparison (portals, levels, distance, lava need server-thread mode)
|
||||
python3 tools/parity.py dedicated_server server_entities server_player_damage
|
||||
```
|
||||
|
||||
|
||||
Generated
+15
@@ -1437,6 +1437,7 @@ dependencies = [
|
||||
name = "horizon-mods"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-shader-api",
|
||||
"log",
|
||||
"minisign-verify",
|
||||
"serde",
|
||||
@@ -2082,6 +2083,13 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minimap"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"horizon-mod-sdk",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minisign-verify"
|
||||
version = "0.3.0"
|
||||
@@ -4287,6 +4295,13 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "welcome"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-mod-sdk",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wgpu"
|
||||
version = "30.0.1"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[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-world", "crates/horizon-client", "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", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/zoom", "xtask"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "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", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! `cargo horizon-mod check <file>`: what the registry checks of a submission,
|
||||
//! run anywhere: its kind's own checks (docs/api/mod-index.md), its signature
|
||||
//! when given a key, and for a mod a trial run in the sandbox: it must start,
|
||||
//! survive ticks, frames, a chat line and each of its commands, and import
|
||||
//! no more than its capabilities.
|
||||
//! survive ticks, frames, a chat line and each of its commands (a server mod:
|
||||
//! a player joining, chatting, typing them and leaving), and import no more
|
||||
//! than its capabilities.
|
||||
use horizon_mods::{
|
||||
Clock, Mods, Output, Package, Player, Snapshot, Status,
|
||||
Clock, GameMode, Mods, Output, Package, Player, ServerPlayer, Snapshot, Status,
|
||||
index::{self, Facts, Kind},
|
||||
manifest::component_imports,
|
||||
};
|
||||
@@ -69,6 +70,8 @@ impl Report {
|
||||
if let Some(side) = f.side {
|
||||
let side = serde_json::to_value(side).unwrap_or_default();
|
||||
out += &format!(", API {}, {}", f.api, side.as_str().unwrap_or("?"));
|
||||
} else if self.kind == Kind::Shader {
|
||||
out += &format!(", shader API {}", f.api);
|
||||
} else if !f.api.is_empty() {
|
||||
out += &format!(", format {}", f.api);
|
||||
}
|
||||
@@ -113,6 +116,7 @@ pub fn kind_of(path: &Path) -> Option<Kind> {
|
||||
"hmod" => Some(Kind::Mod),
|
||||
"hpack" => Some(Kind::Modpack),
|
||||
"zip" => Some(Kind::ResourcePack),
|
||||
"hshader" => Some(Kind::Shader),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -191,40 +195,66 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
|
||||
if let Some(reason) = failed(&mods) {
|
||||
return Err(format!("it didn't start: {reason}"));
|
||||
}
|
||||
report.commands = mods.commands().map(str::to_owned).collect();
|
||||
let client: Vec<String> = mods.commands().map(str::to_owned).collect();
|
||||
let server: Vec<String> = mods.server_commands().map(str::to_owned).collect();
|
||||
report.commands = [client.clone(), server.clone()].concat();
|
||||
// A server mod plays with one player on, who joins, chats and leaves.
|
||||
let steve = ServerPlayer {
|
||||
id: "00000000-0000-4000-8000-000000000001".into(),
|
||||
name: "Steve".into(),
|
||||
x: 0.5,
|
||||
y: 64.0,
|
||||
z: 0.5,
|
||||
dimension: "minecraft:overworld".into(),
|
||||
game_mode: GameMode::Survival,
|
||||
health: 20.0,
|
||||
};
|
||||
let snapshot = |t: u64| Snapshot {
|
||||
player: Some(Player {
|
||||
x: 0.5 + t as f64 * 0.1,
|
||||
y: 64.0,
|
||||
z: 0.5,
|
||||
yaw: 90.0,
|
||||
pitch: 0.0,
|
||||
health: 20.0,
|
||||
food: 20,
|
||||
dimension: "minecraft:overworld".into(),
|
||||
}),
|
||||
clock: Some(Clock {
|
||||
game_time: t,
|
||||
day_time: 1000 + t,
|
||||
}),
|
||||
players: vec![steve.clone()],
|
||||
// The GUI of a 1280 x 720 window at scale 3.
|
||||
gui_size: (427.0, 240.0),
|
||||
..Snapshot::default()
|
||||
};
|
||||
mods.set_snapshot(snapshot(0));
|
||||
mods.player_joined(&steve);
|
||||
for t in 0..TICKS {
|
||||
mods.set_snapshot(Snapshot {
|
||||
player: Some(Player {
|
||||
x: 0.5 + t as f64 * 0.1,
|
||||
y: 64.0,
|
||||
z: 0.5,
|
||||
yaw: 90.0,
|
||||
pitch: 0.0,
|
||||
health: 20.0,
|
||||
food: 20,
|
||||
dimension: "minecraft:overworld".into(),
|
||||
}),
|
||||
clock: Some(Clock {
|
||||
game_time: t,
|
||||
day_time: 1000 + t,
|
||||
}),
|
||||
// The GUI of a 1280 x 720 window at scale 3.
|
||||
gui_size: (427.0, 240.0),
|
||||
..Snapshot::default()
|
||||
});
|
||||
mods.set_snapshot(snapshot(t));
|
||||
mods.tick(t);
|
||||
mods.server_tick(t);
|
||||
for _ in 0..FRAMES_PER_TICK {
|
||||
mods.frame(1.0 / 60.0);
|
||||
}
|
||||
}
|
||||
mods.chat("<Steve> hello");
|
||||
for name in report.commands.clone() {
|
||||
mods.command(&name);
|
||||
mods.player_chat(&steve, "hello");
|
||||
for name in &client {
|
||||
mods.command(name);
|
||||
}
|
||||
for name in &server {
|
||||
mods.server_command(&steve, name);
|
||||
}
|
||||
mods.set_snapshot(Snapshot::default());
|
||||
mods.player_left(&steve);
|
||||
for out in mods.drain() {
|
||||
report.output.push(match out {
|
||||
Output::Chat { text, .. } => format!("chat: {text}"),
|
||||
Output::Feedback { text, error } => {
|
||||
Output::Tell { text, .. } => format!("tell: {text}"),
|
||||
Output::Broadcast { text, .. } => format!("broadcast: {text}"),
|
||||
Output::Feedback { text, error } | Output::Reply { text, error, .. } => {
|
||||
format!("{}: {text}", if error { "error" } else { "feedback" })
|
||||
}
|
||||
Output::Command { line } => format!("command: /{line}"),
|
||||
@@ -285,7 +315,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(e.contains("signature"), "{e}");
|
||||
let e = check(&pack, Kind::Shader, None, None).err().unwrap();
|
||||
assert!(e.contains("shader packs open"), "{e}");
|
||||
assert!(e.contains("horizon-shaders.toml"), "{e}");
|
||||
assert!(check(&pack, Kind::Mod, None, None).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -610,12 +610,17 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unreachable_games_fail_with_status_3() {
|
||||
let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None);
|
||||
let home =
|
||||
std::env::temp_dir().join(format!("horizon-ctl-unreachable-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let mut s = Session::new(home.join("nobody.sock"), None);
|
||||
s.home = home.clone();
|
||||
let f = s.run(&["state".to_owned()]).unwrap_err();
|
||||
assert_eq!(f.status, UNREACHABLE);
|
||||
assert_eq!(f.reply["kind"], "connection");
|
||||
let f = s.run(&["sleep".to_owned(), "x".to_owned()]).unwrap_err();
|
||||
assert_eq!(f.status, USAGE);
|
||||
std::fs::remove_dir_all(home).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -10,6 +10,8 @@ use crate::{
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
use horizon_world::block_collision::BlockCollisionRegistry;
|
||||
|
||||
mod fluids;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ItemEntity {
|
||||
pub health: i32,
|
||||
@@ -165,18 +167,16 @@ impl ItemEntity {
|
||||
facts: &BlockFacts,
|
||||
collision: &BlockCollisionRegistry<'_>,
|
||||
no_physics: bool,
|
||||
fluids: &crate::motion::FluidResources,
|
||||
) -> bool {
|
||||
self.ticks += 1;
|
||||
self.previous = self.position;
|
||||
if self.pickup_delay > 0 && self.pickup_delay != u32::MAX {
|
||||
self.pickup_delay -= 1;
|
||||
}
|
||||
let eye = world.block(
|
||||
self.position.x.floor() as i32,
|
||||
(self.position.y + 0.1).floor() as i32,
|
||||
self.position.z.floor() as i32,
|
||||
);
|
||||
let in_water = facts.get(eye).fluid == Fluid::Water;
|
||||
// Entity.baseTick pushes before ItemEntity applies buoyancy and moves.
|
||||
let (water_height, lava_height) = self.update_fluids(world, fluids);
|
||||
let in_water = water_height > f64::from(0.1f32);
|
||||
if in_water {
|
||||
// ItemEntity.setUnderwaterMovement
|
||||
self.velocity = Vec3::new(
|
||||
@@ -184,7 +184,7 @@ impl ItemEntity {
|
||||
self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 },
|
||||
self.velocity.z * 0.99,
|
||||
);
|
||||
} else if facts.get(eye).fluid == Fluid::Lava {
|
||||
} else if lava_height > f64::from(0.1f32) {
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * 0.95,
|
||||
self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 },
|
||||
@@ -245,6 +245,8 @@ impl ItemEntity {
|
||||
}
|
||||
}
|
||||
self.age += 1;
|
||||
// ItemEntity.tick refreshes immersion and pushes again after moving.
|
||||
self.update_fluids(world, fluids);
|
||||
self.age < 6000 && self.position.y > -128.0
|
||||
}
|
||||
/// `ItemEntity.isMergable` at `age`: a stack below its size whose pickup
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Dropped-item immersion and currents through the shared vanilla fluid helpers.
|
||||
use super::ItemEntity;
|
||||
use crate::{
|
||||
motion::{FluidResources, FluidTags, LAVA, WATER},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Direction, Vec3},
|
||||
position::BlockPos,
|
||||
};
|
||||
use horizon_world::{
|
||||
entity_fluid::{
|
||||
CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership,
|
||||
FluidSections, FluidTagId,
|
||||
},
|
||||
fluid::{FluidHeightWorld, FluidKind, FluidState},
|
||||
fluid_flow::{FluidFlowWorld, flow_at},
|
||||
registry::BlockStateId,
|
||||
};
|
||||
type Error = std::convert::Infallible;
|
||||
struct ItemFluidWorld<'a> {
|
||||
item: &'a mut ItemEntity,
|
||||
world: &'a World,
|
||||
fluids: &'a FluidResources,
|
||||
}
|
||||
impl ItemEntity {
|
||||
pub(super) fn update_fluids(&mut self, world: &World, fluids: &FluidResources) -> (f64, f64) {
|
||||
let mut interaction = EntityFluidInteraction::new([WATER, LAVA]);
|
||||
let mut scene = ItemFluidWorld {
|
||||
item: self,
|
||||
world,
|
||||
fluids,
|
||||
};
|
||||
if interaction.update(&mut scene, false, 4096).is_err() {
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
let water_height = interaction.fluid_height(&scene, WATER);
|
||||
let lava_height = interaction.fluid_height(&scene, LAVA);
|
||||
let _ = interaction.apply_current(&mut scene, WATER, 0.014);
|
||||
let _ = interaction.apply_current(
|
||||
&mut scene,
|
||||
LAVA,
|
||||
if world.fast_lava {
|
||||
0.007
|
||||
} else {
|
||||
0.0023333333333333335
|
||||
},
|
||||
);
|
||||
(water_height, lava_height)
|
||||
}
|
||||
}
|
||||
impl FluidMembership for ItemFluidWorld<'_> {
|
||||
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
|
||||
FluidTags.fluid_in_tag(kind, tag)
|
||||
}
|
||||
}
|
||||
impl CurrentTarget for ItemFluidWorld<'_> {
|
||||
type Error = Error;
|
||||
fn is_player_class(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn velocity(&mut self) -> Result<Vec3, Error> {
|
||||
Ok(self.item.velocity)
|
||||
}
|
||||
fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Error> {
|
||||
let v = self.item.velocity;
|
||||
let sum = Vec3::new(v.x + delta.x, v.y + delta.y, v.z + delta.z);
|
||||
if delta.is_finite() && sum.is_finite() {
|
||||
self.item.velocity = sum;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl FluidInteractionWorld for ItemFluidWorld<'_> {
|
||||
type Error = Error;
|
||||
type Chunk = ();
|
||||
fn interaction_box(&mut self) -> Result<Option<Aabb>, Error> {
|
||||
Ok(Some(
|
||||
self.item.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)),
|
||||
))
|
||||
}
|
||||
fn loaded_chunk(&mut self, x: i32, z: i32) -> Result<Option<()>, Error> {
|
||||
Ok(self.world.chunks.contains_key(&(x, z)).then_some(()))
|
||||
}
|
||||
fn chunk_sections(&mut self, _: ()) -> Result<FluidSections<'_>, Error> {
|
||||
static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS];
|
||||
Ok(FluidSections {
|
||||
minimum_section_y: crate::chunk::MIN_Y >> 4,
|
||||
has_fluid: &SECTIONS,
|
||||
})
|
||||
}
|
||||
fn bounding_box_min_y(&self) -> f64 {
|
||||
self.item.position.y
|
||||
}
|
||||
fn block_x(&self) -> i32 {
|
||||
self.item.position.x.floor() as i32
|
||||
}
|
||||
fn eye_y(&mut self) -> Result<f64, Error> {
|
||||
Ok(self.item.position.y + f64::from(0.2125f32))
|
||||
}
|
||||
fn block_z(&self) -> i32 {
|
||||
self.item.position.z.floor() as i32
|
||||
}
|
||||
fn fluid_state(&mut self, p: BlockPos) -> Result<FluidState, Error> {
|
||||
Ok(self.fluids.fluid(self.world.block(p.x, p.y, p.z)))
|
||||
}
|
||||
fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32, Error> {
|
||||
f.height_at(self, [p.x, p.y, p.z])
|
||||
}
|
||||
fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32, Error> {
|
||||
f.camera_height_at(self, [p.x, p.y, p.z])
|
||||
}
|
||||
fn flow(&mut self, f: FluidState, p: BlockPos) -> Result<Vec3, Error> {
|
||||
flow_at(self, f, p)
|
||||
}
|
||||
}
|
||||
impl FluidHeightWorld for ItemFluidWorld<'_> {
|
||||
type Error = Error;
|
||||
fn fluid(&mut self, p: [i32; 3]) -> Result<FluidState, Error> {
|
||||
Ok(self.fluids.fluid(self.world.block(p[0], p[1], p[2])))
|
||||
}
|
||||
fn sturdy_down(&mut self, p: [i32; 3]) -> Result<bool, Error> {
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
Ok(self.fluids.sturdy(state, Direction::Down))
|
||||
}
|
||||
}
|
||||
impl FluidFlowWorld for ItemFluidWorld<'_> {
|
||||
type Error = Error;
|
||||
type Block = BlockStateId;
|
||||
fn fluid(&mut self, p: BlockPos) -> Result<FluidState, Error> {
|
||||
Ok(self.fluids.fluid(self.world.block(p.x, p.y, p.z)))
|
||||
}
|
||||
fn block(&mut self, p: BlockPos) -> Result<BlockStateId, Error> {
|
||||
Ok(self.world.block(p.x, p.y, p.z))
|
||||
}
|
||||
fn blocks_fluid_flow(&self, s: BlockStateId) -> bool {
|
||||
self.fluids.blocks_flow(s)
|
||||
}
|
||||
fn is_ice_class(&self, s: BlockStateId) -> bool {
|
||||
self.fluids.ice(s)
|
||||
}
|
||||
fn is_face_sturdy(
|
||||
&mut self,
|
||||
s: BlockStateId,
|
||||
_: BlockPos,
|
||||
d: Direction,
|
||||
) -> Result<bool, Error> {
|
||||
Ok(self.fluids.sturdy(s, d))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn items_follow_flowing_water_but_still_water_has_no_horizontal_push() {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("movement-properties.nbt").exists() {
|
||||
return;
|
||||
}
|
||||
let assets = crate::assets::Assets::load(&root).unwrap();
|
||||
let render = assets.reload(&root).unwrap();
|
||||
let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap();
|
||||
let fluids = FluidResources::new(&assets, &facts).unwrap();
|
||||
let collision = crate::collisions::load(&root, assets.registry).unwrap();
|
||||
let mut world = World::test_scene(&assets, &render, 3).unwrap();
|
||||
let stone = assets.registry.default_state("minecraft:stone").unwrap();
|
||||
let water = assets.registry.default_state("minecraft:water").unwrap();
|
||||
let mut state = assets.registry.state(water).unwrap().clone();
|
||||
state.properties.insert("level".into(), "1".into());
|
||||
let flowing = assets.registry.resolve(&state).unwrap();
|
||||
for x in 19..=21 {
|
||||
for z in 19..=21 {
|
||||
world.set(x, 3, z, stone).unwrap();
|
||||
world.set(x, 4, z, water).unwrap();
|
||||
}
|
||||
}
|
||||
let at = Vec3::new(20.5, 4.0, 20.5);
|
||||
let item = ItemEntity {
|
||||
id: 1,
|
||||
health: 5,
|
||||
fire_ticks: 0,
|
||||
stack: crate::items::ItemStack {
|
||||
item: "minecraft:sugar_cane".into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
thrower: None,
|
||||
position: at,
|
||||
previous: at,
|
||||
velocity: Vec3::ZERO,
|
||||
on_ground: false,
|
||||
age: 0,
|
||||
pickup_delay: 0,
|
||||
bob_offset: 0.0,
|
||||
ticks: 0,
|
||||
};
|
||||
let mut still = item.clone();
|
||||
assert!(still.tick(&world, &facts, &collision, false, &fluids));
|
||||
assert_eq!(still.position.x, at.x);
|
||||
assert_eq!(still.velocity.x, 0.0);
|
||||
world.set(21, 4, 20, flowing).unwrap();
|
||||
let mut carried = item;
|
||||
assert!(carried.tick(&world, &facts, &collision, false, &fluids));
|
||||
// First push is damped by buoyancy before motion, second follows drag.
|
||||
assert!((carried.position.x - at.x - 0.014 * 0.99).abs() < 1e-12);
|
||||
assert!((carried.velocity.x - (0.014 * 0.99 * 0.98 + 0.014)).abs() < 1e-12);
|
||||
for _ in 0..20 {
|
||||
carried.tick(&world, &facts, &collision, false, &fluids);
|
||||
}
|
||||
assert!(carried.position.x > at.x + 0.5);
|
||||
}
|
||||
}
|
||||
@@ -378,12 +378,6 @@ impl Cps {
|
||||
pub enum Item {
|
||||
Fullbright,
|
||||
DynamicLights,
|
||||
Minimap,
|
||||
MinimapCorner,
|
||||
MinimapSize,
|
||||
MinimapShape,
|
||||
MinimapZoom,
|
||||
MinimapRotate,
|
||||
AutoReconnect,
|
||||
MouseTweaks,
|
||||
MouseTweaksWheel,
|
||||
@@ -402,13 +396,6 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
|
||||
Err("Lighting"),
|
||||
Ok(Fullbright),
|
||||
Ok(DynamicLights),
|
||||
Err("Minimap"),
|
||||
Ok(Minimap),
|
||||
Ok(MinimapCorner),
|
||||
Ok(MinimapSize),
|
||||
Ok(MinimapShape),
|
||||
Ok(MinimapZoom),
|
||||
Ok(MinimapRotate),
|
||||
Err("Inventory"),
|
||||
Ok(MouseTweaks),
|
||||
Ok(MouseTweaksWheel),
|
||||
@@ -418,32 +405,11 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
|
||||
Ok(AutoReconnect),
|
||||
]
|
||||
}
|
||||
/// "1 block", "2 blocks", "½ block".
|
||||
fn block_count(n: f32) -> String {
|
||||
if n < 1.0 {
|
||||
"½ block".into()
|
||||
} else if n == 1.0 {
|
||||
"1 block".into()
|
||||
} else {
|
||||
format!("{n} blocks")
|
||||
}
|
||||
}
|
||||
fn next<T: Copy + PartialEq>(all: &[T], current: T, back: bool) -> T {
|
||||
let i = all.iter().position(|v| *v == current).unwrap_or(0);
|
||||
let n = all.len();
|
||||
all[if back { (i + n - 1) % n } else { (i + 1) % n }]
|
||||
}
|
||||
impl Item {
|
||||
pub fn caption(self) -> &'static str {
|
||||
match self {
|
||||
Item::Fullbright => "Fullbright",
|
||||
Item::DynamicLights => "Dynamic lights",
|
||||
Item::MinimapCorner => "Corner",
|
||||
Item::Minimap => "Minimap",
|
||||
Item::MinimapSize => "Size",
|
||||
Item::MinimapShape => "Shape",
|
||||
Item::MinimapZoom => "Zoom",
|
||||
Item::MinimapRotate => "Turn with the player",
|
||||
Item::AutoReconnect => "Auto-reconnect",
|
||||
Item::MouseTweaks => "Mouse Tweaks controls",
|
||||
Item::MouseTweaksWheel => "Scroll wheel moves items",
|
||||
@@ -458,10 +424,9 @@ impl Item {
|
||||
pub fn parent(self) -> Option<Item> {
|
||||
use Item::*;
|
||||
Some(match self {
|
||||
MinimapCorner | MinimapSize | MinimapShape | MinimapZoom | MinimapRotate => Minimap,
|
||||
MouseTweaksWheel => MouseTweaks,
|
||||
SortKey => Sort,
|
||||
Fullbright | DynamicLights | Minimap | MouseTweaks | Sort | AutoReconnect | NoAi
|
||||
Fullbright | DynamicLights | MouseTweaks | Sort | AutoReconnect | NoAi
|
||||
| AgentControl | DiscordPresence => {
|
||||
return None;
|
||||
}
|
||||
@@ -474,12 +439,6 @@ impl Item {
|
||||
Item::DynamicLights => {
|
||||
"Torches and other light sources held, dropped or on fire light the blocks around them."
|
||||
}
|
||||
Item::MinimapCorner => "Overlays in one corner stack.",
|
||||
Item::Minimap => "A map of the loaded terrain around you, in map colours.",
|
||||
Item::MinimapSize => "How big the map is on screen.",
|
||||
Item::MinimapShape => "Square or round.",
|
||||
Item::MinimapZoom => "Blocks per pixel: smaller shows more detail, larger more land.",
|
||||
Item::MinimapRotate => "Forward is up; off keeps north up.",
|
||||
Item::AutoReconnect => {
|
||||
"Rejoins a server after a lost connection or a restart, never after a kick or ban."
|
||||
}
|
||||
@@ -511,7 +470,7 @@ impl Item {
|
||||
use crate::graphics_style::Cost;
|
||||
match self {
|
||||
Item::Fullbright => Some(Cost::None),
|
||||
Item::Minimap | Item::DynamicLights => Some(Cost::Low),
|
||||
Item::DynamicLights => Some(Cost::Low),
|
||||
Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None),
|
||||
_ => None,
|
||||
}
|
||||
@@ -521,8 +480,6 @@ impl Item {
|
||||
Some(match self {
|
||||
Item::Fullbright => e.fullbright,
|
||||
Item::DynamicLights => e.dynamic_lights,
|
||||
Item::Minimap => e.minimap,
|
||||
Item::MinimapRotate => e.minimap_rotate,
|
||||
Item::AutoReconnect => e.auto_reconnect,
|
||||
Item::MouseTweaks => e.mouse_tweaks,
|
||||
Item::MouseTweaksWheel => e.mouse_tweaks_wheel,
|
||||
@@ -537,38 +494,22 @@ impl Item {
|
||||
pub fn value(self, e: &Extras) -> String {
|
||||
match self {
|
||||
Item::SortKey => crate::keybinds::display_name(&e.sort_key).plain(),
|
||||
Item::MinimapCorner => e.minimap_corner.label().into(),
|
||||
Item::MinimapSize => MINIMAP_SIZES
|
||||
.iter()
|
||||
.find(|s| s.0 == e.minimap_size)
|
||||
.map_or("Medium", |s| s.1)
|
||||
.into(),
|
||||
Item::MinimapShape => if e.minimap_round { "Round" } else { "Square" }.into(),
|
||||
Item::MinimapZoom => format!("{} per pixel", block_count(e.minimap_zoom)),
|
||||
other => match other.switch(e) {
|
||||
Some(true) => "On".into(),
|
||||
_ => "Off".into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
/// A click (`back` for the right button). The sort key binds instead.
|
||||
pub fn cycle(self, e: &mut Extras, back: bool) {
|
||||
/// A click (`_back` for the right button: every item left is a switch,
|
||||
/// so both flip it). The sort key binds instead.
|
||||
pub fn cycle(self, e: &mut Extras, _back: bool) {
|
||||
match self {
|
||||
Item::Fullbright => e.fullbright = !e.fullbright,
|
||||
Item::DynamicLights => e.dynamic_lights = !e.dynamic_lights,
|
||||
Item::Minimap => e.minimap = !e.minimap,
|
||||
Item::MinimapRotate => e.minimap_rotate = !e.minimap_rotate,
|
||||
Item::AutoReconnect => e.auto_reconnect = !e.auto_reconnect,
|
||||
Item::MouseTweaks => e.mouse_tweaks = !e.mouse_tweaks,
|
||||
Item::MouseTweaksWheel => e.mouse_tweaks_wheel = !e.mouse_tweaks_wheel,
|
||||
Item::Sort => e.sort = !e.sort,
|
||||
Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back),
|
||||
Item::MinimapSize => {
|
||||
let sizes: Vec<u8> = MINIMAP_SIZES.iter().map(|s| s.0).collect();
|
||||
e.minimap_size = next(&sizes, e.minimap_size, back);
|
||||
}
|
||||
Item::MinimapShape => e.minimap_round = !e.minimap_round,
|
||||
Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back),
|
||||
Item::NoAi => e.no_ai = !e.no_ai,
|
||||
Item::AgentControl => e.agent_control = !e.agent_control,
|
||||
Item::DiscordPresence => e.discord_presence = !e.discord_presence,
|
||||
@@ -712,12 +653,9 @@ mod tests {
|
||||
#[test]
|
||||
fn items_cycle_through_their_values() {
|
||||
let mut e = Extras::default();
|
||||
Item::MinimapCorner.cycle(&mut e, true);
|
||||
assert_eq!(e.minimap_corner, Corner::TopLeft);
|
||||
Item::MinimapZoom.cycle(&mut e, true);
|
||||
assert_eq!(Item::MinimapZoom.value(&e), "½ block per pixel");
|
||||
Item::MinimapSize.cycle(&mut e, false);
|
||||
assert_eq!(Item::MinimapSize.value(&e), "Large");
|
||||
Item::Sort.cycle(&mut e, true);
|
||||
assert_eq!(Item::Sort.value(&e), "On");
|
||||
// The minimap's old keys still parse, for the move to its mod.
|
||||
assert_eq!(
|
||||
Extras::parse("minimapSize:7\nminimapZoom:3").minimap_zoom,
|
||||
1.0
|
||||
|
||||
@@ -131,6 +131,7 @@ mod pumpkin;
|
||||
mod raids;
|
||||
mod recipe_book;
|
||||
mod remote;
|
||||
mod remote_chunks;
|
||||
mod remote_mob_data;
|
||||
mod remote_mob_use;
|
||||
mod remote_objects;
|
||||
@@ -2271,7 +2272,13 @@ impl Game<'_> {
|
||||
let speed = self.world.random.next_float() * 0.2 + 0.1;
|
||||
item.move_towards_closest_space(&self.world, self.res.facts(), speed);
|
||||
}
|
||||
let alive = item.tick(&self.world, self.res.facts(), self.collision, no_physics);
|
||||
let alive = item.tick(
|
||||
&self.world,
|
||||
self.res.facts(),
|
||||
self.collision,
|
||||
no_physics,
|
||||
&self.res.motion().fluids,
|
||||
);
|
||||
cells.moved(i, item.previous, item.position);
|
||||
// ItemEntity.tick: merge every 2 ticks while moving between
|
||||
// blocks, every 40 otherwise, before the lifetime check.
|
||||
@@ -4193,6 +4200,9 @@ impl Game<'_> {
|
||||
self.with_level(|b, level, ticks| b.notify_written(level, ticks, position, flags));
|
||||
}
|
||||
fn tick(&mut self) -> Result<()> {
|
||||
if self.agent.hold_server {
|
||||
return Ok(());
|
||||
}
|
||||
self.tick_debug_keys()?;
|
||||
self.tick_debug_charts();
|
||||
if self.remote.is_some() {
|
||||
@@ -5600,6 +5610,8 @@ impl Game<'_> {
|
||||
self.craft_size = 2;
|
||||
self.craft_table = None;
|
||||
if let Some(key) = self.container.take() {
|
||||
// A cart's or chest boat's items go back to it.
|
||||
self.close_cart_container(key);
|
||||
self.container_opener_event(key, false);
|
||||
self.post_block_game_event(
|
||||
"minecraft:container_close",
|
||||
@@ -5639,7 +5651,6 @@ impl Game<'_> {
|
||||
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
|
||||
}
|
||||
self.close_ender_chest();
|
||||
self.close_cart_container();
|
||||
}
|
||||
/// `quickMoveStack` of the open plain menu for a shift-click.
|
||||
fn inventory_quick_move(&mut self, slot: usize) -> bool {
|
||||
|
||||
@@ -300,6 +300,8 @@ struct Glide {
|
||||
pub(super) struct Agent {
|
||||
task: Option<Task>,
|
||||
glide: Option<Glide>,
|
||||
/// Control-fixture barrier: hold simulation and packet handling, not transport threads.
|
||||
pub hold_server: bool,
|
||||
}
|
||||
|
||||
pub(super) enum Handled {
|
||||
@@ -479,6 +481,8 @@ impl Game<'_> {
|
||||
"absorption": p.health.absorption(),
|
||||
// The hurt animation's ticks left (the camera's hurt tilt).
|
||||
"hurt_time": p.health.hurt_animation_time,
|
||||
// LivingEntity.deathTime while dead (the camera's death roll).
|
||||
"death_time": self.death_time(),
|
||||
"air": p.air,
|
||||
"food": p.health.food.food,
|
||||
"saturation": p.health.food.saturation,
|
||||
@@ -667,6 +671,7 @@ impl Game<'_> {
|
||||
});
|
||||
if let Some(chat) = &self.ui.chat_screen {
|
||||
v["chat_input"] = json!(chat.input.value);
|
||||
v["chat_suggestions"] = json!(chat.suggestions_visible());
|
||||
}
|
||||
if self.title.is_some() {
|
||||
v["menu"] = self.title_value();
|
||||
|
||||
@@ -219,6 +219,11 @@ impl Game<'_> {
|
||||
/// client tick (`ClientLevel.tickBlockEntities`).
|
||||
pub(super) fn tick_block_entity_anims(&mut self) {
|
||||
let Some(r) = &self.renderer else {
|
||||
// A server has no window, but its gateways still run their
|
||||
// server ticker.
|
||||
if self.remote.is_none() {
|
||||
self.tick_gateway_servers();
|
||||
}
|
||||
return;
|
||||
};
|
||||
// Sorted by position: the order they tick in, and a quick lookup.
|
||||
@@ -378,6 +383,31 @@ impl Game<'_> {
|
||||
}
|
||||
self.be_anims.present = positions;
|
||||
}
|
||||
/// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the
|
||||
/// gateways a server keeps a copy of, in block-ticking chunks
|
||||
/// (`Level.tickBlockEntities`): the cooldown an entry started runs out,
|
||||
/// and every 2400 ticks `triggerCooldown` sends its block event.
|
||||
fn tick_gateway_servers(&mut self) {
|
||||
let levels = self.tickets.levels();
|
||||
let mut positions: Vec<[i32; 3]> = self
|
||||
.be_anims
|
||||
.gateway_servers
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|p| levels.block_ticking_at(p[0], p[2]))
|
||||
.collect();
|
||||
positions.sort_unstable();
|
||||
for pos in positions {
|
||||
let triggered = self
|
||||
.be_anims
|
||||
.gateway_servers
|
||||
.get_mut(&pos)
|
||||
.is_some_and(EndGateway::portal_tick);
|
||||
if triggered {
|
||||
self.block_entity_event(pos, 1, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `EndGatewayBlock.entityInside` on the server: whether the gateway at
|
||||
/// `pos` let the entity in (`triggerCooldown`, with its block event).
|
||||
pub(super) fn gateway_enter(&mut self, pos: [i32; 3]) -> bool {
|
||||
|
||||
@@ -1097,6 +1097,12 @@ impl Game<'_> {
|
||||
Target::Player => {
|
||||
// ServerPlayer.teleport: removeVehicle before placing the player.
|
||||
self.stop_riding();
|
||||
// A server's player teleported within their level is placed
|
||||
// there at once: the arrival they were waiting for elsewhere
|
||||
// in it (whose chunks lose their tickets) is abandoned.
|
||||
if let Some(conn) = self.lan_acting {
|
||||
self.server_trips.retain(|trip| !trip.is(conn));
|
||||
}
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
p.position = v;
|
||||
p.velocity = Vec3::new(0.0, 0.0, 0.0);
|
||||
|
||||
@@ -11,6 +11,9 @@ use winit::{event::MouseButton, event_loop::ActiveEventLoop, keyboard::KeyCode};
|
||||
|
||||
const HELP: &[&str] = &[
|
||||
"status game, player, streaming and renderer state",
|
||||
"simulation authoritative projectiles in the owner's level",
|
||||
"server-hold on|off hold simulation and player packets at a control-fixture barrier",
|
||||
"stall MILLISECONDS stall the window thread (0..5000), leaving transport alive",
|
||||
"key KEY down|up|tap|repeat press, release or auto-repeat a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)",
|
||||
"release release every key and mouse button",
|
||||
"mouse left|right|middle down|up|click",
|
||||
@@ -238,6 +241,47 @@ impl Game<'_> {
|
||||
}
|
||||
"sculk" => Ok(Some(self.sculk_command(&words)?)),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"stall" => {
|
||||
let millis: u64 = arg(1)?.parse()?;
|
||||
if millis > 5000 {
|
||||
return Err("stall is limited to 5000 milliseconds".into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(millis));
|
||||
ok()
|
||||
}
|
||||
"simulation" => {
|
||||
self.require_world()?;
|
||||
let value = if let Some(server) = &self.integrated {
|
||||
server
|
||||
.call(|g| {
|
||||
g.in_owner_level(|g| {
|
||||
json!({ "game_time": g.world.game_time, "projectiles": g.projectiles_status() })
|
||||
})
|
||||
})
|
||||
.ok_or("the integrated server stopped")?
|
||||
} else {
|
||||
json!({ "game_time": self.world.game_time, "projectiles": self.projectiles_status() })
|
||||
};
|
||||
Ok(Some(value))
|
||||
}
|
||||
"server-hold" => {
|
||||
self.require_world()?;
|
||||
let held = match arg(1)? {
|
||||
"on" => true,
|
||||
"off" => false,
|
||||
_ => return Err("server-hold on|off".into()),
|
||||
};
|
||||
if let Some(server) = &self.integrated {
|
||||
server
|
||||
.call(move |g| g.agent.hold_server = held)
|
||||
.ok_or("the integrated server stopped")?;
|
||||
} else if self.remote.is_some() {
|
||||
return Err("server-hold requires the world's host".into());
|
||||
} else {
|
||||
self.agent.hold_server = held;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
"pad" => Ok(Some(self.pad_command(&words)?)),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
@@ -508,10 +552,23 @@ impl Game<'_> {
|
||||
"mobs" => {
|
||||
self.require_world()?;
|
||||
let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?;
|
||||
if let Some(server) = &self.integrated {
|
||||
let center = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position);
|
||||
let value = server
|
||||
.call(move |g| g.in_owner_level(|g| g.control_mobs_at(radius, center)))
|
||||
.ok_or("the integrated server stopped")?;
|
||||
return Ok(Some(value));
|
||||
}
|
||||
Ok(Some(self.control_mobs(radius)))
|
||||
}
|
||||
"hurtlog" => {
|
||||
self.require_world()?;
|
||||
if let Some(server) = &self.integrated {
|
||||
let value = server
|
||||
.call(|g| g.control_hurt_log())
|
||||
.ok_or("the integrated server stopped")?;
|
||||
return Ok(Some(value));
|
||||
}
|
||||
Ok(Some(self.control_hurt_log()))
|
||||
}
|
||||
"resume" => {
|
||||
|
||||
@@ -312,6 +312,9 @@ impl Game<'_> {
|
||||
/// The `mobs` command: nearby mobs with position, health and running goals.
|
||||
pub(super) fn control_mobs(&self, radius: f64) -> serde_json::Value {
|
||||
let center = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position);
|
||||
self.control_mobs_at(radius, center)
|
||||
}
|
||||
pub(super) fn control_mobs_at(&self, radius: f64, center: Vec3) -> serde_json::Value {
|
||||
let list: Vec<serde_json::Value> = self
|
||||
.mobs
|
||||
.iter()
|
||||
@@ -504,6 +507,17 @@ impl Game<'_> {
|
||||
Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players),
|
||||
_ => Default::default(),
|
||||
};
|
||||
// The guests' entity ids by connection, for the shulker bullets fired
|
||||
// at the guest a mob sees.
|
||||
let guest_ids: Vec<(u32, u32)> = match self.lan.as_ref() {
|
||||
Some(host) if !guests.is_empty() => host
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.map(|g| (g.conn, g.entity_id as u32))
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut guest_events = Vec::new();
|
||||
let level_random;
|
||||
{
|
||||
@@ -578,6 +592,19 @@ impl Game<'_> {
|
||||
let kept = m.tick(&w, &mut scratch, &mut events);
|
||||
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
|
||||
if let Some(conn) = seen_guest {
|
||||
// ShulkerBullet.finalTarget is the guest's entity: the
|
||||
// bullet homes on it while the projectiles tick, where
|
||||
// `Who::Player` is the host's own player.
|
||||
if let Some(&(_, id)) = guest_ids.iter().find(|g| g.0 == conn) {
|
||||
for e in &mut events[from..] {
|
||||
if let MobEvent::Projectile(p) = e
|
||||
&& let ProjectileKind::ShulkerBullet { target, .. } = &mut p.kind
|
||||
&& *target == Who::Player
|
||||
{
|
||||
*target = Who::Mob(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut k = from;
|
||||
while k < events.len() {
|
||||
if super::lan_mobs::acts_on_player(&events[k]) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Horizon's extras in the game (`docs/extras.md`): the minimap's tiles and
|
||||
//! image, and its HUD; a mod's zoom (`render.set-zoom`) on the camera; clicks
|
||||
//! Horizon's extras in the game (`docs/extras.md`); a mod's minimap
|
||||
//! (`render.set-minimap`: its tiles, image and HUD) and zoom (`render.set-zoom`) on the camera; clicks
|
||||
//! and frame times for mods (`input.clicks-per-second`, `render.frame-stats`).
|
||||
//! Each hook does nothing while its extra is off and no mod runs.
|
||||
use super::{Dim, Game, Screen};
|
||||
@@ -128,44 +128,29 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The minimap that shows, the extra's or else a mod's
|
||||
/// (`render.set-minimap`): its corner, its side in GUI pixels and its
|
||||
/// view of the player.
|
||||
/// The minimap a mod shows (`render.set-minimap`): its corner, its side
|
||||
/// in GUI pixels and its view of the player.
|
||||
fn minimap_shown(&self) -> Option<(Corner, f32, View)> {
|
||||
let p = self.player.as_ref()?;
|
||||
if self.title.is_some() || self.ui.hide_gui {
|
||||
return None;
|
||||
}
|
||||
let e = &self.settings.extras;
|
||||
let (corner, size, rotate, blocks_per_pixel, round) = if e.minimap {
|
||||
let size = f32::from(e.minimap_size);
|
||||
(
|
||||
e.minimap_corner,
|
||||
size,
|
||||
e.minimap_rotate,
|
||||
e.minimap_zoom,
|
||||
e.minimap_round,
|
||||
)
|
||||
} else {
|
||||
let m = self.mod_minimap()?;
|
||||
(m.corner, m.size, m.rotate, m.blocks_per_pixel, m.round)
|
||||
};
|
||||
let m = self.mod_minimap()?;
|
||||
let view = View {
|
||||
x: p.position.x,
|
||||
z: p.position.z,
|
||||
yaw: self.yaw,
|
||||
rotate,
|
||||
blocks_per_pixel,
|
||||
round,
|
||||
rotate: m.rotate,
|
||||
blocks_per_pixel: m.blocks_per_pixel,
|
||||
round: m.round,
|
||||
};
|
||||
Some((corner, size, view))
|
||||
Some((m.corner, m.size, view))
|
||||
}
|
||||
/// Refresh the minimap's tiles within the frame budget, recompose its
|
||||
/// image when the view or a tile changed, and queue the upload.
|
||||
fn update_minimap(&mut self) {
|
||||
let Some((_, _, view)) = self.minimap_shown() else {
|
||||
let wanted = self.settings.extras.minimap || self.mod_minimap().is_some();
|
||||
if !wanted || self.player.is_none() {
|
||||
if self.mod_minimap().is_none() || self.player.is_none() {
|
||||
self.extras.minimap.clear();
|
||||
self.extras.minimap_dim = None;
|
||||
}
|
||||
|
||||
@@ -71,6 +71,18 @@ impl Rocket {
|
||||
(self.position, self.velocity)
|
||||
}
|
||||
}
|
||||
/// `damageAmount * (float)Math.sqrt((5.0 - this.distanceTo(target)) / 5.0)`
|
||||
/// from the rocket at `from` to a target at `to`; `Entity.distanceTo` sums
|
||||
/// the squared offsets in floats.
|
||||
fn blast_damage(damage: f32, from: Vec3, to: Vec3) -> f32 {
|
||||
let (x, y, z) = (
|
||||
(from.x - to.x) as f32,
|
||||
(from.y - to.y) as f32,
|
||||
(from.z - to.z) as f32,
|
||||
);
|
||||
let distance = f64::from(x * x + y * y + z * z).sqrt() as f32;
|
||||
damage * ((5.0 - f64::from(distance)) / 5.0).sqrt() as f32
|
||||
}
|
||||
pub(super) fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
|
||||
// The item's default component: flight 1, no explosions.
|
||||
stack
|
||||
@@ -251,21 +263,24 @@ impl Game<'_> {
|
||||
let at = [r.position.x, r.position.y, r.position.z];
|
||||
if !r.explosions.is_empty() {
|
||||
let damage = 5.0 + r.explosions.len() as f32 * 2.0;
|
||||
// The player it boosts takes the full damage, a guest as well.
|
||||
if r.attached {
|
||||
match r.guest {
|
||||
None => self.hurt_player_by("minecraft:fireworks", damage),
|
||||
Some(conn) => {
|
||||
if let Some(mut host) = self.lan.take() {
|
||||
self.as_guest(&mut host, conn, |g| {
|
||||
g.hurt_player_by("minecraft:fireworks", damage);
|
||||
});
|
||||
self.lan = Some(host);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let from = r.position;
|
||||
// `attachedToEntity` takes the full damage, a guest as well; every
|
||||
// other player in range and in sight takes the blast.
|
||||
let boosted = r.guest.filter(|_| r.attached);
|
||||
if r.attached && boosted.is_none() {
|
||||
self.rocket_hurt_player(damage);
|
||||
} else {
|
||||
self.rocket_blast_player(from, damage);
|
||||
}
|
||||
if let Some(conn) = boosted
|
||||
&& let Some(mut host) = self.lan.take()
|
||||
{
|
||||
self.as_guest(&mut host, conn, |g| g.rocket_hurt_player(damage));
|
||||
self.lan = Some(host);
|
||||
}
|
||||
// Every other player in the level (LAN guests, the players of a
|
||||
// server thread), each swapped in as the player.
|
||||
self.each_guest_hit_except(boosted, |g| g.rocket_blast_player(from, damage));
|
||||
let hits: Vec<(u32, f32)> = {
|
||||
let world = self.mob_world_base(&[]);
|
||||
self.mobs
|
||||
@@ -285,7 +300,7 @@ impl Game<'_> {
|
||||
);
|
||||
world.clear_between(from, to, false)
|
||||
});
|
||||
sees.then(|| (m.id, damage * ((5.0 - d2.sqrt()) / 5.0).sqrt() as f32))
|
||||
sees.then(|| (m.id, blast_damage(damage, from, m.position)))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -307,6 +322,49 @@ impl Game<'_> {
|
||||
self.particles
|
||||
.fireworks(at, v, r.explosions.clone(), camera);
|
||||
}
|
||||
/// `dealExplosionDamage` on a player that is not the rocket's
|
||||
/// `attachedToEntity`: within 5 blocks, when the rocket sees its feet or
|
||||
/// its middle (`ClipContext.Block.COLLIDER`, no fluids).
|
||||
fn rocket_blast_player(&mut self, from: Vec3, damage: f32) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let feet = p.position;
|
||||
let d2 = (feet.x - from.x).powi(2) + (feet.y - from.y).powi(2) + (feet.z - from.z).powi(2);
|
||||
if d2 > 25.0 {
|
||||
return;
|
||||
}
|
||||
let height = f64::from(p.dimensions.height);
|
||||
let sees = {
|
||||
let world = self.mob_world_base(&[]);
|
||||
(0..2).any(|step| {
|
||||
let to = Vec3::new(feet.x, feet.y + height * 0.5 * f64::from(step), feet.z);
|
||||
world.clear_between(from, to, false)
|
||||
})
|
||||
};
|
||||
if sees {
|
||||
self.rocket_hurt_player(blast_damage(damage, from, feet));
|
||||
}
|
||||
}
|
||||
/// `hurtServer` with `damageSources().fireworks`: armor absorbs it and
|
||||
/// wears (`hurtArmor`); creative and spectator players are immune.
|
||||
fn rocket_hurt_player(&mut self, amount: f32) {
|
||||
if self.creative || self.spectator() {
|
||||
return;
|
||||
}
|
||||
let hurt = if let Some(p) = self.player.as_mut()
|
||||
&& !p.health.dead_or_dying()
|
||||
&& let Some(id) = self.motion.health.damage.id("minecraft:fireworks")
|
||||
{
|
||||
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if hurt {
|
||||
self.hurt_armor(amount);
|
||||
}
|
||||
}
|
||||
/// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera,
|
||||
/// lit at the rocket's light probe.
|
||||
pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
|
||||
@@ -64,14 +64,14 @@ impl Game<'_> {
|
||||
});
|
||||
self.view.tick(eye, target);
|
||||
}
|
||||
/// The player's `deathTime` while dead or dying.
|
||||
fn death_time(&self) -> Option<i32> {
|
||||
/// The player's `deathTime` while dead or dying: whole ticks counted by
|
||||
/// `LivingEntity.tickDeath`, so `deathTime + partialTicks` in
|
||||
/// `Camera.extractRenderState` rises smoothly across frames.
|
||||
pub(super) fn death_time(&self) -> Option<i32> {
|
||||
let p = self.player.as_ref()?;
|
||||
p.health.dead_or_dying().then(|| {
|
||||
self.ui
|
||||
.died_at
|
||||
.map_or(0, |t| (t.elapsed().as_secs_f32() * 20.0) as i32)
|
||||
})
|
||||
p.health
|
||||
.dead_or_dying()
|
||||
.then(|| self.ui.death_time.min(i32::MAX as u32) as i32)
|
||||
}
|
||||
/// The fluid at the camera, as `Camera.getFluidInCamera` reports it.
|
||||
pub(super) fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid {
|
||||
|
||||
@@ -370,6 +370,12 @@ impl Game<'_> {
|
||||
let mut next = Instant::now();
|
||||
while !flags.stop.load(Ordering::Relaxed) {
|
||||
self.run_tasks();
|
||||
if self.agent.hold_server {
|
||||
// Keep servicing control requests so the fixture can release the barrier.
|
||||
// Unlike /tick freeze, no player's queued packets are applied here.
|
||||
self.wait_for_next_server_tick(&mut next, true);
|
||||
continue;
|
||||
}
|
||||
let paused = flags.paused.load(Ordering::Relaxed);
|
||||
if paused {
|
||||
// Only the connections run.
|
||||
|
||||
@@ -1192,6 +1192,10 @@ impl Game<'_> {
|
||||
{
|
||||
self.container_changed(key);
|
||||
}
|
||||
// A vehicle's menu edits the vehicle's own items.
|
||||
if let Some(Slots::Block(key)) = slots {
|
||||
self.store_cart_items(key);
|
||||
}
|
||||
self.drop_guest_items(host, gi, drops);
|
||||
}
|
||||
S::ContainerClose(p) => {
|
||||
@@ -1831,6 +1835,10 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
if self.on_server_trip(conn) {
|
||||
// LivingEntity.hurt kills at once (die), whether the level
|
||||
// has loaded around the player or not: its respawn request
|
||||
// is taken as soon as it comes.
|
||||
self.guest_die(host, gi, conn);
|
||||
continue;
|
||||
}
|
||||
let play = host.play.entry(conn).or_default();
|
||||
@@ -1916,69 +1924,72 @@ impl Game<'_> {
|
||||
self.guest_dig_feedback(host, conn);
|
||||
self.guest_pickups(host, gi);
|
||||
self.guest_orbs(host, gi);
|
||||
if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead {
|
||||
self.guest_forget_digging(host, conn);
|
||||
// FishingHook.shouldStopFishing: its owner is dead.
|
||||
if let Some(play) = host.play.get_mut(&conn) {
|
||||
play.hook = None;
|
||||
}
|
||||
self.guest_die(host, gi, conn);
|
||||
}
|
||||
}
|
||||
|
||||
/// `ServerPlayer.die` for a guest whose health has run out: the death
|
||||
/// message, the loot and experience, the death screen.
|
||||
fn guest_die(&mut self, host: &mut LanHost, gi: usize, conn: u32) {
|
||||
if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead {
|
||||
self.guest_forget_digging(host, conn);
|
||||
// FishingHook.shouldStopFishing: its owner is dead.
|
||||
if let Some(play) = host.play.get_mut(&conn) {
|
||||
play.hook = None;
|
||||
}
|
||||
let g = &mut host.hub.guests[gi];
|
||||
if g.health <= 0.0 && !g.dead {
|
||||
g.dead = true;
|
||||
g.last_death = Some(g.position.map(|v| v.floor() as i32));
|
||||
let (id, at) = (g.entity_id, g.position);
|
||||
let reward = Experience {
|
||||
level: g.xp_level,
|
||||
progress: g.xp_progress,
|
||||
total: g.xp_total,
|
||||
}
|
||||
.death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR);
|
||||
let (name, uuid) = (g.name.clone(), g.uuid);
|
||||
// ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3.
|
||||
let drops = (g.game_mode != SPECTATOR)
|
||||
.then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]);
|
||||
let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take());
|
||||
// ServerPlayer.die: with showDeathMessages, the message goes to
|
||||
// the dying player's death screen and to everyone the team lets
|
||||
// see it; without it, the death screen gets an empty one.
|
||||
let message = if self.ui.rules.bool("show_death_messages") {
|
||||
let me = self.player_text(&name, uuid);
|
||||
let text = match cause {
|
||||
Some(key) => horizon_client::text::Text::translate(&key, &[me]),
|
||||
None if at[1] < f64::from(horizon_client::chunk::MIN_Y - 64) => {
|
||||
horizon_client::text::Text::translate("death.attack.outOfWorld", &[me])
|
||||
}
|
||||
None => self.guest_death_message(conn, me),
|
||||
};
|
||||
let message = horizon_client::lan::data::component_nbt(&text.component());
|
||||
let team = self.score.board.players_team(&name);
|
||||
if horizon_client::scoreboard::own_death_message_shown(team) {
|
||||
host.hub.system_message(message.clone());
|
||||
if self.options.dedicated.is_some() {
|
||||
super::dedicated::log(
|
||||
"INFO",
|
||||
&format!("System chat: {}", text.plain()),
|
||||
);
|
||||
} else if self.player.is_some() {
|
||||
self.system_message(text);
|
||||
}
|
||||
}
|
||||
let g = &mut host.hub.guests[gi];
|
||||
if g.health <= 0.0 && !g.dead {
|
||||
g.dead = true;
|
||||
g.last_death = Some(g.position.map(|v| v.floor() as i32));
|
||||
let (id, at) = (g.entity_id, g.position);
|
||||
let reward = Experience {
|
||||
level: g.xp_level,
|
||||
progress: g.xp_progress,
|
||||
total: g.xp_total,
|
||||
}
|
||||
.death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR);
|
||||
let (name, uuid) = (g.name.clone(), g.uuid);
|
||||
// ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3.
|
||||
let drops =
|
||||
(g.game_mode != SPECTATOR).then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]);
|
||||
let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take());
|
||||
// ServerPlayer.die: with showDeathMessages, the message goes to
|
||||
// the dying player's death screen and to everyone the team lets
|
||||
// see it; without it, the death screen gets an empty one.
|
||||
let message = if self.ui.rules.bool("show_death_messages") {
|
||||
let me = self.player_text(&name, uuid);
|
||||
let text = match cause {
|
||||
Some(key) => horizon_client::text::Text::translate(&key, &[me]),
|
||||
None if at[1] < f64::from(horizon_client::chunk::MIN_Y - 64) => {
|
||||
horizon_client::text::Text::translate("death.attack.outOfWorld", &[me])
|
||||
}
|
||||
message
|
||||
} else {
|
||||
literal("")
|
||||
None => self.guest_death_message(conn, me),
|
||||
};
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::PlayerCombatKill(play::PlayerCombatKill { id, message }),
|
||||
);
|
||||
// LivingEntity.die: the death animation, the dying player included.
|
||||
host.hub.entity_event(id, 3, at);
|
||||
if let Some(eyes) = drops {
|
||||
self.as_guest(host, conn, |game| game.drop_inventory(eyes));
|
||||
let message = horizon_client::lan::data::component_nbt(&text.component());
|
||||
let team = self.score.board.players_team(&name);
|
||||
if horizon_client::scoreboard::own_death_message_shown(team) {
|
||||
host.hub.system_message(message.clone());
|
||||
if self.options.dedicated.is_some() {
|
||||
super::dedicated::log("INFO", &format!("System chat: {}", text.plain()));
|
||||
} else if self.player.is_some() {
|
||||
self.system_message(text);
|
||||
}
|
||||
}
|
||||
self.spawn_orbs(at, reward);
|
||||
message
|
||||
} else {
|
||||
literal("")
|
||||
};
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::PlayerCombatKill(play::PlayerCombatKill { id, message }),
|
||||
);
|
||||
// LivingEntity.die: the death animation, the dying player included.
|
||||
host.hub.entity_event(id, 3, at);
|
||||
if let Some(eyes) = drops {
|
||||
self.as_guest(host, conn, |game| game.drop_inventory(eyes));
|
||||
}
|
||||
self.spawn_orbs(at, reward);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2176,6 +2187,9 @@ impl Game<'_> {
|
||||
let _ = w.tick_environment_damage();
|
||||
let _ = w.apply_fire_contact();
|
||||
let _ = w.server_hazards_tick(in_wall);
|
||||
// Player.tick ends with updatePlayerPose: a swimmer, or a player
|
||||
// crawling under a block, takes the short box its moves are checked with.
|
||||
let _ = w.update_player_pose();
|
||||
let mut events = std::mem::take(&mut w.player.events);
|
||||
// LayeredCauldronBlock.handleEntityOnFireInside along those moves.
|
||||
for event in &events {
|
||||
|
||||
@@ -291,6 +291,11 @@ impl Game<'_> {
|
||||
let at = host.hub.guests[gi].position;
|
||||
self.award_furnace_recipes(pos, at);
|
||||
}
|
||||
// Slot.setChanged on a changed container slot: BlockEntity.setChanged,
|
||||
// so the chunk is saved and comparators read the block again.
|
||||
if changed.iter().any(|&s| s < items.len()) {
|
||||
self.container_changed(pos);
|
||||
}
|
||||
host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu));
|
||||
host.hub.inventory_clicked(conn, p, &self.world, &changed);
|
||||
true
|
||||
|
||||
@@ -119,7 +119,17 @@ impl Game<'_> {
|
||||
|
||||
/// Runs `f` as each guest in play here, for what strikes every player in
|
||||
/// an area (`Level.getEntities`), not only the window's own.
|
||||
pub(super) fn each_guest_hit(&mut self, mut f: impl FnMut(&mut Self)) {
|
||||
pub(super) fn each_guest_hit(&mut self, f: impl FnMut(&mut Self)) {
|
||||
self.each_guest_hit_except(None, f);
|
||||
}
|
||||
|
||||
/// [`Self::each_guest_hit`] leaving out the guest `except` (the one a
|
||||
/// firework rocket is attached to, which it hurts on its own).
|
||||
pub(super) fn each_guest_hit_except(
|
||||
&mut self,
|
||||
except: Option<u32>,
|
||||
mut f: impl FnMut(&mut Self),
|
||||
) {
|
||||
let Some(mut host) = self.lan.take() else {
|
||||
return;
|
||||
};
|
||||
@@ -127,7 +137,7 @@ impl Game<'_> {
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && Some(g.conn) != except)
|
||||
.map(|g| g.conn)
|
||||
.collect();
|
||||
for conn in conns {
|
||||
|
||||
@@ -1117,22 +1117,35 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// Closing a cart's container copies the items back.
|
||||
pub(super) fn close_cart_container(&mut self) {
|
||||
let Some(key) = self.container.filter(|k| k.1 == CART_KEY_Y) else {
|
||||
return;
|
||||
};
|
||||
let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) else {
|
||||
/// Closing the cart's container open under `key` copies the items back.
|
||||
pub(super) fn close_cart_container(&mut self, key: (i32, i32, i32)) {
|
||||
if key.1 != CART_KEY_Y {
|
||||
return;
|
||||
}
|
||||
self.store_cart_items(key);
|
||||
self.world.block_entities.remove(&key);
|
||||
if let Some(c) = self.carts.iter().find(|c| c.id as i32 == key.2)
|
||||
&& c.kind == CartKind::Chest
|
||||
{
|
||||
let at = [c.position.x, c.position.y, c.position.z];
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.audio
|
||||
.play("minecraft:block.chest.close", Some(at), 0.5, pitch);
|
||||
}
|
||||
}
|
||||
/// The menu of a chest or hopper minecart or a chest boat works on the
|
||||
/// vehicle's own items (`ContainerEntity`): the placeholder under `key`
|
||||
/// that the menu edits is copied back to the vehicle.
|
||||
pub(super) fn store_cart_items(&mut self, key: (i32, i32, i32)) {
|
||||
if key.1 != CART_KEY_Y {
|
||||
return;
|
||||
}
|
||||
let Some(BlockEntity::Chest(items)) = self.world.block_entities.get(&key) else {
|
||||
return;
|
||||
};
|
||||
let items = items.clone();
|
||||
if let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) {
|
||||
c.items = items;
|
||||
let at = [c.position.x, c.position.y, c.position.z];
|
||||
if c.kind == CartKind::Chest {
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.audio
|
||||
.play("minecraft:block.chest.close", Some(at), 0.5, pitch);
|
||||
}
|
||||
} else if let Some(b) = self.boats.iter_mut().find(|b| b.id as i32 == key.2) {
|
||||
b.items = items;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,9 @@ use {
|
||||
text::{self, Text},
|
||||
ui,
|
||||
},
|
||||
horizon_mods::{Clock, ModKey, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget},
|
||||
horizon_mods::{
|
||||
Clock, ModKey, Mods, Output, Player, Runs, Snapshot, Status, UiScreen, UiWidget,
|
||||
},
|
||||
std::time::Instant,
|
||||
winit::{event::MouseButton, keyboard::KeyCode},
|
||||
};
|
||||
@@ -270,7 +272,7 @@ impl Game<'_> {
|
||||
.collect();
|
||||
let enabled = &self.settings.mods.enabled;
|
||||
let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id);
|
||||
let mods = Mods::load(&paths, on, vanilla_command);
|
||||
let mods = Mods::load_for(Runs::Client, &paths, on, vanilla_command);
|
||||
self.mods.mods = mods;
|
||||
let chosen = &self.settings.mods;
|
||||
self.mods.mods.set_bindings(|id| chosen.keys_of(id));
|
||||
@@ -412,6 +414,7 @@ impl Game<'_> {
|
||||
mappings,
|
||||
cps,
|
||||
font_widths: self.mods.font_widths.clone(),
|
||||
players: Vec::new(),
|
||||
}
|
||||
}
|
||||
/// A game tick.
|
||||
@@ -522,6 +525,8 @@ impl Game<'_> {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Server mods' lines: this game runs no server mod yet.
|
||||
Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. } => continue,
|
||||
};
|
||||
// Not through system_message: a mod must not hear its own lines.
|
||||
// Written by this client, so the Chat option doesn't hide it.
|
||||
|
||||
@@ -6,11 +6,12 @@
|
||||
//! clicks). The player still moves with the local physics, as the vanilla
|
||||
//! client predicts its own movement; the server stays authoritative for
|
||||
//! everything else.
|
||||
use super::remote_chunks::{ChunkDecoder, ChunkFormat, Next};
|
||||
use super::{Dim, Game, Mining, Screen};
|
||||
use horizon_client::first_person::{Hand, SwingAnimation};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy},
|
||||
chunk::{Chunk, SECTIONS},
|
||||
containers::{BlockEntity, Furnace, FurnaceKind},
|
||||
entities::{Experience, ExperienceOrb, ItemEntity},
|
||||
hud::{HudBatch, rgba},
|
||||
@@ -25,11 +26,7 @@ use horizon_client::{
|
||||
tab_list::SPECTATOR,
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
paletted::{PalettedContainer, Strategy},
|
||||
random::RandomSource,
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use horizon_protocol::{
|
||||
entity_data::{ITEM_ENTITY_ITEM, Value},
|
||||
item::{Hashed, Stack},
|
||||
@@ -64,9 +61,6 @@ fn menu_title(tag: &Tag) -> horizon_client::text::Text {
|
||||
remote_text(tag).resolve_legacy()
|
||||
}
|
||||
|
||||
/// A section's sky and block light layers from the wire.
|
||||
type LightLayers = (Option<Vec<u8>>, Option<Vec<u8>>);
|
||||
|
||||
/// Streaming needs a generator; a server world never generates.
|
||||
struct NoTerrain;
|
||||
impl ChunkGenerator for NoTerrain {
|
||||
@@ -104,6 +98,14 @@ fn place_interpolated(m: &mut Mob, at: PosRot) {
|
||||
m.head_pitch = (at.pitch % 360.0).clamp(-90.0, 90.0);
|
||||
}
|
||||
|
||||
/// What the network thread delivered, in order: an event, or a chunk packet
|
||||
/// handed to the decoder (with the format it decodes with), whose column
|
||||
/// comes back from `ChunkDecoder::next`.
|
||||
enum Received {
|
||||
Event(Event),
|
||||
Chunk(Arc<ChunkFormat>),
|
||||
}
|
||||
|
||||
pub(super) struct Remote {
|
||||
pub session: Session,
|
||||
pub brand: String,
|
||||
@@ -114,8 +116,11 @@ pub(super) struct Remote {
|
||||
status: String,
|
||||
pub(super) entity_id: i32,
|
||||
dimension: DimensionType,
|
||||
biome_map: Vec<u16>,
|
||||
biome_bits: u8,
|
||||
/// What chunk packets decode with (the dimension's height and sky, the
|
||||
/// biome registry); replaced whenever one of them changes.
|
||||
pub(super) chunk_format: Arc<ChunkFormat>,
|
||||
/// Decodes chunk packets as they arrive, off the frame.
|
||||
decoder: ChunkDecoder,
|
||||
view_distance: i32,
|
||||
sequence: i32,
|
||||
position_sender: horizon_client::player_sync::PositionSender,
|
||||
@@ -200,7 +205,7 @@ pub(super) struct Remote {
|
||||
chunk_center: (i32, i32),
|
||||
/// Received events a frame left for the next one, in order, and when
|
||||
/// the oldest of them first waited (`poll_remote`).
|
||||
backlog: VecDeque<Event>,
|
||||
backlog: VecDeque<Received>,
|
||||
backlog_since: Option<Instant>,
|
||||
/// `ClientboundTransferPacket`'s target: when the connection ends the
|
||||
/// game connects here, the stored cookies carried over (`TransferState`).
|
||||
@@ -210,11 +215,12 @@ pub(super) struct Remote {
|
||||
/// The time a frame spends on chunk packets before it leaves the rest of
|
||||
/// the received events for the next frame. A batch of 25 to 60 columns
|
||||
/// (0.1 ms each on an M4 Pro) all in one frame was a 3 to 8 ms frame every
|
||||
/// time the player crossed a chunk border at 32 chunks.
|
||||
/// time the player crossed a chunk border at 32 chunks; they decode on the
|
||||
/// chunk decoder's thread now, and the frame only inserts them.
|
||||
const CHUNK_PACKETS_PER_FRAME: Duration = Duration::from_millis(1);
|
||||
/// Events that have waited this long are all handled in the next frame,
|
||||
/// whatever their cost: the packets after a slow machine's chunks never
|
||||
/// wait more than a tick.
|
||||
/// whatever inserting their columns costs, up to a column still decoding:
|
||||
/// the packets after a slow machine's chunks don't wait on its frames.
|
||||
const BACKLOG_LIMIT: Duration = Duration::from_millis(50);
|
||||
/// The open menu name of a server's horse inventory, then its chest's
|
||||
/// columns (the packet names no `MenuType`).
|
||||
@@ -420,8 +426,12 @@ impl Game<'_> {
|
||||
status: "Connecting to the server...".into(),
|
||||
entity_id: 0,
|
||||
dimension: DimensionType::vanilla("minecraft:overworld"),
|
||||
biome_map: Vec::new(),
|
||||
biome_bits: 7,
|
||||
chunk_format: Arc::new(ChunkFormat::new(
|
||||
&DimensionType::vanilla("minecraft:overworld"),
|
||||
Vec::new(),
|
||||
7,
|
||||
)),
|
||||
decoder: ChunkDecoder::new(),
|
||||
view_distance: self.settings.render_distance,
|
||||
sequence: 0,
|
||||
position_sender: Default::default(),
|
||||
@@ -741,25 +751,63 @@ impl Game<'_> {
|
||||
/// client's packet processor), in order. Chunk packets get
|
||||
/// `CHUNK_PACKETS_PER_FRAME`: once a frame has spent it, the events from
|
||||
/// the next chunk packet on wait for the next frame, unless they have
|
||||
/// already waited `BACKLOG_LIMIT`.
|
||||
/// already waited `BACKLOG_LIMIT`. A chunk packet still decoding holds
|
||||
/// back what follows it.
|
||||
pub(super) fn poll_remote(&mut self) -> Result<()> {
|
||||
let Some(r) = self.remote.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut events = std::mem::take(&mut r.backlog);
|
||||
events.extend(r.session.poll());
|
||||
// Chunk packets start decoding now; the frame that reaches one in
|
||||
// order inserts its column.
|
||||
for event in r.session.poll() {
|
||||
events.push_back(match event {
|
||||
Event::Packet(p) if matches!(*p, C::LevelChunkWithLight(_)) => {
|
||||
match r.decoder.submit(r.chunk_format.clone(), p) {
|
||||
None => Received::Chunk(r.chunk_format.clone()),
|
||||
Some(p) => Received::Event(Event::Packet(p)),
|
||||
}
|
||||
}
|
||||
event => Received::Event(event),
|
||||
});
|
||||
}
|
||||
let overdue = r
|
||||
.backlog_since
|
||||
.is_some_and(|since| since.elapsed() >= BACKLOG_LIMIT);
|
||||
let mut chunks = Duration::ZERO;
|
||||
while let Some(event) = events.pop_front() {
|
||||
let chunk =
|
||||
matches!(&event, Event::Packet(p) if matches!(**p, C::LevelChunkWithLight(_)));
|
||||
while let Some(item) = events.pop_front() {
|
||||
let chunk = matches!(item, Received::Chunk(_));
|
||||
if chunk && !overdue && chunks >= CHUNK_PACKETS_PER_FRAME {
|
||||
events.push_front(event);
|
||||
events.push_front(item);
|
||||
break;
|
||||
}
|
||||
let started = chunk.then(Instant::now);
|
||||
let event = match item {
|
||||
Received::Event(event) => event,
|
||||
Received::Chunk(format) => {
|
||||
// A column still decoding waits for the next frame, with
|
||||
// what came after it, overdue or not.
|
||||
let Some(next) = self.remote.as_ref().map(|r| r.decoder.next()) else {
|
||||
break;
|
||||
};
|
||||
let (packet, column) = match next {
|
||||
Next::Ready(decoded) => decoded,
|
||||
Next::Decoding => {
|
||||
events.push_front(Received::Chunk(format));
|
||||
break;
|
||||
}
|
||||
Next::Lost => {
|
||||
log::warn!("Horizon: the chunk decoder stopped; a column is missing");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let C::LevelChunkWithLight(p) = *packet {
|
||||
self.remote_chunk(&p, Some((&format, column)));
|
||||
}
|
||||
chunks += started.map_or(Duration::ZERO, |t| t.elapsed());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match event {
|
||||
Event::Status(s) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
@@ -915,8 +963,8 @@ impl Game<'_> {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.biome_bits = ceil_log2(biomes.len());
|
||||
r.biome_map = biomes;
|
||||
let bits = ceil_log2(biomes.len());
|
||||
r.chunk_format = Arc::new(ChunkFormat::new(&r.dimension, biomes, bits));
|
||||
r.registries = registries;
|
||||
}
|
||||
}
|
||||
@@ -927,6 +975,7 @@ impl Game<'_> {
|
||||
};
|
||||
let dimension = r.registries.dimension(spawn.dimension_type);
|
||||
let same = r.dimension.name == dimension.name && keep_world;
|
||||
r.chunk_format = Arc::new(r.chunk_format.with_dimension(&dimension));
|
||||
r.dimension = dimension;
|
||||
r.game_mode = spawn.game_type;
|
||||
r.loaded_sent = false;
|
||||
@@ -989,145 +1038,10 @@ impl Game<'_> {
|
||||
self.apply_settings();
|
||||
}
|
||||
|
||||
/// LevelChunkSection data into the client's fixed -64..320 column.
|
||||
fn remote_chunk(&self, p: &play::LevelChunkWithLight) -> std::result::Result<Chunk, String> {
|
||||
let r = self.remote.as_ref().ok_or("no connection")?;
|
||||
let sections = p
|
||||
.chunk
|
||||
.sections(r.dimension.sections(), 16, r.biome_bits)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut chunk = Chunk::empty(p.x, p.z);
|
||||
let offset = (r.dimension.min_y - MIN_Y).div_euclid(16);
|
||||
// Biome table index per quart cell of the dimension's own sections.
|
||||
let mut biome_cells: Vec<[u32; 64]> = Vec::with_capacity(sections.len());
|
||||
for (i, s) in sections.iter().enumerate() {
|
||||
let target = offset + i as i32;
|
||||
let mut cells = [0u32; 64];
|
||||
for (j, cell) in cells.iter_mut().enumerate() {
|
||||
*cell = u32::from(
|
||||
r.biome_map
|
||||
.get(s.biomes.get(j) as usize)
|
||||
.copied()
|
||||
.unwrap_or(0),
|
||||
);
|
||||
}
|
||||
biome_cells.push(cells);
|
||||
if !(0..SECTIONS as i32).contains(&target) {
|
||||
continue;
|
||||
}
|
||||
// A global section is as wide as the server's registry: 16 bits
|
||||
// from a vanilla server, wider from a Horizon host with the same
|
||||
// content mods. Read it at that width, then widen it to ours.
|
||||
let ours = block_strategy();
|
||||
let strategy = if ours.wire_has_palette(s.states.bits) {
|
||||
ours
|
||||
} else {
|
||||
Strategy::blocks(s.states.bits)
|
||||
};
|
||||
let palette = s.states.palette.iter().map(|&p| p as u32).collect();
|
||||
let words = s.states.data.iter().map(|&w| w as u64).collect();
|
||||
let mut blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if strategy.global_bits != ours.global_bits {
|
||||
let mut values = [0u32; 4096];
|
||||
blocks.unpack(&mut values);
|
||||
// Ids past our registry (a host with mods we lack) read as air.
|
||||
let limit = 1u64 << ours.global_bits;
|
||||
for v in &mut values {
|
||||
if u64::from(*v) >= limit {
|
||||
*v = 0;
|
||||
}
|
||||
}
|
||||
blocks = PalettedContainer::from_values(ours, &values);
|
||||
}
|
||||
let mut section = Section {
|
||||
blocks,
|
||||
biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells),
|
||||
light: Light::Uniform(0xF0),
|
||||
};
|
||||
section.compact();
|
||||
chunk.sections[target as usize] = Arc::new(section);
|
||||
}
|
||||
// Sections outside the dimension's range take its nearest biomes
|
||||
// (the column's top or bottom cell layer repeated).
|
||||
if !biome_cells.is_empty() {
|
||||
let last = biome_cells.len() - 1;
|
||||
for si in 0..SECTIONS as i32 {
|
||||
let i = si - offset;
|
||||
if (0..sections.len() as i32).contains(&i) {
|
||||
continue;
|
||||
}
|
||||
let (edge, layer) = if i < 0 { (0, 0) } else { (last, 3) };
|
||||
let mut cells = [0u32; 64];
|
||||
for (j, cell) in cells.iter_mut().enumerate() {
|
||||
*cell = biome_cells[edge][layer * 16 + j % 16];
|
||||
}
|
||||
Arc::make_mut(&mut chunk.sections[si as usize]).biomes =
|
||||
PalettedContainer::from_values(BIOME_STRATEGY, &cells);
|
||||
}
|
||||
}
|
||||
// ClientPacketListener.applyLightData: the column keeps the light
|
||||
// the server sent; nothing is relit.
|
||||
let (layers, above) = self.wire_light(&p.light);
|
||||
let sky = r.dimension.has_skylight;
|
||||
horizon_client::light::light_from_layers(&mut chunk, &layers, above, sky);
|
||||
Ok(chunk)
|
||||
}
|
||||
/// `ClientPacketListener.readSectionList`: the sky and block layers of a
|
||||
/// light packet, by section of the client's column, and the sky light
|
||||
/// above the column's top section (from the light section just above
|
||||
/// it, else open sky).
|
||||
fn wire_light(
|
||||
&self,
|
||||
light: &horizon_protocol::chunk::LightData,
|
||||
) -> (Vec<LightLayers>, [u8; 256]) {
|
||||
let mut layers: Vec<LightLayers> = vec![(None, None); SECTIONS];
|
||||
let Some(r) = self.remote.as_ref() else {
|
||||
return (layers, [0; 256]);
|
||||
};
|
||||
let sky = r.dimension.has_skylight;
|
||||
let mut above = [if sky { 15 } else { 0 }; 256];
|
||||
// Light section b is the dimension's section b - 1.
|
||||
let first = (r.dimension.min_y - MIN_Y).div_euclid(16) - 1;
|
||||
for (b, layer) in light
|
||||
.layers(r.dimension.sections() + 2)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let si = first + b as i32;
|
||||
if (0..SECTIONS as i32).contains(&si) {
|
||||
layers[si as usize] = layer;
|
||||
} else if si == SECTIONS as i32
|
||||
&& sky
|
||||
&& let Some(l) = &layer.0
|
||||
{
|
||||
for (i, a) in above.iter_mut().enumerate() {
|
||||
*a = (l[i >> 1] >> ((i & 1) * 4)) & 15;
|
||||
}
|
||||
}
|
||||
}
|
||||
(layers, above)
|
||||
}
|
||||
/// `handleLightUpdatePacket`: the sections it names take its light.
|
||||
fn remote_light_update(&mut self, p: &play::LightUpdate) {
|
||||
let Some(sky) = self.remote.as_ref().map(|r| r.dimension.has_skylight) else {
|
||||
return;
|
||||
};
|
||||
if !self.world.chunks.contains_key(&(p.x, p.z)) {
|
||||
return;
|
||||
}
|
||||
let (layers, _) = self.wire_light(&p.light);
|
||||
let Some(chunk) = self.world.chunks.get_mut(&(p.x, p.z)) else {
|
||||
return;
|
||||
};
|
||||
let changed =
|
||||
horizon_client::light::update_light_layers(Arc::make_mut(chunk), &layers, sky);
|
||||
Streaming::light_updated(&mut self.world, p.x, p.z, &changed);
|
||||
}
|
||||
/// `ClientChunkCache.Storage.inRange`: within the storage around the
|
||||
/// view centre, `calculateStorageRange` (the server's radius, at least
|
||||
/// two, plus three) chunks each way.
|
||||
fn remote_chunk_in_range(&self, x: i32, z: i32) -> bool {
|
||||
pub(super) fn remote_chunk_in_range(&self, x: i32, z: i32) -> bool {
|
||||
self.remote.as_ref().is_none_or(|r| {
|
||||
let range = r.view_distance.max(2) + 3;
|
||||
(x - r.chunk_center.0).abs() <= range && (z - r.chunk_center.1).abs() <= range
|
||||
@@ -1135,29 +1049,33 @@ impl Game<'_> {
|
||||
}
|
||||
/// The columns a moved or resized storage no longer holds.
|
||||
fn drop_remote_chunks_out_of_range(&mut self) {
|
||||
let gone: Vec<(i32, i32)> = self
|
||||
let gone: horizon_client::fast_hash::FxHashSet<(i32, i32)> = self
|
||||
.world
|
||||
.chunks
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|&(x, z)| !self.remote_chunk_in_range(x, z))
|
||||
.collect();
|
||||
for (x, z) in gone {
|
||||
if gone.is_empty() {
|
||||
return;
|
||||
}
|
||||
for &(x, z) in &gone {
|
||||
self.streaming.forget(&mut self.world, x, z);
|
||||
self.world
|
||||
.block_entities
|
||||
.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z));
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
for sy in 0..SECTIONS as i32 {
|
||||
renderer.remove((x, sy, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
// One pass for all of them.
|
||||
self.world
|
||||
.block_entities
|
||||
.retain(|k, _| !gone.contains(&(k.0 >> 4, k.2 >> 4)));
|
||||
}
|
||||
/// `handleBlockEntityData`: the block entity at `pos`, when it is of the
|
||||
/// packet's type, loads the tag (`loadWithComponents`); an empty tag
|
||||
/// changes nothing.
|
||||
fn remote_block_entity_data(&mut self, pos: [i32; 3], kind: i32, tag: &Tag) {
|
||||
pub(super) fn remote_block_entity_data(&mut self, pos: [i32; 3], kind: i32, tag: &Tag) {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
let Some(name) = self
|
||||
.remote
|
||||
@@ -1248,7 +1166,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// Keep the renderable block entities (chests, furnaces) in step with blocks.
|
||||
fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) {
|
||||
pub(super) fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) {
|
||||
let name = self.res.facts().get(state).name.clone();
|
||||
match BlockEntity::for_block(&name) {
|
||||
Some(entity) => {
|
||||
@@ -1704,36 +1622,7 @@ impl Game<'_> {
|
||||
})
|
||||
.clamp(-90.0, 90.0);
|
||||
}
|
||||
// ClientChunkCache.replaceWithPacketData: a column outside the
|
||||
// storage around the view centre is ignored.
|
||||
C::LevelChunkWithLight(p) if !self.remote_chunk_in_range(p.x, p.z) => {
|
||||
log::warn!(
|
||||
"Ignoring chunk since it's not in the view range: {}, {}",
|
||||
p.x,
|
||||
p.z
|
||||
);
|
||||
}
|
||||
C::LevelChunkWithLight(p) => match self.remote_chunk(&p) {
|
||||
Ok(chunk) => {
|
||||
let (x, z) = (p.x, p.z);
|
||||
self.streaming.insert_remote(&mut self.world, chunk);
|
||||
self.world
|
||||
.block_entities
|
||||
.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z));
|
||||
for info in &p.chunk.block_entities {
|
||||
let pos = (
|
||||
x * 16 + i32::from(info.packed_xz as u8 >> 4),
|
||||
i32::from(info.y),
|
||||
z * 16 + i32::from(info.packed_xz as u8 & 15),
|
||||
);
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
self.sync_block_entity(pos, state);
|
||||
// LevelChunk.replaceWithPacketData: the block entity loads its update tag.
|
||||
self.remote_block_entity_data([pos.0, pos.1, pos.2], info.kind, &info.tag);
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z),
|
||||
},
|
||||
C::LevelChunkWithLight(p) => self.remote_chunk(&p, None),
|
||||
C::LightUpdate(p) => self.remote_light_update(&p),
|
||||
C::ForgetLevelChunk(p) => {
|
||||
let [x, z] = p.pos;
|
||||
@@ -2234,6 +2123,7 @@ impl Game<'_> {
|
||||
self.apply_remote_health();
|
||||
if p.health <= 0.0 && self.screen != Screen::Dead && self.player.is_some() {
|
||||
self.screen = Screen::Dead;
|
||||
self.ui.death_time = 0;
|
||||
self.capture(false);
|
||||
}
|
||||
}
|
||||
@@ -2250,6 +2140,7 @@ impl Game<'_> {
|
||||
// screen, whatever health was last sent.
|
||||
if me && self.screen != Screen::Dead && self.player.is_some() {
|
||||
self.screen = Screen::Dead;
|
||||
self.ui.death_time = 0;
|
||||
self.capture(false);
|
||||
}
|
||||
}
|
||||
@@ -3288,6 +3179,11 @@ impl Game<'_> {
|
||||
);
|
||||
let was_flying = player.flying;
|
||||
self.sync_player_body();
|
||||
// LivingEntity.tickDeath: the local player counts its deathTime once
|
||||
// per client tick while dead (the camera's death roll and zoom).
|
||||
if self.screen == Screen::Dead {
|
||||
self.ui.death_time = self.ui.death_time.saturating_add(1);
|
||||
}
|
||||
let Some(player) = self.player.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -3616,7 +3512,7 @@ impl Game<'_> {
|
||||
// ticks), and only the server removes it.
|
||||
let (world, facts, collision) = (&self.world, self.res.facts(), self.collision);
|
||||
for d in self.dropped.iter_mut().filter(|_| running) {
|
||||
d.tick(world, facts, collision, false);
|
||||
d.tick(world, facts, collision, false, &self.res.motion().fluids);
|
||||
}
|
||||
head_lerps.retain(|_, (_, steps)| *steps > 0);
|
||||
for (item, ticks, at, eye, pitch, yaw) in using {
|
||||
@@ -4066,6 +3962,10 @@ impl Game<'_> {
|
||||
if let Some(placed) = &placed {
|
||||
self.predict_place(placed, seq);
|
||||
self.with_hand(hand, Game::consume_held);
|
||||
} else if let Some(r) = self.remote.as_mut() {
|
||||
// BlockItem.place plays its sound only once the block is set: the
|
||||
// server's resend of the target it refused is no placement.
|
||||
r.placing = None;
|
||||
}
|
||||
if reacts || placed.is_some() {
|
||||
self.with_hand(hand, Game::swing_arm);
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
//! A server's chunk columns (`ClientboundLevelChunkWithLightPacket`): the
|
||||
//! sections and light of each packet become a client column on a decoder
|
||||
//! thread as soon as the packet arrives, so the frame that handles it in
|
||||
//! order only inserts the result (`ClientPacketListener.handleLevelChunkWithLight`).
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy},
|
||||
streaming::Streaming,
|
||||
};
|
||||
use horizon_core::paletted::{PalettedContainer, Strategy};
|
||||
use horizon_protocol::{
|
||||
chunk::{LightData, SectionLight},
|
||||
packets::play::{self, Clientbound as C},
|
||||
registry::DimensionType,
|
||||
};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
mpsc::{self, TryRecvError},
|
||||
};
|
||||
|
||||
/// What turning a chunk packet into a client column depends on: the
|
||||
/// dimension's height and sky, and the server's biome registry mapped to
|
||||
/// ours. The connection replaces it when either changes, so a column decoded
|
||||
/// with an older one is decoded again.
|
||||
#[derive(Default)]
|
||||
pub(super) struct ChunkFormat {
|
||||
min_y: i32,
|
||||
sections: usize,
|
||||
has_skylight: bool,
|
||||
biome_map: Vec<u16>,
|
||||
biome_bits: u8,
|
||||
}
|
||||
|
||||
impl ChunkFormat {
|
||||
pub(super) fn new(dimension: &DimensionType, biome_map: Vec<u16>, biome_bits: u8) -> Self {
|
||||
Self {
|
||||
min_y: dimension.min_y,
|
||||
sections: dimension.sections(),
|
||||
has_skylight: dimension.has_skylight,
|
||||
biome_map,
|
||||
biome_bits,
|
||||
}
|
||||
}
|
||||
pub(super) fn with_dimension(&self, dimension: &DimensionType) -> Self {
|
||||
Self::new(dimension, self.biome_map.clone(), self.biome_bits)
|
||||
}
|
||||
|
||||
/// LevelChunkSection data into the client's fixed -64..320 column.
|
||||
fn column(&self, p: &play::LevelChunkWithLight) -> Result<Chunk, String> {
|
||||
let sections = p
|
||||
.chunk
|
||||
.sections(self.sections, 16, self.biome_bits)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut chunk = Chunk::empty(p.x, p.z);
|
||||
let offset = (self.min_y - MIN_Y).div_euclid(16);
|
||||
// Biome table index per quart cell of the dimension's own sections.
|
||||
let mut biome_cells: Vec<[u32; 64]> = Vec::with_capacity(sections.len());
|
||||
for (i, s) in sections.iter().enumerate() {
|
||||
let target = offset + i as i32;
|
||||
let mut cells = [0u32; 64];
|
||||
for (j, cell) in cells.iter_mut().enumerate() {
|
||||
*cell = u32::from(
|
||||
self.biome_map
|
||||
.get(s.biomes.get(j) as usize)
|
||||
.copied()
|
||||
.unwrap_or(0),
|
||||
);
|
||||
}
|
||||
biome_cells.push(cells);
|
||||
if !(0..SECTIONS as i32).contains(&target) {
|
||||
continue;
|
||||
}
|
||||
// A global section is as wide as the server's registry: 16 bits
|
||||
// from a vanilla server, wider from a Horizon host with the same
|
||||
// content mods. Read it at that width, then widen it to ours.
|
||||
let ours = block_strategy();
|
||||
let strategy = if ours.wire_has_palette(s.states.bits) {
|
||||
ours
|
||||
} else {
|
||||
Strategy::blocks(s.states.bits)
|
||||
};
|
||||
let palette = s.states.palette.iter().map(|&p| p as u32).collect();
|
||||
let words = s.states.data.iter().map(|&w| w as u64).collect();
|
||||
let mut blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if strategy.global_bits != ours.global_bits {
|
||||
let mut values = [0u32; 4096];
|
||||
blocks.unpack(&mut values);
|
||||
// Ids past our registry (a host with mods we lack) read as air.
|
||||
let limit = 1u64 << ours.global_bits;
|
||||
for v in &mut values {
|
||||
if u64::from(*v) >= limit {
|
||||
*v = 0;
|
||||
}
|
||||
}
|
||||
blocks = PalettedContainer::from_values(ours, &values);
|
||||
}
|
||||
let mut section = Section {
|
||||
blocks,
|
||||
biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells),
|
||||
light: Light::Uniform(0xF0),
|
||||
};
|
||||
section.compact();
|
||||
chunk.sections[target as usize] = Arc::new(section);
|
||||
}
|
||||
// Sections outside the dimension's range take its nearest biomes
|
||||
// (the column's top or bottom cell layer repeated).
|
||||
if !biome_cells.is_empty() {
|
||||
let last = biome_cells.len() - 1;
|
||||
for si in 0..SECTIONS as i32 {
|
||||
let i = si - offset;
|
||||
if (0..sections.len() as i32).contains(&i) {
|
||||
continue;
|
||||
}
|
||||
let (edge, layer) = if i < 0 { (0, 0) } else { (last, 3) };
|
||||
let mut cells = [0u32; 64];
|
||||
for (j, cell) in cells.iter_mut().enumerate() {
|
||||
*cell = biome_cells[edge][layer * 16 + j % 16];
|
||||
}
|
||||
Arc::make_mut(&mut chunk.sections[si as usize]).biomes =
|
||||
PalettedContainer::from_values(BIOME_STRATEGY, &cells);
|
||||
}
|
||||
}
|
||||
// ClientPacketListener.applyLightData: the column keeps the light
|
||||
// the server sent; nothing is relit.
|
||||
let (layers, above) = self.light(&p.light);
|
||||
horizon_client::light::light_from_layers(&mut chunk, &layers, above, self.has_skylight);
|
||||
Ok(chunk)
|
||||
}
|
||||
|
||||
/// `ClientPacketListener.readSectionList`: the sky and block layers of a
|
||||
/// light packet, by section of the client's column, and the sky light
|
||||
/// above the column's top section (from the light section just above
|
||||
/// it, else open sky).
|
||||
pub(super) fn light(&self, light: &LightData) -> (Vec<SectionLight>, [u8; 256]) {
|
||||
let mut layers: Vec<SectionLight> = vec![(None, None); SECTIONS];
|
||||
let sky = self.has_skylight;
|
||||
let mut above = [if sky { 15 } else { 0 }; 256];
|
||||
// Light section b is the dimension's section b - 1.
|
||||
let first = (self.min_y - MIN_Y).div_euclid(16) - 1;
|
||||
for (b, layer) in light.layers(self.sections + 2).into_iter().enumerate() {
|
||||
let si = first + b as i32;
|
||||
if (0..SECTIONS as i32).contains(&si) {
|
||||
layers[si as usize] = layer;
|
||||
} else if si == SECTIONS as i32
|
||||
&& sky
|
||||
&& let Some(l) = &layer.0
|
||||
{
|
||||
for (i, a) in above.iter_mut().enumerate() {
|
||||
*a = (l[i >> 1] >> ((i & 1) * 4)) & 15;
|
||||
}
|
||||
}
|
||||
}
|
||||
(layers, above)
|
||||
}
|
||||
}
|
||||
|
||||
type Decoded = (Box<C>, Result<Chunk, String>);
|
||||
|
||||
/// One thread that decodes chunk packets in the order they arrived; its
|
||||
/// results come back in that order, one per `submit`.
|
||||
pub(super) struct ChunkDecoder {
|
||||
jobs: mpsc::Sender<(Arc<ChunkFormat>, Box<C>)>,
|
||||
done: mpsc::Receiver<Decoded>,
|
||||
}
|
||||
|
||||
impl ChunkDecoder {
|
||||
pub(super) fn new() -> Self {
|
||||
let (jobs, todo) = mpsc::channel::<(Arc<ChunkFormat>, Box<C>)>();
|
||||
let (finished, done) = mpsc::channel();
|
||||
// The thread ends with the connection, when `jobs` is dropped.
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("Chunk decoder".into())
|
||||
.spawn(move || {
|
||||
// A frame waits for its columns, as it would for the render
|
||||
// thread's own work.
|
||||
horizon_threads::favour_current();
|
||||
for (format, packet) in todo {
|
||||
let column = match &*packet {
|
||||
C::LevelChunkWithLight(p) => format.column(p),
|
||||
_ => Err("not a chunk packet".into()),
|
||||
};
|
||||
if finished.send((packet, column)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("Horizon: no chunk decoder thread ({e}); chunks decode in the frame");
|
||||
}
|
||||
Self { jobs, done }
|
||||
}
|
||||
|
||||
/// Start decoding a chunk packet with the format it arrived under.
|
||||
/// Without a decoder thread the packet comes back undecoded.
|
||||
pub(super) fn submit(&self, format: Arc<ChunkFormat>, packet: Box<C>) -> Option<Box<C>> {
|
||||
self.jobs.send((format, packet)).err().map(|e| (e.0).1)
|
||||
}
|
||||
|
||||
/// The oldest submitted packet and its column, unless it is still
|
||||
/// decoding: a frame never waits for the decoder.
|
||||
pub(super) fn next(&self) -> Next {
|
||||
match self.done.try_recv() {
|
||||
Ok(decoded) => Next::Ready(decoded),
|
||||
Err(TryRecvError::Empty) => Next::Decoding,
|
||||
// The decoder thread panicked: its columns are gone.
|
||||
Err(TryRecvError::Disconnected) => Next::Lost,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) enum Next {
|
||||
Ready(Decoded),
|
||||
Decoding,
|
||||
Lost,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `handleLevelChunkWithLight`: the column replaces any loaded one, and
|
||||
/// its block entities load their update tags. `decoded` is the column the
|
||||
/// decoder made with `format`; another format since means decode again.
|
||||
pub(super) fn remote_chunk(
|
||||
&mut self,
|
||||
p: &play::LevelChunkWithLight,
|
||||
decoded: Option<(&Arc<ChunkFormat>, Result<Chunk, String>)>,
|
||||
) {
|
||||
// ClientChunkCache.replaceWithPacketData: a column outside the
|
||||
// storage around the view centre is ignored.
|
||||
if !self.remote_chunk_in_range(p.x, p.z) {
|
||||
log::warn!(
|
||||
"Ignoring chunk since it's not in the view range: {}, {}",
|
||||
p.x,
|
||||
p.z
|
||||
);
|
||||
return;
|
||||
}
|
||||
let Some(format) = self.remote.as_ref().map(|r| r.chunk_format.clone()) else {
|
||||
return;
|
||||
};
|
||||
let column = match decoded {
|
||||
Some((used, column)) if Arc::ptr_eq(used, &format) => column,
|
||||
_ => format.column(p),
|
||||
};
|
||||
let chunk = match column {
|
||||
Ok(chunk) => chunk,
|
||||
Err(e) => {
|
||||
log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (x, z) = (p.x, p.z);
|
||||
self.streaming.insert_remote(&mut self.world, chunk);
|
||||
self.world
|
||||
.block_entities
|
||||
.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z));
|
||||
for info in &p.chunk.block_entities {
|
||||
let pos = (
|
||||
x * 16 + i32::from(info.packed_xz as u8 >> 4),
|
||||
i32::from(info.y),
|
||||
z * 16 + i32::from(info.packed_xz as u8 & 15),
|
||||
);
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
self.sync_block_entity(pos, state);
|
||||
// LevelChunk.replaceWithPacketData: the block entity loads its update tag.
|
||||
self.remote_block_entity_data([pos.0, pos.1, pos.2], info.kind, &info.tag);
|
||||
}
|
||||
}
|
||||
|
||||
/// `handleLightUpdatePacket`: the sections it names take its light.
|
||||
pub(super) fn remote_light_update(&mut self, p: &play::LightUpdate) {
|
||||
let Some(format) = self.remote.as_ref().map(|r| r.chunk_format.clone()) else {
|
||||
return;
|
||||
};
|
||||
if !self.world.chunks.contains_key(&(p.x, p.z)) {
|
||||
return;
|
||||
}
|
||||
let (layers, _) = format.light(&p.light);
|
||||
let Some(chunk) = self.world.chunks.get_mut(&(p.x, p.z)) else {
|
||||
return;
|
||||
};
|
||||
let changed = horizon_client::light::update_light_layers(
|
||||
Arc::make_mut(chunk),
|
||||
&layers,
|
||||
format.has_skylight,
|
||||
);
|
||||
Streaming::light_updated(&mut self.world, p.x, p.z, &changed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_protocol::chunk::{ChunkData, Paletted, Section as Wire, Strategy as Wiring};
|
||||
|
||||
/// A column of `state` with biome 1 everywhere, unlit.
|
||||
fn packet(x: i32, state: i32) -> Box<C> {
|
||||
let section = Wire {
|
||||
non_empty: 4096,
|
||||
fluids: 0,
|
||||
states: Paletted::from_values(&[state; 4096], Wiring::Blocks, 16),
|
||||
biomes: Paletted::from_values(&[1; 64], Wiring::Biomes, 2),
|
||||
};
|
||||
let none = LightData {
|
||||
sky_mask: Vec::new(),
|
||||
block_mask: Vec::new(),
|
||||
empty_sky_mask: Vec::new(),
|
||||
empty_block_mask: Vec::new(),
|
||||
sky: Vec::new(),
|
||||
block: Vec::new(),
|
||||
};
|
||||
Box::new(C::LevelChunkWithLight(play::LevelChunkWithLight {
|
||||
x,
|
||||
z: -3,
|
||||
chunk: ChunkData {
|
||||
heightmaps: Vec::new(),
|
||||
buffer: ChunkData::from_sections(&vec![section; 24]),
|
||||
block_entities: Vec::new(),
|
||||
},
|
||||
light: none,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Columns come back one per packet, in the order the packets went in,
|
||||
/// as the frame would have decoded them itself.
|
||||
#[test]
|
||||
fn the_decoder_returns_columns_in_order() {
|
||||
let overworld = DimensionType::vanilla("minecraft:overworld");
|
||||
let format = Arc::new(ChunkFormat::new(&overworld, vec![0, 7, 9], 2));
|
||||
let decoder = ChunkDecoder::new();
|
||||
for x in 0..20 {
|
||||
assert!(decoder.submit(format.clone(), packet(x, 1 + x)).is_none());
|
||||
}
|
||||
for x in 0..20 {
|
||||
let (packet, column) = loop {
|
||||
match decoder.next() {
|
||||
Next::Ready(decoded) => break decoded,
|
||||
Next::Decoding => std::thread::yield_now(),
|
||||
Next::Lost => panic!("the decoder stopped"),
|
||||
}
|
||||
};
|
||||
let C::LevelChunkWithLight(p) = *packet else {
|
||||
panic!("not a chunk packet");
|
||||
};
|
||||
let (column, direct) = (column.unwrap(), format.column(&p).unwrap());
|
||||
assert_eq!((column.x, column.z), (x, -3));
|
||||
for (cx, y, cz) in [(0, -64, 0), (5, 70, 9), (15, 319, 15)] {
|
||||
assert_eq!(column.get(cx, y, cz), 1 + x as u32);
|
||||
assert_eq!(column.get(cx, y, cz), direct.get(cx, y, cz));
|
||||
// Wire biome 1 is our biome 7.
|
||||
assert_eq!(column.biome(cx, y, cz), 7);
|
||||
}
|
||||
}
|
||||
assert!(matches!(decoder.next(), Next::Decoding));
|
||||
}
|
||||
}
|
||||
@@ -353,7 +353,8 @@ impl Game<'_> {
|
||||
out.push(json!({"id": t.id, "kind": "minecraft:trident", "position": at(t.position)}));
|
||||
}
|
||||
for p in &self.creatures.projectiles {
|
||||
out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)}));
|
||||
out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position), "velocity": at(p.velocity),
|
||||
"player_owned": p.owner == Some(horizon_client::mobs::Who::Player)}));
|
||||
}
|
||||
for (kind, p, _) in self.potions.thrown_entities() {
|
||||
out.push(json!({"kind": kind, "position": at(p)}));
|
||||
|
||||
@@ -67,7 +67,9 @@ mod end_sky;
|
||||
mod flat;
|
||||
pub mod lightning;
|
||||
mod lod;
|
||||
mod native_pack;
|
||||
mod native_post;
|
||||
mod native_sky;
|
||||
mod occlusion;
|
||||
mod pack_atlas;
|
||||
pub mod pack_draw;
|
||||
@@ -501,7 +503,7 @@ pub struct Renderer {
|
||||
/// The shader pack's post-processing, and the dimension (legacy id) it was loaded for.
|
||||
pack_post: Option<(i32, Option<pack_post::PackPost>)>,
|
||||
/// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s.
|
||||
native_post: Option<native_post::NativePost>,
|
||||
native: Option<native_pack::NativePack>,
|
||||
/// Time the shader pack's passes on the GPU (F3, or `HORIZON_SHADER_PACK_TIMING`).
|
||||
pass_timing: bool,
|
||||
/// The entity vertices Horizon draws itself while a shader pack draws the others.
|
||||
@@ -2414,7 +2416,7 @@ impl Renderer {
|
||||
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
|
||||
world_post,
|
||||
pack_post: None,
|
||||
native_post: None,
|
||||
native: None,
|
||||
pass_timing: pack_timing::PassTiming::logging(),
|
||||
pack_entity_rest: Vec::new(),
|
||||
cloud_bindings,
|
||||
@@ -2924,41 +2926,40 @@ impl Renderer {
|
||||
});
|
||||
self.pack_post = Some((dimension, post));
|
||||
if self.pack_post.as_ref().is_some_and(|p| p.1.is_some()) {
|
||||
self.native_post = None;
|
||||
self.native = None;
|
||||
}
|
||||
report
|
||||
}
|
||||
/// Drops the running shader pack, of either kind.
|
||||
pub fn drop_shader_packs(&mut self) {
|
||||
self.pack_post = None;
|
||||
self.native_post = None;
|
||||
self.native = None;
|
||||
self.pack_atlas = None;
|
||||
}
|
||||
/// Runs the post passes of one of Horizon's own shader packs over the world from now on
|
||||
/// (`None`: no pack), with its options' values; replaces a `shaders/` pack. Returns the
|
||||
/// passes' labels; on an error the passes that ran keep running.
|
||||
/// Runs the sky and post stages of one of Horizon's own shader packs from now on (`None`:
|
||||
/// no pack), with its options' values; replaces a `shaders/` pack. Returns the stages'
|
||||
/// labels; on an error the pack that ran keeps running.
|
||||
pub fn set_native_shader_pack(
|
||||
&mut self,
|
||||
pack: Option<(horizon_shader_api::Report, Vec<(String, f64)>)>,
|
||||
) -> std::result::Result<Vec<String>, String> {
|
||||
let stages = pack.map(|(report, constants)| {
|
||||
let post: Vec<_> = report
|
||||
.stages
|
||||
.into_iter()
|
||||
.filter(|s| s.kind == horizon_shader_api::StageKind::Post)
|
||||
.collect();
|
||||
(post, constants)
|
||||
});
|
||||
let Some((post, constants)) = stages.filter(|(post, _)| !post.is_empty()) else {
|
||||
self.native_post = None;
|
||||
let Some((report, constants)) = pack else {
|
||||
self.native = None;
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let format = self.config.format.remove_srgb_suffix();
|
||||
let post = native_post::NativePost::new(&self.device, post, &constants, format)?;
|
||||
let labels = post.labels().into_iter().map(str::to_owned).collect();
|
||||
self.pack_post = None;
|
||||
self.pack_atlas = None;
|
||||
self.native_post = Some(post);
|
||||
let (pack, labels) = native_pack::NativePack::new(
|
||||
&self.device,
|
||||
&self.terrain_layout,
|
||||
report,
|
||||
&constants,
|
||||
format,
|
||||
)?;
|
||||
self.native = pack.draws().then_some(pack);
|
||||
if self.native.is_some() {
|
||||
self.pack_post = None;
|
||||
self.pack_atlas = None;
|
||||
}
|
||||
Ok(labels)
|
||||
}
|
||||
/// What a shader pack's gbuffers programs read from Horizon's geometry: the sky's, and
|
||||
@@ -3009,20 +3010,20 @@ impl Renderer {
|
||||
/// The running shader pack's timer, of either kind.
|
||||
fn pass_timer<'a>(
|
||||
pack: &'a mut Option<(i32, Option<pack_post::PackPost>)>,
|
||||
native: &'a mut Option<native_post::NativePost>,
|
||||
native: &'a mut Option<native_pack::NativePack>,
|
||||
) -> Option<&'a mut Option<pack_timing::PassTiming>> {
|
||||
match (pack, native) {
|
||||
(Some((_, Some(post))), _) => Some(&mut post.timing),
|
||||
(_, Some(post)) => Some(&mut post.timing),
|
||||
(_, Some(native)) => Some(&mut native.timing),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Each pass of the running shader pack with its median GPU time in milliseconds, while
|
||||
/// they are timed (`set_pass_timing`).
|
||||
pub fn shader_pass_times(&self) -> Vec<(String, f32)> {
|
||||
let timer = match (&self.pack_post, &self.native_post) {
|
||||
let timer = match (&self.pack_post, &self.native) {
|
||||
(Some((_, Some(post))), _) => post.timing.as_ref(),
|
||||
(_, Some(post)) => post.timing.as_ref(),
|
||||
(_, Some(native)) => native.timing.as_ref(),
|
||||
_ => None,
|
||||
};
|
||||
timer
|
||||
@@ -4052,8 +4053,8 @@ impl Renderer {
|
||||
// The world's targets: the screen, or the scaled target of `post`.
|
||||
let pack_post = !frame.title && self.pack_post.as_ref().is_some_and(|p| p.1.is_some());
|
||||
// One of Horizon's own packs reads the same world target.
|
||||
let native_post = !frame.title && self.native_post.is_some();
|
||||
if let Some(timer) = Self::pass_timer(&mut self.pack_post, &mut self.native_post)
|
||||
let native_post = !frame.title && self.native.as_ref().is_some_and(|n| n.post.is_some());
|
||||
if let Some(timer) = Self::pass_timer(&mut self.pack_post, &mut self.native)
|
||||
&& timer.is_some() != self.pass_timing
|
||||
{
|
||||
*timer = self
|
||||
@@ -4115,24 +4116,79 @@ impl Renderer {
|
||||
cull.bind_depth(&self.device, world_depth);
|
||||
}
|
||||
let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0);
|
||||
let clear = if frame.title || (frame.end_sky && !frame.underwater) {
|
||||
wgpu::Color::BLACK
|
||||
} else {
|
||||
wgpu::Color {
|
||||
r: f64::from(fog_color[0]),
|
||||
g: f64::from(fog_color[1]),
|
||||
b: f64::from(fog_color[2]),
|
||||
a: 1.0,
|
||||
}
|
||||
};
|
||||
let sky_visible = sky_open(frame);
|
||||
// One of Horizon's own packs: this frame's inputs; in a timed frame its sky draws in a
|
||||
// pass of its own, so that it has a time of its own.
|
||||
let mut native_sky_pass = false;
|
||||
if !frame.title
|
||||
&& let Some(native) = &mut self.native
|
||||
{
|
||||
let size = self
|
||||
.world_post
|
||||
.size()
|
||||
.filter(|_| scaled.is_some())
|
||||
.unwrap_or([self.config.width, self.config.height]);
|
||||
native.frame.write(&self.queue, frame, size);
|
||||
if let Some(t) = &mut native.timing {
|
||||
t.begin(&self.device, &self.queue);
|
||||
native_sky_pass =
|
||||
native.sky.is_some() && t.recording() && sky_visible && frame.skybox;
|
||||
}
|
||||
}
|
||||
if native_sky_pass
|
||||
&& let Some(native) = &mut self.native
|
||||
&& let Some(sky) = &native.sky
|
||||
{
|
||||
if let Some(t) = &mut native.timing {
|
||||
let format = self.config.format.remove_srgb_suffix();
|
||||
t.mark(&self.device, &mut encoder, (world_view, format));
|
||||
}
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some(&sky.label),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: world_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(clear),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: world_depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(0.0),
|
||||
store: wgpu::StoreOp::Discard,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
timestamp_writes: native.timing.as_mut().and_then(|t| t.writes(&sky.label)),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
sky.draw(&mut pass, &native.frame);
|
||||
}
|
||||
{
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: world_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(
|
||||
if frame.title || (frame.end_sky && !frame.underwater) {
|
||||
wgpu::Color::BLACK
|
||||
} else {
|
||||
wgpu::Color {
|
||||
r: f64::from(fog_color[0]),
|
||||
g: f64::from(fog_color[1]),
|
||||
b: f64::from(fog_color[2]),
|
||||
a: 1.0,
|
||||
}
|
||||
},
|
||||
),
|
||||
load: if native_sky_pass {
|
||||
wgpu::LoadOp::Load
|
||||
} else {
|
||||
wgpu::LoadOp::Clear(clear)
|
||||
},
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
@@ -4155,11 +4211,19 @@ impl Renderer {
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
let sky_visible = sky_open(frame);
|
||||
if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) {
|
||||
if !frame.title && frame.skybox && !pack_draws_sky {
|
||||
pass.set_pipeline(&self.sky);
|
||||
pass.draw(0..3, 0..1);
|
||||
if !frame.title && frame.skybox && !pack_draws_sky && !native_sky_pass {
|
||||
match self
|
||||
.native
|
||||
.as_ref()
|
||||
.and_then(|n| Some((n.sky.as_ref()?, &n.frame)))
|
||||
{
|
||||
Some((sky, native)) => sky.draw(&mut pass, native),
|
||||
None => {
|
||||
pass.set_pipeline(&self.sky);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if frame.title {
|
||||
self.panorama.draw(&mut pass);
|
||||
@@ -4511,17 +4575,17 @@ impl Renderer {
|
||||
self.pack_post = Some((dimension, Some(post)));
|
||||
} else if let Some((color, depth)) = &scaled
|
||||
&& native_post
|
||||
&& let Some(post) = &mut self.native_post
|
||||
&& let Some(native) = &mut self.native
|
||||
&& let Some(post) = &mut native.post
|
||||
{
|
||||
let size = self.world_post.size().unwrap_or([1, 1]);
|
||||
post.run(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&mut encoder,
|
||||
(color, depth),
|
||||
&view_target,
|
||||
frame,
|
||||
size,
|
||||
native.timing.as_mut(),
|
||||
);
|
||||
} else if scaled.is_some() {
|
||||
self.world_post.finish(&mut encoder, &view_target);
|
||||
@@ -4694,7 +4758,7 @@ impl Renderer {
|
||||
timer.submitted(&self.queue);
|
||||
timer.collect(&self.device, &mut self.gpu_times);
|
||||
}
|
||||
if let Some(Some(timer)) = Self::pass_timer(&mut self.pack_post, &mut self.native_post) {
|
||||
if let Some(Some(timer)) = Self::pass_timer(&mut self.pack_post, &mut self.native) {
|
||||
timer.submitted(&self.queue);
|
||||
}
|
||||
if let Some((path, buffer)) = readback {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! One of Horizon's own shader packs while it runs (docs/shaders.md): the frame its stages
|
||||
//! read, its sky and post stages, and the timer of their passes.
|
||||
|
||||
use horizon_shader_api::{Report, StageKind};
|
||||
|
||||
use super::native_post::{NativeFrame, NativePost};
|
||||
use super::native_sky::NativeSky;
|
||||
use super::pack_timing::PassTiming;
|
||||
|
||||
pub struct NativePack {
|
||||
pub frame: NativeFrame,
|
||||
pub sky: Option<NativeSky>,
|
||||
pub post: Option<NativePost>,
|
||||
/// GPU time of each pass, while the renderer asks for it (`pack_timing.rs`).
|
||||
pub timing: Option<PassTiming>,
|
||||
}
|
||||
|
||||
impl NativePack {
|
||||
/// The pack of the checked stages `report` with the option values `constants`, drawing
|
||||
/// onto targets of `format`; `globals` is the terrain's group 0, which the sky reads.
|
||||
/// Also returns its stages' labels, in the order they draw. Errors name the stage wgpu
|
||||
/// refused.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
globals: &wgpu::BindGroupLayout,
|
||||
report: Report,
|
||||
constants: &[(String, f64)],
|
||||
format: wgpu::TextureFormat,
|
||||
) -> Result<(Self, Vec<String>), String> {
|
||||
let frame = NativeFrame::new(device);
|
||||
let (post, others): (Vec<_>, Vec<_>) = report
|
||||
.stages
|
||||
.into_iter()
|
||||
.partition(|s| s.kind == StageKind::Post);
|
||||
let sky = others
|
||||
.iter()
|
||||
.find(|s| s.kind == StageKind::Sky)
|
||||
.map(|stage| NativeSky::new(device, globals, &frame, stage, constants, format))
|
||||
.transpose()?;
|
||||
let post = (!post.is_empty())
|
||||
.then(|| NativePost::new(device, post, constants, format, &frame))
|
||||
.transpose()?;
|
||||
let mut labels: Vec<String> = sky.iter().map(|s| s.label.clone()).collect();
|
||||
if let Some(post) = &post {
|
||||
labels.extend(post.labels().into_iter().map(str::to_owned));
|
||||
}
|
||||
let pack = Self {
|
||||
frame,
|
||||
sky,
|
||||
post,
|
||||
timing: None,
|
||||
};
|
||||
Ok((pack, labels))
|
||||
}
|
||||
|
||||
/// Whether the pack draws anything the game runs today.
|
||||
pub fn draws(&self) -> bool {
|
||||
self.sky.is_some() || self.post.is_some()
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//! the pack's options as pipeline constants. A pass reads bind group 3: the frame, the world's
|
||||
//! colour and depth, the previous pass's output and two samplers. Passes before the last write
|
||||
//! half-float targets of the world's size, so values over 1 carry to the next; the last draws
|
||||
//! onto the screen.
|
||||
//! onto the screen. Every stage of a pack reads the same `frame`, written once a frame
|
||||
//! (`NativeFrame`).
|
||||
|
||||
use glam::{Mat4, Vec3};
|
||||
use horizon_shader_api::{Frame as FrameInputs, check::CheckedStage, stages::GROUP};
|
||||
@@ -25,12 +26,87 @@ pub struct NativePost {
|
||||
targets: Option<([u32; 2], [wgpu::TextureView; 2])>,
|
||||
/// One bind group per pass, for these world views.
|
||||
groups: Option<(WorldViews, Vec<wgpu::BindGroup>)>,
|
||||
start: std::time::Instant,
|
||||
frames: u32,
|
||||
/// The screen's colour format, the world target's too.
|
||||
format: wgpu::TextureFormat,
|
||||
/// GPU time of each pass, while the renderer asks for it (`pack_timing.rs`).
|
||||
pub timing: Option<super::pack_timing::PassTiming>,
|
||||
}
|
||||
|
||||
/// The `frame` every stage of a pack reads (group 3, binding 0), written once a frame.
|
||||
pub struct NativeFrame {
|
||||
pub(super) buffer: wgpu::Buffer,
|
||||
/// Group 3 of the stages that read only the frame (the sky).
|
||||
pub layout: wgpu::BindGroupLayout,
|
||||
pub group: wgpu::BindGroup,
|
||||
start: std::time::Instant,
|
||||
frames: u32,
|
||||
}
|
||||
|
||||
/// The uniform `frame` at binding 0, read by `visibility`.
|
||||
fn frame_entry(visibility: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: wgpu::BufferSize::new(size_of::<FrameInputs>() as u64),
|
||||
},
|
||||
count: None,
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeFrame {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Native shader pack frame"),
|
||||
size: size_of::<FrameInputs>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Native shader pack frame"),
|
||||
entries: &[frame_entry(wgpu::ShaderStages::VERTEX_FRAGMENT)],
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Native shader pack frame"),
|
||||
layout: &layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
Self {
|
||||
buffer,
|
||||
layout,
|
||||
group,
|
||||
start: std::time::Instant::now(),
|
||||
frames: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes this frame's inputs, for a world of `size`.
|
||||
pub fn write(&mut self, queue: &wgpu::Queue, frame: &Frame, size: [u32; 2]) {
|
||||
let seconds = self.start.elapsed().as_secs_f32() % 3600.0;
|
||||
let inputs = frame_inputs(frame, size, seconds, self.frames);
|
||||
self.frames = self.frames.wrapping_add(1);
|
||||
queue.write_buffer(&self.buffer, 0, bytemuck::bytes_of(&inputs));
|
||||
}
|
||||
}
|
||||
|
||||
/// The option values of `constants` that `module` declares as overrides (wgpu refuses others).
|
||||
pub fn present_constants<'a>(
|
||||
module: &naga::Module,
|
||||
constants: &'a [(String, f64)],
|
||||
) -> Vec<(&'a str, f64)> {
|
||||
constants
|
||||
.iter()
|
||||
.filter(|(id, _)| {
|
||||
module
|
||||
.overrides
|
||||
.iter()
|
||||
.any(|(_, o)| o.name.as_ref() == Some(id))
|
||||
})
|
||||
.map(|(id, v)| (id.as_str(), *v))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn texture_entry(binding: u32, sample_type: wgpu::TextureSampleType) -> wgpu::BindGroupLayoutEntry {
|
||||
@@ -63,21 +139,13 @@ impl NativePost {
|
||||
stages: Vec<CheckedStage>,
|
||||
constants: &[(String, f64)],
|
||||
format: wgpu::TextureFormat,
|
||||
frame: &NativeFrame,
|
||||
) -> Result<Self, String> {
|
||||
let float = wgpu::TextureSampleType::Float { filterable: true };
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Native shader pack post"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: wgpu::BufferSize::new(size_of::<FrameInputs>() as u64),
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
frame_entry(wgpu::ShaderStages::FRAGMENT),
|
||||
texture_entry(1, float),
|
||||
texture_entry(2, wgpu::TextureSampleType::Depth),
|
||||
texture_entry(3, float),
|
||||
@@ -95,17 +163,7 @@ impl NativePost {
|
||||
let count = stages.len();
|
||||
let mut passes = Vec::with_capacity(count);
|
||||
for (i, stage) in stages.into_iter().enumerate() {
|
||||
let present: Vec<(&str, f64)> = constants
|
||||
.iter()
|
||||
.filter(|(id, _)| {
|
||||
stage
|
||||
.module
|
||||
.overrides
|
||||
.iter()
|
||||
.any(|(_, o)| o.name.as_ref() == Some(id))
|
||||
})
|
||||
.map(|(id, v)| (id.as_str(), *v))
|
||||
.collect();
|
||||
let present = present_constants(&stage.module, constants);
|
||||
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some(&stage.label),
|
||||
@@ -145,12 +203,6 @@ impl NativePost {
|
||||
}
|
||||
passes.push((stage.label, pipeline));
|
||||
}
|
||||
let frame = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Native shader pack frame"),
|
||||
size: size_of::<FrameInputs>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let sampler = |label, filter| {
|
||||
device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some(label),
|
||||
@@ -162,15 +214,12 @@ impl NativePost {
|
||||
Ok(Self {
|
||||
passes,
|
||||
layout,
|
||||
frame,
|
||||
frame: frame.buffer.clone(),
|
||||
linear: sampler("Native shader pack linear", wgpu::FilterMode::Linear),
|
||||
nearest: sampler("Native shader pack nearest", wgpu::FilterMode::Nearest),
|
||||
targets: None,
|
||||
groups: None,
|
||||
start: std::time::Instant::now(),
|
||||
frames: 0,
|
||||
format,
|
||||
timing: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -264,37 +313,18 @@ impl NativePost {
|
||||
}
|
||||
|
||||
/// Runs the passes over the world target `world` (colour, depth) of `size`, the last onto
|
||||
/// `screen`.
|
||||
/// `screen`, timed by `timing` when it times this frame.
|
||||
pub fn run(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
world: (&wgpu::TextureView, &wgpu::TextureView),
|
||||
screen: &wgpu::TextureView,
|
||||
frame: &Frame,
|
||||
size: [u32; 2],
|
||||
) {
|
||||
let seconds = self.start.elapsed().as_secs_f32() % 3600.0;
|
||||
let inputs = frame_inputs(frame, size, seconds, self.frames);
|
||||
self.frames = self.frames.wrapping_add(1);
|
||||
self.draw(device, queue, encoder, world, screen, &inputs, size);
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
world: (&wgpu::TextureView, &wgpu::TextureView),
|
||||
screen: &wgpu::TextureView,
|
||||
inputs: &FrameInputs,
|
||||
size: [u32; 2],
|
||||
mut timing: Option<&mut super::pack_timing::PassTiming>,
|
||||
) {
|
||||
self.prepare(device, world, size);
|
||||
queue.write_buffer(&self.frame, 0, bytemuck::bytes_of(inputs));
|
||||
if let Some(t) = &mut self.timing {
|
||||
t.begin(device, queue);
|
||||
if let Some(t) = timing.as_deref_mut() {
|
||||
t.mark(device, encoder, (world.0, self.format));
|
||||
}
|
||||
let Some((_, groups)) = &self.groups else {
|
||||
@@ -317,7 +347,7 @@ impl NativePost {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some(label),
|
||||
color_attachments: &attachments,
|
||||
timestamp_writes: self.timing.as_mut().and_then(|t| t.writes(label)),
|
||||
timestamp_writes: timing.as_deref_mut().and_then(|t| t.writes(label)),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
@@ -437,8 +467,20 @@ mod tests {
|
||||
.into();
|
||||
let report = check(&Pack::from_files(files).unwrap()).unwrap();
|
||||
let format = wgpu::TextureFormat::Rgba8Unorm;
|
||||
let mut post =
|
||||
NativePost::new(&device, report.stages, &[("gain".into(), 1.0)], format).unwrap();
|
||||
let frame = NativeFrame::new(&device);
|
||||
queue.write_buffer(
|
||||
&frame.buffer,
|
||||
0,
|
||||
bytemuck::bytes_of(&FrameInputs::default()),
|
||||
);
|
||||
let mut post = NativePost::new(
|
||||
&device,
|
||||
report.stages,
|
||||
&[("gain".into(), 1.0)],
|
||||
format,
|
||||
&frame,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(post.labels(), ["a.wgsl", "b.wgsl"]);
|
||||
|
||||
let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING;
|
||||
@@ -478,15 +520,7 @@ mod tests {
|
||||
..Default::default()
|
||||
});
|
||||
let view = screen.create_view(&Default::default());
|
||||
post.draw(
|
||||
&device,
|
||||
&queue,
|
||||
&mut encoder,
|
||||
(&color, &depth),
|
||||
&view,
|
||||
&FrameInputs::default(),
|
||||
[4, 4],
|
||||
);
|
||||
post.run(&device, &mut encoder, (&color, &depth), &view, [4, 4], None);
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT * 4),
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
//! The sky stage of Horizon's own shader packs (docs/shaders.md): the pack's `sky` function,
|
||||
//! called for each pixel of the sky disc with vanilla's colour along its view ray. The
|
||||
//! pipeline's shader is the pack's stage (`CheckedStage::source`) followed by a copy of the
|
||||
//! renderer's sky (terrain.wgsl's `Globals`, `linear_fog` and sky section) whose names all
|
||||
//! take a `horizon_sky_` prefix, so none can meet a pack's (the check refuses `horizon_`
|
||||
//! names). It reads the renderer's globals (group 0) and the pack's frame (group 3), and
|
||||
//! draws where vanilla's sky draws; the sun, moon, stars and the dark disc are drawn over it.
|
||||
|
||||
use horizon_shader_api::{check::CheckedStage, stages::GROUP};
|
||||
|
||||
use super::native_post::{NativeFrame, present_constants};
|
||||
|
||||
const PREFIX: &str = "horizon_sky_";
|
||||
const TERRAIN: &str = include_str!("../terrain.wgsl");
|
||||
|
||||
/// The fragment entry that calls the pack: vanilla's colour in, an opaque colour out.
|
||||
const PACK_ENTRY: &str = "
|
||||
@fragment fn horizon_sky_fs_pack(in: horizon_sky_SkyOut) -> @location(0) vec4<f32> {
|
||||
let d = horizon_sky_view_ray(in.ndc);
|
||||
return vec4(sky(SkyInput(d, vec4(horizon_sky_sky_along_ray(d), 1.0))).rgb, 1.0);
|
||||
}
|
||||
";
|
||||
|
||||
pub struct NativeSky {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// The text of `source` from the line starting with `start` up to (not including) the one
|
||||
/// starting with `end`.
|
||||
fn section<'a>(source: &'a str, start: &str, end: &str) -> &'a str {
|
||||
let from = source
|
||||
.find(&format!("\n{start}"))
|
||||
.expect("terrain.wgsl has the section")
|
||||
+ 1;
|
||||
let to = from
|
||||
+ source[from..]
|
||||
.find(&format!("\n{end}"))
|
||||
.expect("terrain.wgsl ends the section")
|
||||
+ 1;
|
||||
&source[from..to]
|
||||
}
|
||||
|
||||
/// terrain.wgsl's sky with every name it declares (and `globals`) prefixed.
|
||||
fn vanilla_sky() -> String {
|
||||
let text = [
|
||||
section(TERRAIN, "struct Globals {", "@group(0) @binding(0)"),
|
||||
section(TERRAIN, "fn linear_fog(", "fn apply_fog("),
|
||||
section(TERRAIN, "struct SkyOut {", "// rendertype_lines"),
|
||||
]
|
||||
.concat();
|
||||
let mut names = vec!["globals"];
|
||||
for line in text.lines() {
|
||||
let line = line
|
||||
.trim_start_matches("@vertex ")
|
||||
.trim_start_matches("@fragment ");
|
||||
for keyword in ["fn ", "struct ", "const "] {
|
||||
if let Some(rest) = line.strip_prefix(keyword) {
|
||||
let end = rest
|
||||
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.unwrap_or(rest.len());
|
||||
names.push(&rest[..end]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::with_capacity(text.len() * 2);
|
||||
let mut word = String::new();
|
||||
let flush = |word: &mut String, out: &mut String| {
|
||||
if names.contains(&word.as_str()) {
|
||||
out.push_str(PREFIX);
|
||||
}
|
||||
out.push_str(word);
|
||||
word.clear();
|
||||
};
|
||||
for c in text.chars() {
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
word.push(c);
|
||||
} else {
|
||||
flush(&mut word, &mut out);
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
flush(&mut word, &mut out);
|
||||
out + &format!("@group(0) @binding(0) var<uniform> {PREFIX}globals: {PREFIX}Globals;\n")
|
||||
}
|
||||
|
||||
/// The sky shader for the pack's sky stage `source`.
|
||||
fn shader_source(source: &str) -> String {
|
||||
format!(
|
||||
"{source}\n// Horizon's sky (terrain.wgsl)\n{}{PACK_ENTRY}",
|
||||
vanilla_sky()
|
||||
)
|
||||
}
|
||||
|
||||
/// A sky pipeline over `module` whose fragment entry is `fragment`.
|
||||
fn pipeline(
|
||||
device: &wgpu::Device,
|
||||
layout: &wgpu::PipelineLayout,
|
||||
module: &wgpu::ShaderModule,
|
||||
fragment: &str,
|
||||
constants: &[(&str, f64)],
|
||||
format: wgpu::TextureFormat,
|
||||
) -> wgpu::RenderPipeline {
|
||||
let options = wgpu::PipelineCompilationOptions {
|
||||
constants,
|
||||
..Default::default()
|
||||
};
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Native shader pack sky"),
|
||||
layout: Some(layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some("horizon_sky_vs_sky"),
|
||||
compilation_options: options.clone(),
|
||||
buffers: &[],
|
||||
},
|
||||
primitive: Default::default(),
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(false),
|
||||
depth_compare: Some(wgpu::CompareFunction::Always),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some(fragment),
|
||||
compilation_options: options,
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The sky's naga module and the layout of its pipelines: `globals` at group 0, the frame
|
||||
/// at group 3.
|
||||
fn build(
|
||||
device: &wgpu::Device,
|
||||
globals: &wgpu::BindGroupLayout,
|
||||
frame: &NativeFrame,
|
||||
stage: &CheckedStage,
|
||||
) -> Result<(naga::Module, wgpu::PipelineLayout), String> {
|
||||
let text = shader_source(&stage.source);
|
||||
let module = naga::front::wgsl::parse_str(&text)
|
||||
.map_err(|e| format!("{}: {}", stage.file, e.emit_to_string(&text)))?;
|
||||
let mut groups: [Option<&wgpu::BindGroupLayout>; GROUP as usize + 1] = Default::default();
|
||||
groups[0] = Some(globals);
|
||||
groups[GROUP as usize] = Some(&frame.layout);
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Native shader pack sky"),
|
||||
bind_group_layouts: &groups,
|
||||
..Default::default()
|
||||
});
|
||||
Ok((module, layout))
|
||||
}
|
||||
|
||||
impl NativeSky {
|
||||
/// The pipeline of the pack's sky `stage` with the option values `constants`, drawing
|
||||
/// onto the world's target of `format`; `globals` is the terrain's group 0.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
globals: &wgpu::BindGroupLayout,
|
||||
frame: &NativeFrame,
|
||||
stage: &CheckedStage,
|
||||
constants: &[(String, f64)],
|
||||
format: wgpu::TextureFormat,
|
||||
) -> Result<Self, String> {
|
||||
let (module, layout) = build(device, globals, frame, stage)?;
|
||||
let present = present_constants(&module, constants);
|
||||
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some(&stage.label),
|
||||
source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)),
|
||||
});
|
||||
let pipeline = pipeline(
|
||||
device,
|
||||
&layout,
|
||||
&module,
|
||||
"horizon_sky_fs_pack",
|
||||
&present,
|
||||
format,
|
||||
);
|
||||
if let Some(e) = pollster::block_on(scope.pop()) {
|
||||
return Err(format!("{}: {e}", stage.file));
|
||||
}
|
||||
Ok(Self {
|
||||
pipeline,
|
||||
label: stage.label.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Draws the sky in a pass whose group 0 is the terrain's.
|
||||
pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>, frame: &NativeFrame) {
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(GROUP, &frame.group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_shader_api::{Frame as FrameInputs, MANIFEST, Pack, StageKind, check};
|
||||
|
||||
fn stage(sky: &str) -> CheckedStage {
|
||||
let mut manifest = "schema = 1\nid = \"t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.1\"\n\
|
||||
[sky]\nfile = \"sky.wgsl\"\n"
|
||||
.to_owned();
|
||||
if sky.contains("gain") {
|
||||
manifest += "[[options]]\nid = \"gain\"\nname = \"Gain\"\ntype = \"float\"\n\
|
||||
default = 1.0\nmin = 0.0\nmax = 2.0\n";
|
||||
}
|
||||
let manifest = manifest.as_str();
|
||||
let files = [(MANIFEST, manifest), ("sky.wgsl", sky)]
|
||||
.map(|(n, t)| (n.to_owned(), t.as_bytes().to_vec()))
|
||||
.into();
|
||||
let mut report = check(&Pack::from_files(files).unwrap()).unwrap();
|
||||
assert_eq!(report.stages[0].kind, StageKind::Sky);
|
||||
report.stages.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_renderer_s_sky_takes_a_prefix_and_validates_with_a_pack() {
|
||||
let sky = vanilla_sky();
|
||||
for name in [
|
||||
"Globals",
|
||||
"SkyOut",
|
||||
"view_ray",
|
||||
"PI",
|
||||
"sky_along_ray",
|
||||
"linear_fog",
|
||||
"fs_sky",
|
||||
] {
|
||||
assert!(sky.contains(&format!("{PREFIX}{name}")), "{name}");
|
||||
}
|
||||
// A pack may use the renderer's names for its own things.
|
||||
let own = "override gain: f32;\nconst PI: f32 = 3.0;\nfn view_ray() -> f32 { return PI; }\n\
|
||||
fn sky(input: SkyInput) -> vec4<f32> { return input.color * gain * view_ray(); }\n";
|
||||
let text = shader_source(&stage(own).source);
|
||||
let module = naga::front::wgsl::parse_str(&text).unwrap_or_else(|e| {
|
||||
panic!("{}", e.emit_to_string(&text));
|
||||
});
|
||||
naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::default(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Vanilla's sky and two packs over the same globals: one that returns its input draws
|
||||
/// vanilla's pixels, one that inverts them draws the inverse (and stays opaque).
|
||||
#[test]
|
||||
fn a_pack_gets_vanilla_s_colour_and_draws_opaque() {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
|
||||
return;
|
||||
};
|
||||
let (device, queue) =
|
||||
pollster::block_on(adapter.request_device(&Default::default())).unwrap();
|
||||
let format = wgpu::TextureFormat::Rgba8Unorm;
|
||||
let globals_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let mut globals: super::super::Globals = bytemuck::Zeroable::zeroed();
|
||||
globals.inverse_view = glam::Mat4::IDENTITY.to_cols_array_2d();
|
||||
globals.misc = [0.0, 0.0, 1.0, 1.0];
|
||||
globals.fog_color = [0.2, 0.4, 0.6, 1.0];
|
||||
globals.sky_color = [0.5, 0.7, 1.0, 1.0];
|
||||
globals.fog_ends = [64.0, 0.0, 0.0, 0.0];
|
||||
let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: size_of::<super::super::Globals>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
queue.write_buffer(&globals_buffer, 0, bytemuck::bytes_of(&globals));
|
||||
let globals_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &globals_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: globals_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
let frame = NativeFrame::new(&device);
|
||||
queue.write_buffer(
|
||||
&frame.buffer,
|
||||
0,
|
||||
bytemuck::bytes_of(&FrameInputs::default()),
|
||||
);
|
||||
|
||||
let gain = [("gain".to_owned(), 1.0)];
|
||||
let draw = |stage: &CheckedStage, vanilla: bool| -> Vec<u8> {
|
||||
let sky =
|
||||
NativeSky::new(&device, &globals_layout, &frame, stage, &gain, format).unwrap();
|
||||
let pipeline = if vanilla {
|
||||
let (module, layout) = build(&device, &globals_layout, &frame, stage).unwrap();
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)),
|
||||
});
|
||||
pipeline(&device, &layout, &module, "horizon_sky_fs_sky", &[], format)
|
||||
} else {
|
||||
sky.pipeline.clone()
|
||||
};
|
||||
let texture = |format, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d {
|
||||
width: 4,
|
||||
height: 4,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let color = texture(
|
||||
format,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
);
|
||||
let depth = texture(
|
||||
wgpu::TextureFormat::Depth32Float,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
);
|
||||
let (color_view, depth_view) = (
|
||||
color.create_view(&Default::default()),
|
||||
depth.create_view(&Default::default()),
|
||||
);
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: None,
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &color_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &depth_view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(0.0),
|
||||
store: wgpu::StoreOp::Discard,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &globals_group, &[]);
|
||||
pass.set_pipeline(&pipeline);
|
||||
pass.set_bind_group(GROUP, &frame.group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT * 4),
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
encoder.copy_texture_to_buffer(
|
||||
color.as_image_copy(),
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT),
|
||||
rows_per_image: Some(4),
|
||||
},
|
||||
},
|
||||
color.size(),
|
||||
);
|
||||
queue.submit([encoder.finish()]);
|
||||
buffer
|
||||
.slice(..)
|
||||
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
let bytes = buffer.slice(..).get_mapped_range().unwrap().to_vec();
|
||||
(0..4)
|
||||
.flat_map(|row| {
|
||||
let start = row * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
|
||||
bytes[start..start + 16].to_vec()
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let same = stage("fn sky(input: SkyInput) -> vec4<f32> { return input.color; }\n");
|
||||
let vanilla = draw(&same, true);
|
||||
assert_eq!(draw(&same, false), vanilla);
|
||||
// The top row looks up into the sky disc, the bottom one down into the fog.
|
||||
assert_ne!(vanilla[..4], vanilla[vanilla.len() - 4..]);
|
||||
let inverse = stage(
|
||||
"override gain: f32;\nfn sky(input: SkyInput) -> vec4<f32> { return vec4(vec3(gain) - input.color.rgb, 0.25); }\n",
|
||||
);
|
||||
let inverted = draw(&inverse, false);
|
||||
for (got, want) in inverted.chunks(4).zip(vanilla.chunks(4)) {
|
||||
assert_eq!(got[3], 255);
|
||||
for i in 0..3 {
|
||||
assert!(got[i].abs_diff(255 - want[i]) <= 1, "{got:?} {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,11 @@ impl PassTiming {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the frame being recorded is timed.
|
||||
pub fn recording(&self) -> bool {
|
||||
matches!(self.stage, Stage::Recording)
|
||||
}
|
||||
|
||||
/// Timestamp writes for the pass `name`, in a timed frame.
|
||||
pub fn writes(&mut self, name: &str) -> Option<wgpu::RenderPassTimestampWrites<'_>> {
|
||||
let i = self.push(name)?;
|
||||
|
||||
@@ -2175,17 +2175,24 @@ impl Hub {
|
||||
if g.spectator() || g.sleeping {
|
||||
return (false, false);
|
||||
}
|
||||
let height = if g.fall_flying {
|
||||
0.6
|
||||
// getBoundingBox: the box of the body's pose (swimming and crawling
|
||||
// are 0.6 tall), so a swimmer under a ceiling isn't sent back.
|
||||
let (half, height) = if g.fall_flying {
|
||||
(0.3, 0.6)
|
||||
} else if let Some(m) = &g.motion {
|
||||
(
|
||||
f64::from(m.dimensions.width) / 2.0,
|
||||
f64::from(m.dimensions.height),
|
||||
)
|
||||
} else if g.sneaking {
|
||||
1.5
|
||||
(0.3, 1.5)
|
||||
} else {
|
||||
1.8
|
||||
(0.3, 1.8)
|
||||
};
|
||||
let at = |p: [f64; 3]| {
|
||||
Aabb::new(
|
||||
Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3),
|
||||
Vec3::new(p[0] + 0.3, p[1] + height, p[2] + 0.3),
|
||||
Vec3::new(p[0] - half, p[1], p[2] - half),
|
||||
Vec3::new(p[0] + half, p[1] + height, p[2] + half),
|
||||
)
|
||||
};
|
||||
let (old, new) = (at(g.position), at(to));
|
||||
|
||||
@@ -44,7 +44,7 @@ use std::{
|
||||
|
||||
pub(crate) mod environment;
|
||||
mod fluids;
|
||||
pub use fluids::{FluidResources, LAVA, PlayerFluids, WATER};
|
||||
pub use fluids::{FluidResources, FluidTags, LAVA, PlayerFluids, WATER};
|
||||
|
||||
pub struct MotionResources {
|
||||
pub attributes: Arc<Catalog>,
|
||||
|
||||
@@ -103,10 +103,10 @@ fn is_tagged(kind: FluidKind, tag: FluidTagId) -> bool {
|
||||
}
|
||||
impl PlayerMotion {
|
||||
pub fn fluid_height(&self, tag: FluidTagId) -> f64 {
|
||||
self.fluids.interaction.fluid_height(&Membership, tag)
|
||||
self.fluids.interaction.fluid_height(&FluidTags, tag)
|
||||
}
|
||||
pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool {
|
||||
self.fluids.interaction.is_eye_in_fluid(&Membership, tag)
|
||||
self.fluids.interaction.is_eye_in_fluid(&FluidTags, tag)
|
||||
}
|
||||
/// `LocalPlayer.isUnderWater`: `wasUnderwater`, the eye sample `Player.tick`
|
||||
/// takes before the base tick (`Entity.isUnderWater` also needs the body
|
||||
@@ -116,11 +116,12 @@ impl PlayerMotion {
|
||||
}
|
||||
/// `Entity.isInLava`.
|
||||
pub fn is_in_lava(&self) -> bool {
|
||||
!self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA)
|
||||
!self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&FluidTags, LAVA)
|
||||
}
|
||||
}
|
||||
struct Membership;
|
||||
impl FluidMembership for Membership {
|
||||
/// Which fluids `FluidTags.WATER` and `FluidTags.LAVA` hold.
|
||||
pub struct FluidTags;
|
||||
impl FluidMembership for FluidTags {
|
||||
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
|
||||
is_tagged(kind, tag)
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ pub struct Moved {
|
||||
pub name: &'static str,
|
||||
}
|
||||
|
||||
pub const MOVED: [Moved; 3] = [
|
||||
pub const MOVED: [Moved; 4] = [
|
||||
Moved {
|
||||
id: "fps_overlay",
|
||||
name: "FPS counter",
|
||||
@@ -38,6 +38,10 @@ pub const MOVED: [Moved; 3] = [
|
||||
id: "zoom",
|
||||
name: "Zoom",
|
||||
},
|
||||
Moved {
|
||||
id: "minimap",
|
||||
name: "Minimap",
|
||||
},
|
||||
];
|
||||
|
||||
impl Moved {
|
||||
@@ -45,7 +49,8 @@ impl Moved {
|
||||
match self.id {
|
||||
"fps_overlay" => e.fps,
|
||||
"keystrokes" => e.keystrokes,
|
||||
_ => e.zoom,
|
||||
"zoom" => e.zoom,
|
||||
_ => e.minimap,
|
||||
}
|
||||
}
|
||||
/// The extra's settings as the mod keeps them (its storage keys).
|
||||
@@ -60,11 +65,21 @@ impl Moved {
|
||||
("corner", e.keystrokes_corner.name().into()),
|
||||
("cps", flag(e.keystrokes_cps)),
|
||||
],
|
||||
_ => vec![
|
||||
"zoom" => vec![
|
||||
("level", e.zoom_level.to_string()),
|
||||
("smooth", flag(e.zoom_smooth)),
|
||||
("sensitivity", flag(e.zoom_sensitivity)),
|
||||
],
|
||||
_ => vec![
|
||||
("corner", e.minimap_corner.name().into()),
|
||||
("size", e.minimap_size.to_string()),
|
||||
(
|
||||
"shape",
|
||||
if e.minimap_round { "round" } else { "square" }.into(),
|
||||
),
|
||||
("zoom", e.minimap_zoom.to_string()),
|
||||
("rotate", flag(e.minimap_rotate)),
|
||||
],
|
||||
}
|
||||
}
|
||||
/// The extra's key as the mod's key (`horizon-mods.txt`), when the
|
||||
@@ -208,7 +223,7 @@ mod tests {
|
||||
fn only_extras_that_were_on_are_installed_and_each_once() {
|
||||
let mut e = Extras::default();
|
||||
assert!(pending(&e).is_empty());
|
||||
assert_eq!(nothing_to_do(&e).len(), 3);
|
||||
assert_eq!(nothing_to_do(&e).len(), 4);
|
||||
e.fps = true;
|
||||
e.fps_corner = Corner::BottomRight;
|
||||
e.fps_lows = true;
|
||||
@@ -223,7 +238,7 @@ mod tests {
|
||||
);
|
||||
e.moved.push("fps_overlay".into());
|
||||
assert!(pending(&e).is_empty());
|
||||
assert_eq!(nothing_to_do(&e), [&MOVED[1], &MOVED[2]]);
|
||||
assert_eq!(nothing_to_do(&e), [&MOVED[1], &MOVED[2], &MOVED[3]]);
|
||||
// Zoom: its settings, and its key only when the player changed it.
|
||||
e.zoom = true;
|
||||
e.zoom_level = 8;
|
||||
@@ -240,6 +255,23 @@ mod tests {
|
||||
assert!(MOVED[2].keys(&e).is_empty());
|
||||
e.zoom_key = "key.mouse.4".into();
|
||||
assert_eq!(MOVED[2].keys(&e), [("zoom", "key.mouse.4".into())]);
|
||||
// The minimap: its five settings, in the extra's values.
|
||||
e.minimap = true;
|
||||
e.minimap_corner = Corner::BottomLeft;
|
||||
e.minimap_size = 128;
|
||||
e.minimap_round = true;
|
||||
e.minimap_zoom = 0.5;
|
||||
assert_eq!(pending(&e), [&MOVED[2], &MOVED[3]]);
|
||||
assert_eq!(
|
||||
MOVED[3].settings(&e),
|
||||
[
|
||||
("corner", "bottom_left".into()),
|
||||
("size", "128".into()),
|
||||
("shape", "round".into()),
|
||||
("zoom", "0.5".into()),
|
||||
("rotate", "false".into())
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
MOVED[0].notice(),
|
||||
"FPS counter moved to the mod browser: installed for you"
|
||||
|
||||
@@ -3377,7 +3377,7 @@ mod tests {
|
||||
s.extras
|
||||
);
|
||||
// In a window too short for the page, the wheel scrolls to its end.
|
||||
let short = (480.0, 300.0);
|
||||
let short = (480.0, 180.0);
|
||||
ui.scroll(&s, short, -1000.0);
|
||||
let (_, top, bottom, content) = ui.layout(&s, short.0, short.1);
|
||||
assert!(content > bottom - top);
|
||||
|
||||
@@ -639,8 +639,12 @@ impl Streaming {
|
||||
self.lit.remove(&(x, z));
|
||||
self.meshed.remove(&(x, z));
|
||||
self.lighting.remove(&(x, z));
|
||||
self.meshing.retain(|k, _| (k.0, k.2) != (x, z));
|
||||
self.waiting.retain(|k| (k.0, k.2) != (x, z));
|
||||
// By key, not by a pass over every pending section: a moved or
|
||||
// shrunk storage forgets thousands of columns in one frame.
|
||||
for sy in 0..SECTIONS as i32 {
|
||||
self.meshing.remove(&(x, sy, z));
|
||||
self.waiting.remove(&(x, sy, z));
|
||||
}
|
||||
world.dirty_sections.take_column(x, z);
|
||||
world.chunks.remove(&(x, z))
|
||||
}
|
||||
|
||||
@@ -227,8 +227,9 @@ fn sunrise_weight(d: vec3<f32>) -> f32 {
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4<f32> {
|
||||
let d = view_ray(in.ndc);
|
||||
// The sky's colour along the view ray `d` (a shader pack's sky stage gets it as its input:
|
||||
// gfx/native_sky.rs builds that stage from this section).
|
||||
fn sky_along_ray(d: vec3<f32>) -> vec3<f32> {
|
||||
var color = globals.fog_color.rgb;
|
||||
let dist = disc_distance(d, 16.0);
|
||||
if dist.x >= 0.0 {
|
||||
@@ -238,7 +239,10 @@ fn sunrise_weight(d: vec3<f32>) -> f32 {
|
||||
if w > 0.0 {
|
||||
color = mix(color, globals.sunrise.rgb, w * globals.sunrise.a);
|
||||
}
|
||||
return vec4(color, 1.0);
|
||||
return color;
|
||||
}
|
||||
@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4<f32> {
|
||||
return vec4(sky_along_ray(view_ray(in.ndc)), 1.0);
|
||||
}
|
||||
@fragment fn fs_dark_disc(in: SkyOut) -> @location(0) vec4<f32> {
|
||||
let d = view_ray(in.ndc);
|
||||
|
||||
Generated
+243
-8
@@ -17,12 +17,24 @@ dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayvec"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||
|
||||
[[package]]
|
||||
name = "atomic-waker"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "axum"
|
||||
version = "0.8.9"
|
||||
@@ -80,6 +92,27 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -95,6 +128,26 @@ version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
version = "1.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||
dependencies = [
|
||||
"bytemuck_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
@@ -117,6 +170,21 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
|
||||
|
||||
[[package]]
|
||||
name = "codespan-reporting"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
|
||||
dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core_detect"
|
||||
version = "1.0.0"
|
||||
@@ -147,6 +215,12 @@ version = "0.8.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
@@ -165,7 +239,7 @@ checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -187,7 +261,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -236,6 +310,12 @@ dependencies = [
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
@@ -302,11 +382,26 @@ dependencies = [
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "half"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"crunchy",
|
||||
"num-traits",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
@@ -340,6 +435,7 @@ dependencies = [
|
||||
name = "horizon-mods"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-shader-api",
|
||||
"log",
|
||||
"minisign-verify",
|
||||
"serde",
|
||||
@@ -349,6 +445,19 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-shader-api"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"naga",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"toml",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
@@ -554,6 +663,12 @@ version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.3"
|
||||
@@ -634,6 +749,54 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
|
||||
|
||||
[[package]]
|
||||
name = "naga"
|
||||
version = "30.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"bit-set",
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"cfg_aliases",
|
||||
"codespan-reporting",
|
||||
"half",
|
||||
"hashbrown",
|
||||
"indexmap",
|
||||
"libm",
|
||||
"log",
|
||||
"naga-types",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"rustc-hash",
|
||||
"spirv",
|
||||
"thiserror",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "naga-types"
|
||||
version = "30.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"
|
||||
dependencies = [
|
||||
"hashbrown",
|
||||
"indexmap",
|
||||
"rustc-hash",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@@ -699,6 +862,12 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
@@ -779,7 +948,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -894,6 +1063,15 @@ version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
|
||||
[[package]]
|
||||
name = "spirv"
|
||||
version = "0.4.0+sdk-1.4.341.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -906,6 +1084,17 @@ version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
@@ -931,7 +1120,27 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -968,7 +1177,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1049,6 +1258,12 @@ version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
@@ -1254,10 +1469,30 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.8"
|
||||
@@ -1275,7 +1510,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -1315,7 +1550,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -342,11 +342,12 @@ async fn what_the_form_refuses() {
|
||||
);
|
||||
let (status, json) = client.submit(&csrf, &f, &file).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{json}");
|
||||
// Shader packs aren't open.
|
||||
// A shader pack runs the game's own check: a mod's file isn't one.
|
||||
let mut f = form();
|
||||
f["kind"] = json!("shader");
|
||||
let (status, json) = client.submit(&csrf, &f, &file).await;
|
||||
refused(status, &json, "shader packs open");
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{json}");
|
||||
refused(status, &json, "horizon-shaders.toml: missing");
|
||||
// An update by someone who isn't an owner.
|
||||
let owned = "id = \"coords_hud\"\nkind = \"mod\"\nname = \"C\"\nsummary = \"s\"\nowners = [\"bob\"]\nlicense = \"MIT\"\nsource = \"https://x.test\"\n\n[[versions]]\nversion = \"0.0.1\"\npublished = \"2026-01-01\"\ngame = \"26.3\"\nfile = \"coords_hud-0.0.1.hmod\"\nsha256 = \"0000000000000000000000000000000000000000000000000000000000000000\"\n";
|
||||
mock.lock()
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "welcome"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "Example Horizon server mod: greets players, announces newcomers, /online and /mined"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
horizon-mod-sdk = { path = "../.." }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,8 @@
|
||||
id = "welcome"
|
||||
name = "Welcome"
|
||||
version = "0.1.0"
|
||||
description = "Greets each player who joins, announces a newcomer to everyone, /online lists who is on, /mined counts the blocks you broke."
|
||||
authors = ["Horizon"]
|
||||
api = "0.3"
|
||||
side = "server"
|
||||
capabilities = ["players", "storage"]
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Example Horizon server mod (`docs/mods.md`, "Server mods"): greets each
|
||||
//! player who joins, announces a newcomer to everyone (the players it has
|
||||
//! seen are kept in `storage`), `/online` lists who is on and where, and
|
||||
//! `/mined` counts the blocks the player broke since the server started.
|
||||
use horizon_mod_sdk::{
|
||||
server::{BlockPos, Player, Registration, ServerMod, players},
|
||||
storage,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
struct Welcome {
|
||||
/// Ids of every player seen, one per line in storage key `seen`.
|
||||
seen: Vec<String>,
|
||||
mined: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
impl ServerMod for Welcome {
|
||||
fn init() -> Result<(Self, Registration), String> {
|
||||
let seen = storage::get("seen")
|
||||
.map(|b| {
|
||||
String::from_utf8_lossy(&b)
|
||||
.lines()
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let hooks = Registration::new()
|
||||
.command("online")
|
||||
.command("mined")
|
||||
.on_joins()
|
||||
.on_blocks();
|
||||
Ok((
|
||||
Welcome {
|
||||
seen,
|
||||
mined: HashMap::new(),
|
||||
},
|
||||
hooks,
|
||||
))
|
||||
}
|
||||
|
||||
fn player_joined(&mut self, player: &Player) {
|
||||
let others = players::online().len() - 1;
|
||||
players::tell(
|
||||
&player.id,
|
||||
&format!("Welcome, {}! {others} other player(s) online.", player.name),
|
||||
);
|
||||
if !self.seen.contains(&player.id) {
|
||||
self.seen.push(player.id.clone());
|
||||
let _ = storage::set("seen", self.seen.join("\n").as_bytes());
|
||||
players::broadcast(&format!("{} is here for the first time", player.name));
|
||||
}
|
||||
}
|
||||
|
||||
fn command(
|
||||
&mut self,
|
||||
player: &Player,
|
||||
name: &str,
|
||||
_args: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
Ok(Some(match name {
|
||||
"online" => players::online()
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{} ({})",
|
||||
p.name,
|
||||
p.dimension.trim_start_matches("minecraft:")
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
_ => {
|
||||
let n = self.mined.get(&player.id).copied().unwrap_or(0);
|
||||
format!("You broke {n} block(s)")
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
fn block_broken(&mut self, player: &Player, _pos: BlockPos, _state: &str) {
|
||||
*self.mined.entry(player.id.clone()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
|
||||
horizon_mod_sdk::export_server_mod!(Welcome);
|
||||
@@ -21,7 +21,8 @@
|
||||
//! ```
|
||||
//!
|
||||
//! Every interface but `log` is a capability: list the ones the mod uses in
|
||||
//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`, `command`, `ui`).
|
||||
//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`, `command`, `ui`;
|
||||
//! a server mod `storage` and `players`). Server mods: [`server`].
|
||||
//!
|
||||
//! Widgets (capability `ui`): a mod shows a screen it owns with
|
||||
//! [`ui::open_screen`] and a page in Options > Mods with
|
||||
@@ -173,3 +174,152 @@ macro_rules! export_mod {
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/// Server mods (manifest `side = "server"`, `api = "0.3"`, experimental): a
|
||||
/// type implementing [`ServerMod`](server::ServerMod), exported with
|
||||
/// [`export_server_mod!`]. It runs where the world is simulated, and reads
|
||||
/// and messages the players with capability `players`.
|
||||
pub mod server {
|
||||
wit_bindgen::generate!({
|
||||
path: "wit",
|
||||
world: "horizon-server-mod",
|
||||
pub_export_macro: true,
|
||||
export_macro_name: "__export_horizon_server_mod",
|
||||
default_bindings_module: "horizon_mod_sdk::server",
|
||||
with: {
|
||||
"horizon:mods/log@0.1.0": crate::log,
|
||||
"horizon:mods/storage@0.1.0": crate::storage,
|
||||
},
|
||||
});
|
||||
|
||||
pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration};
|
||||
pub use horizon::mods::players::{self, GameMode, Player};
|
||||
|
||||
/// The server's calls into a mod. Only the hooks [`Registration`] asks
|
||||
/// for are called; the others may stay as their defaults.
|
||||
pub trait ServerMod: Sized + 'static {
|
||||
/// Once, after loading: the mod's state and the hooks it wants. An
|
||||
/// error keeps the mod off and is logged.
|
||||
fn init() -> Result<(Self, Registration), String>;
|
||||
/// Every server tick, when [`Registration::tick`] is set.
|
||||
fn tick(&mut self, _tick: u64) {}
|
||||
/// When [`Registration::joins`] is set.
|
||||
fn player_joined(&mut self, _player: &Player) {}
|
||||
fn player_left(&mut self, _player: &Player) {}
|
||||
/// A chat message a player sent, when [`Registration::chat`] is set.
|
||||
fn chat(&mut self, _player: &Player, _text: &str) {}
|
||||
/// `/name args` typed by `player`. `Ok(Some(text))` is their
|
||||
/// feedback, `Err(text)` their error in red.
|
||||
fn command(
|
||||
&mut self,
|
||||
_player: &Player,
|
||||
_name: &str,
|
||||
_args: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
Err("This command does nothing".into())
|
||||
}
|
||||
/// When [`Registration::blocks`] is set: `state` is what was there.
|
||||
fn block_broken(&mut self, _player: &Player, _pos: BlockPos, _state: &str) {}
|
||||
fn block_placed(&mut self, _player: &Player, _pos: BlockPos, _state: &str) {}
|
||||
}
|
||||
|
||||
impl Registration {
|
||||
/// No commands and no hooks.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
commands: Vec::new(),
|
||||
tick: false,
|
||||
joins: false,
|
||||
chat: false,
|
||||
blocks: false,
|
||||
}
|
||||
}
|
||||
/// Adds `/name`.
|
||||
pub fn command(mut self, name: &str) -> Self {
|
||||
self.commands.push(name.into());
|
||||
self
|
||||
}
|
||||
pub fn on_tick(mut self) -> Self {
|
||||
self.tick = true;
|
||||
self
|
||||
}
|
||||
pub fn on_joins(mut self) -> Self {
|
||||
self.joins = true;
|
||||
self
|
||||
}
|
||||
pub fn on_chat(mut self) -> Self {
|
||||
self.chat = true;
|
||||
self
|
||||
}
|
||||
pub fn on_blocks(mut self) -> Self {
|
||||
self.blocks = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
impl Default for Registration {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports a [`ServerMod`](server::ServerMod) as the component's
|
||||
/// `server-events` interface, as [`export_mod!`] does for a client mod.
|
||||
#[macro_export]
|
||||
macro_rules! export_server_mod {
|
||||
($t:ty) => {
|
||||
const _: () = {
|
||||
use ::std::cell::RefCell;
|
||||
use $crate::server::{BlockPos, Player, Registration, ServerMod};
|
||||
::std::thread_local! {
|
||||
static STATE: RefCell<Option<$t>> = const { RefCell::new(None) };
|
||||
}
|
||||
fn with(f: impl FnOnce(&mut $t)) {
|
||||
STATE.with(|s| {
|
||||
if let Some(m) = s.borrow_mut().as_mut() {
|
||||
f(m)
|
||||
}
|
||||
})
|
||||
}
|
||||
struct Export;
|
||||
impl $crate::server::__Guest for Export {
|
||||
fn init() -> Result<Registration, String> {
|
||||
let (m, registration) = <$t as ServerMod>::init()?;
|
||||
STATE.with(|s| *s.borrow_mut() = Some(m));
|
||||
Ok(registration)
|
||||
}
|
||||
fn tick(tick: u64) {
|
||||
with(|m| m.tick(tick))
|
||||
}
|
||||
fn player_joined(player: Player) {
|
||||
with(|m| m.player_joined(&player))
|
||||
}
|
||||
fn player_left(player: Player) {
|
||||
with(|m| m.player_left(&player))
|
||||
}
|
||||
fn chat(player: Player, text: String) {
|
||||
with(|m| m.chat(&player, &text))
|
||||
}
|
||||
fn command(
|
||||
player: Player,
|
||||
name: String,
|
||||
args: String,
|
||||
) -> Result<Option<String>, String> {
|
||||
let mut out = Err("The mod is not running".to_string());
|
||||
with(|m| out = m.command(&player, &name, &args));
|
||||
out
|
||||
}
|
||||
fn block_broken(player: Player, pos: BlockPos, state: String) {
|
||||
with(|m| m.block_broken(&player, pos, &state))
|
||||
}
|
||||
fn block_placed(player: Player, pos: BlockPos, state: String) {
|
||||
with(|m| m.block_placed(&player, pos, &state))
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
$crate::server::__export_horizon_server_mod!(Export);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let _ = <Export as $crate::server::__Guest>::init;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -412,6 +412,84 @@ interface events {
|
||||
chat: func(text: string);
|
||||
}
|
||||
|
||||
/// Capability `players`, server mods only (manifest `api = "0.3"`,
|
||||
/// experimental): the players on the server, and messages to them.
|
||||
interface players {
|
||||
enum game-mode {
|
||||
survival,
|
||||
creative,
|
||||
adventure,
|
||||
spectator,
|
||||
}
|
||||
record player {
|
||||
/// The player's UUID, `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`.
|
||||
id: string,
|
||||
name: string,
|
||||
/// Feet position, in blocks.
|
||||
x: f64,
|
||||
y: f64,
|
||||
z: f64,
|
||||
/// `minecraft:overworld`, `minecraft:the_nether`, ...
|
||||
dimension: string,
|
||||
game-mode: game-mode,
|
||||
/// Hit points as vanilla counts them: 20 is full health without effects.
|
||||
health: f32,
|
||||
}
|
||||
/// The players online, in the order they joined.
|
||||
online: func() -> list<player>;
|
||||
/// A system message to one player, after the mod's name; false when no
|
||||
/// player with that id is online. Up to 8 messages per call.
|
||||
tell: func(player: string, text: string) -> bool;
|
||||
/// A system message to every player and the server's log, after the
|
||||
/// mod's name. Counts toward the same 8 per call.
|
||||
broadcast: func(text: string);
|
||||
}
|
||||
|
||||
/// What the server calls in a server mod (manifest `api = "0.3"`,
|
||||
/// experimental). Only the hooks `init` asks for are ever called. The player
|
||||
/// in each event is as the server saw them when it happened.
|
||||
interface server-events {
|
||||
use players.{player};
|
||||
|
||||
record registration {
|
||||
/// Commands players may type, without the slash. A name vanilla
|
||||
/// already uses is refused (vanilla's command runs).
|
||||
commands: list<string>,
|
||||
/// Call `tick` every server tick (20 per second).
|
||||
tick: bool,
|
||||
/// Call `player-joined` and `player-left`.
|
||||
joins: bool,
|
||||
/// Call `chat` for each chat message a player sends.
|
||||
chat: bool,
|
||||
/// Call `block-broken` and `block-placed`.
|
||||
blocks: bool,
|
||||
}
|
||||
record block-pos {
|
||||
x: s32,
|
||||
y: s32,
|
||||
z: s32,
|
||||
}
|
||||
/// Once, after loading. An error keeps the mod off and is logged.
|
||||
init: func() -> result<registration, string>;
|
||||
/// Each server tick, with the server's tick counter.
|
||||
tick: func(tick: u64);
|
||||
/// A player joined the server; they are in `players.online` already.
|
||||
player-joined: func(player: player);
|
||||
/// A player left the server; they are no longer in `players.online`.
|
||||
player-left: func(player: player);
|
||||
/// A chat message a player sent, as plain text.
|
||||
chat: func(player: player, text: string);
|
||||
/// `/name args` typed by `player`: ok(some(text)) is their feedback,
|
||||
/// err(text) their error in red.
|
||||
command: func(player: player, name: string, args: string) -> result<option<string>, string>;
|
||||
/// A player broke the block at `pos` in their dimension: `state` is what
|
||||
/// was there, as `minecraft:oak_log[axis=y]`.
|
||||
block-broken: func(player: player, pos: block-pos, state: string);
|
||||
/// A player placed `state` at `pos` in their dimension.
|
||||
block-placed: func(player: player, pos: block-pos, state: string);
|
||||
}
|
||||
|
||||
/// A client mod: runs in the player's game.
|
||||
world horizon-mod {
|
||||
import log;
|
||||
import game;
|
||||
@@ -422,6 +500,16 @@ world horizon-mod {
|
||||
export events;
|
||||
}
|
||||
|
||||
/// A server mod (manifest `side = "server"`, `api = "0.3"`, experimental):
|
||||
/// runs where the world is simulated, on the dedicated server, a LAN host
|
||||
/// and single player's own server.
|
||||
world horizon-server-mod {
|
||||
import log;
|
||||
import storage;
|
||||
import players;
|
||||
export server-events;
|
||||
}
|
||||
|
||||
/// A mod with widgets (capability `ui`): the SDK builds every mod against
|
||||
/// this world. Mods built for `horizon-mod` alone (no `ui-events` export)
|
||||
/// still load and simply hear nothing of their widgets.
|
||||
|
||||
@@ -20,6 +20,8 @@ wit-parser = { version = "0.254", optional = true }
|
||||
# The registry index's checks (feature `index`): SHA-256, and minisign signatures (no dependencies of its own).
|
||||
sha2 = { version = "0.10", optional = true }
|
||||
minisign-verify = { version = "0.3", optional = true }
|
||||
# A shader pack's check (kind `shader`): the one the game runs before it loads a pack.
|
||||
horizon-shader-api = { path = "../horizon-shader-api", optional = true }
|
||||
|
||||
[features]
|
||||
# Loads and runs mods (the game's `mods` feature); without it only manifests,
|
||||
@@ -28,7 +30,7 @@ minisign-verify = { version = "0.3", optional = true }
|
||||
runtime = ["dep:wasmtime"]
|
||||
pack = ["dep:wit-component", "dep:wit-parser"]
|
||||
# The mod registry's index (docs/api/mod-index.md): the launcher, the registry server and its CI.
|
||||
index = ["dep:sha2", "dep:minisign-verify"]
|
||||
index = ["dep:sha2", "dep:minisign-verify", "dep:horizon-shader-api"]
|
||||
|
||||
# Runs real mods: `cargo test -p horizon-mods --features runtime,pack`.
|
||||
[[test]]
|
||||
|
||||
@@ -47,8 +47,8 @@ pub enum Kind {
|
||||
Modpack,
|
||||
/// A resource pack (`.zip` with `pack.mcmeta`) made or tested for Horizon.
|
||||
ResourcePack,
|
||||
/// A Horizon shader pack (the native WGSL format, not Iris or OptiFine
|
||||
/// packs). Listed by the schema; submissions open with its API.
|
||||
/// A Horizon shader pack (`.hshader`, the native WGSL format of
|
||||
/// docs/shaders.md; not the shaders/-folder packs, which stay on Modrinth).
|
||||
Shader,
|
||||
Other(String),
|
||||
}
|
||||
@@ -69,7 +69,8 @@ impl Kind {
|
||||
match self {
|
||||
Kind::Mod => Some("hmod"),
|
||||
Kind::Modpack => Some("hpack"),
|
||||
Kind::ResourcePack | Kind::Shader => Some("zip"),
|
||||
Kind::ResourcePack => Some("zip"),
|
||||
Kind::Shader => Some(horizon_shader_api::EXTENSION),
|
||||
Kind::Other(_) => None,
|
||||
}
|
||||
}
|
||||
@@ -448,7 +449,7 @@ pub fn check_file(
|
||||
(None, None) => Trust::Unsigned,
|
||||
_ => return Err("its signature and the project's key don't go together".into()),
|
||||
};
|
||||
if matches!(project.kind, Kind::Shader | Kind::Other(_)) {
|
||||
if matches!(project.kind, Kind::Other(_)) {
|
||||
return Err(format!(
|
||||
"this Horizon can't install a {} yet",
|
||||
project.kind.name()
|
||||
@@ -502,6 +503,13 @@ impl Facts {
|
||||
names(&self.capabilities)
|
||||
),
|
||||
Kind::Modpack => format!("its {} isn't what the index lists", modpack::MANIFEST),
|
||||
Kind::Shader => format!(
|
||||
"its {} ({} {}, shader API {}) isn't what the index lists",
|
||||
horizon_shader_api::MANIFEST,
|
||||
self.id.as_deref().unwrap_or("?"),
|
||||
self.version.as_deref().unwrap_or("?"),
|
||||
self.api
|
||||
),
|
||||
_ => format!("its pack format {} isn't what the index lists", self.api),
|
||||
})
|
||||
}
|
||||
@@ -509,8 +517,8 @@ impl Facts {
|
||||
|
||||
/// Reads and checks a file as its kind: a mod's manifest and content, a
|
||||
/// modpack's manifest and overrides, a resource pack's `pack.mcmeta` and
|
||||
/// paths. Shader packs and kinds this build doesn't know are refused: their
|
||||
/// checks come with their formats.
|
||||
/// paths, a shader pack's `horizon_shader_api::check` (the game's own). Kinds
|
||||
/// this build doesn't know are refused: their checks come with their formats.
|
||||
pub fn inspect(kind: &Kind, path: &Path) -> Result<Facts, String> {
|
||||
match kind {
|
||||
Kind::Mod => {
|
||||
@@ -540,9 +548,23 @@ pub fn inspect(kind: &Kind, path: &Path) -> Result<Facts, String> {
|
||||
api: check_resource_pack(path)?,
|
||||
..Facts::default()
|
||||
}),
|
||||
Kind::Shader => Err(
|
||||
"Horizon's own shader pack format isn't out yet: shader packs open when it is".into(),
|
||||
),
|
||||
Kind::Shader => {
|
||||
let pack = horizon_shader_api::Pack::read(path)?;
|
||||
if let Err(problems) = horizon_shader_api::check(&pack) {
|
||||
let lines: Vec<String> = problems.iter().map(ToString::to_string).collect();
|
||||
return Err(format!(
|
||||
"the shader pack fails its check:\n{}",
|
||||
lines.join("\n")
|
||||
));
|
||||
}
|
||||
let m = pack.manifest;
|
||||
Ok(Facts {
|
||||
id: Some(m.id),
|
||||
version: Some(m.version),
|
||||
api: m.api,
|
||||
..Facts::default()
|
||||
})
|
||||
}
|
||||
Kind::Other(name) => Err(format!("this Horizon can't read a {name} yet")),
|
||||
}
|
||||
}
|
||||
@@ -591,14 +613,11 @@ fn check_resource_pack(path: &Path) -> Result<String, String> {
|
||||
Ok(format)
|
||||
}
|
||||
|
||||
/// The kinds the registry takes submissions for. Shader packs wait for
|
||||
/// Horizon's own format; other kinds for theirs.
|
||||
/// The kinds the registry takes submissions for; other kinds wait for their
|
||||
/// formats.
|
||||
pub fn open(kind: &Kind) -> Result<(), String> {
|
||||
match kind {
|
||||
Kind::Mod | Kind::Modpack | Kind::ResourcePack => Ok(()),
|
||||
Kind::Shader => Err(
|
||||
"shader packs open when Horizon's own shader pack format is out (Iris and OptiFine packs stay on Modrinth)".into(),
|
||||
),
|
||||
Kind::Mod | Kind::Modpack | Kind::ResourcePack | Kind::Shader => Ok(()),
|
||||
Kind::Other(name) => Err(format!("the registry doesn't take {name} yet")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! A registry checkout holding the sample index's mod and modpack builds the
|
||||
//! sample index (`tests/index/index-v1.json`) exactly.
|
||||
//! A registry checkout holding the sample index's mod, modpack and shader pack
|
||||
//! builds the sample index (`tests/index/index-v1.json`) exactly.
|
||||
use super::*;
|
||||
|
||||
const HMOD: &str = "e1135345692f6dd8fd4c51920151944b82333e17049c9bb7d756f27b8deefc53";
|
||||
const HPACK: &str = "241ac840f9c5ea3f6252d849da10c90d36cb1da4d6cd8d1d268c2760a353cd65";
|
||||
const HSHADER: &str = "331cfe29a666a0de804e9a9ff3d19d246eebcfbfa70b4f49bba8482d30ad9f02";
|
||||
|
||||
fn fixtures() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/index")
|
||||
@@ -61,6 +62,23 @@ file = "cozy-1.0.0.hpack"
|
||||
sha256 = "241ac840f9c5ea3f6252d849da10c90d36cb1da4d6cd8d1d268c2760a353cd65"
|
||||
"#;
|
||||
|
||||
const GLOW: &str = r#"id = "glow"
|
||||
kind = "shader"
|
||||
name = "Soft Glow"
|
||||
summary = "A post-processing pass over the world."
|
||||
authors = ["Horizon"]
|
||||
owners = ["ludovic111"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/ludovic111/horizon-mods"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-10-26"
|
||||
game = "26.3"
|
||||
file = "glow-1.0.0.hshader"
|
||||
sha256 = "331cfe29a666a0de804e9a9ff3d19d246eebcfbfa70b4f49bba8482d30ad9f02"
|
||||
"#;
|
||||
|
||||
const REVOKED_TOML: &str = r#"[[revoked]]
|
||||
id = "bad_mod"
|
||||
sha256 = "1111111111111111111111111111111111111111111111111111111111111111"
|
||||
@@ -82,9 +100,14 @@ impl Scratch {
|
||||
let s = Scratch(dir);
|
||||
s.write("mods/coords_hud.toml", &hud_entry());
|
||||
s.write("mods/cozy.toml", COZY);
|
||||
s.write("mods/glow.toml", GLOW);
|
||||
s.write("revoked.toml", REVOKED_TOML);
|
||||
s.write("icons/coords_hud.png", "png");
|
||||
for (name, hash) in [("coords_hud-0.1.0.hmod", HMOD), ("cozy-1.0.0.hpack", HPACK)] {
|
||||
for (name, hash) in [
|
||||
("coords_hud-0.1.0.hmod", HMOD),
|
||||
("cozy-1.0.0.hpack", HPACK),
|
||||
("glow-1.0.0.hshader", HSHADER),
|
||||
] {
|
||||
std::fs::copy(fixtures().join(name), s.0.join("files").join(hash)).unwrap();
|
||||
}
|
||||
s
|
||||
@@ -117,7 +140,7 @@ fn builds_the_sample_index() {
|
||||
let s = Scratch::new("sample");
|
||||
let built = s.build().unwrap();
|
||||
let sample = sample();
|
||||
assert_eq!(built.projects, sample.projects[..2]);
|
||||
assert_eq!(built.projects, sample.projects[..3]);
|
||||
assert_eq!(built.revoked, sample.revoked);
|
||||
assert_eq!(built.generated, sample.generated);
|
||||
// What it writes reads back.
|
||||
@@ -154,7 +177,11 @@ fn lists_every_problem_of_a_registry() {
|
||||
"{errors:?}"
|
||||
);
|
||||
assert!(has("coords_hud 0.1.0: the project has a key"), "{errors:?}");
|
||||
assert!(has("glow: shader packs open when"), "{errors:?}");
|
||||
// A shader entry is taken now, and checked like the others.
|
||||
assert!(
|
||||
has("glow 1.0.0: the file isn't the one its sha256 names"),
|
||||
"{errors:?}"
|
||||
);
|
||||
assert!(
|
||||
has("other 0.1.0: the file's id is \"coords_hud\""),
|
||||
"{errors:?}"
|
||||
@@ -219,7 +246,7 @@ fn a_review_protects_published_files() {
|
||||
#[test]
|
||||
fn only_open_kinds_are_taken() {
|
||||
assert!(open(&Kind::Mod).is_ok() && open(&Kind::ResourcePack).is_ok());
|
||||
assert!(open(&Kind::Shader).unwrap_err().contains("Iris"));
|
||||
assert!(open(&Kind::Shader).is_ok());
|
||||
assert!(open(&Kind::Other("world".into())).is_err());
|
||||
let mut submit: Entry = toml::from_str(COZY).unwrap();
|
||||
submit.id = "submit".into();
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The sample index (`tests/index/index-v1.json`, the one docs/api/mod-index.md
|
||||
//! shows) and its files: `coords_hud-0.1.0.hmod`, signed with the throwaway
|
||||
//! key `test.pub` by minisign 0.12 (its secret key was deleted), and
|
||||
//! `cozy-1.0.0.hpack`, unsigned.
|
||||
//! key `test.pub` by minisign 0.12 (its secret key was deleted),
|
||||
//! `cozy-1.0.0.hpack`, unsigned, and `glow-1.0.0.hshader`, unsigned
|
||||
//! (`horizon-shader new --template post`, then `horizon-shader pack`).
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -25,8 +26,8 @@ fn reads_the_sample_and_keeps_unknown_kinds() {
|
||||
let index = sample();
|
||||
assert_eq!(index.schema, SCHEMA);
|
||||
let kinds: Vec<&str> = index.projects.iter().map(|p| p.kind.name()).collect();
|
||||
assert_eq!(kinds, ["mod", "modpack", "world"]);
|
||||
assert_eq!(index.projects[2].kind, Kind::Other("world".into()));
|
||||
assert_eq!(kinds, ["mod", "modpack", "shader", "world"]);
|
||||
assert_eq!(index.projects[3].kind, Kind::Other("world".into()));
|
||||
let hud = index.project("coords_hud").unwrap();
|
||||
assert_eq!(
|
||||
hud.versions[0].capabilities,
|
||||
@@ -44,6 +45,8 @@ fn files_pass_against_their_entries() {
|
||||
assert_eq!(check(&index, "coords_hud", &hmod), Ok(Trust::Verified));
|
||||
let hpack = fixtures().join("cozy-1.0.0.hpack");
|
||||
assert_eq!(check(&index, "cozy", &hpack), Ok(Trust::Unsigned));
|
||||
let hshader = fixtures().join("glow-1.0.0.hshader");
|
||||
assert_eq!(check(&index, "glow", &hshader), Ok(Trust::Unsigned));
|
||||
let world = index.project("skyblock_start").unwrap();
|
||||
let e = check_file(&index, world, &world.versions[0], &hpack).unwrap_err();
|
||||
assert!(e.contains("bytes"), "{e}");
|
||||
@@ -163,3 +166,55 @@ fn resource_packs_need_a_pack_mcmeta() {
|
||||
assert!(e.contains("plain path"), "{e}");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shader_packs_pass_the_game_s_own_check() {
|
||||
let manifest = "schema = 1\nid = \"glow\"\nname = \"Glow\"\nversion = \"1.0.0\"\napi = \"0.1\"\n\
|
||||
[[post]]\nfile = \"post.wgsl\"\n";
|
||||
let pack = |post: &str| {
|
||||
let files = [
|
||||
(horizon_shader_api::MANIFEST, manifest),
|
||||
("post.wgsl", post),
|
||||
]
|
||||
.map(|(n, t)| (n.to_owned(), t.as_bytes().to_vec()))
|
||||
.into();
|
||||
horizon_shader_api::Pack::from_files(files)
|
||||
.unwrap()
|
||||
.package()
|
||||
.unwrap()
|
||||
};
|
||||
let dir = std::env::temp_dir().join(format!("horizon-mods-shader-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let good = dir.join("glow-1.0.0.hshader");
|
||||
std::fs::write(
|
||||
&good,
|
||||
pack("fn post(input: PostInput) -> vec4<f32> { return input.color; }\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let bad = dir.join("bad.hshader");
|
||||
std::fs::write(
|
||||
&bad,
|
||||
pack("fn post(input: PostInput) -> vec4<f32> { return input.color }\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let facts = inspect(&Kind::Shader, &good);
|
||||
let refused = inspect(&Kind::Shader, &bad).unwrap_err();
|
||||
let not_a_pack = inspect(&Kind::Shader, &fixtures().join("cozy-1.0.0.hpack")).unwrap_err();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let facts = facts.unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
facts.id.as_deref(),
|
||||
facts.version.as_deref(),
|
||||
facts.api.as_str()
|
||||
),
|
||||
(Some("glow"), Some("1.0.0"), "0.1")
|
||||
);
|
||||
assert!(refused.contains("post.wgsl:1:"), "{refused}");
|
||||
assert!(
|
||||
not_a_pack.contains(horizon_shader_api::MANIFEST),
|
||||
"{not_a_pack}"
|
||||
);
|
||||
assert_eq!(Kind::Shader.extension(), Some("hshader"));
|
||||
assert!(open(&Kind::Shader).is_ok());
|
||||
}
|
||||
|
||||
@@ -16,7 +16,10 @@ pub const API: &str = "0.1";
|
||||
/// The manifest `api` lines this build loads. 0.2 is 0.1 plus content:
|
||||
/// `assets/` and `data/` in the `.hmod`, with blocks and items declared in
|
||||
/// `data/<id>/horizon/` (docs/modpacks.md). Code still links API 0.1.
|
||||
pub const APIS: [&str; 2] = [API, "0.2"];
|
||||
/// 0.3 is a server mod (experimental): the `horizon-server-mod` world.
|
||||
pub const APIS: [&str; 3] = [API, "0.2", SERVER_API];
|
||||
/// The line of server mods, experimental: `side = "server"`.
|
||||
pub const SERVER_API: &str = "0.3";
|
||||
/// Namespaces no mod may claim: vanilla's, the convention tags' (mods add
|
||||
/// to those, docs/mods.md) and the game's own.
|
||||
const RESERVED_NAMESPACES: [&str; 3] = ["minecraft", "c", "horizon"];
|
||||
@@ -63,7 +66,7 @@ pub enum Side {
|
||||
/// Runs in the player's game only (HUD, keys, chat commands).
|
||||
#[default]
|
||||
Client,
|
||||
/// Runs where the world is simulated (rules, blocks); not run yet.
|
||||
/// Runs where the world is simulated (rules, blocks): `api = "0.3"`.
|
||||
Server,
|
||||
/// Both, and the server tells clients which version it expects.
|
||||
Both,
|
||||
@@ -92,9 +95,11 @@ pub enum Capability {
|
||||
/// The use button on items the mod claims, and its own keys
|
||||
/// (interface `input`).
|
||||
Input,
|
||||
/// The players on the server and messages to them (server mods).
|
||||
Players,
|
||||
}
|
||||
impl Capability {
|
||||
pub const ALL: [Capability; 9] = [
|
||||
pub const ALL: [Capability; 10] = [
|
||||
Capability::GameRead,
|
||||
Capability::Chat,
|
||||
Capability::Hud,
|
||||
@@ -104,7 +109,12 @@ impl Capability {
|
||||
Capability::Ui,
|
||||
Capability::Render,
|
||||
Capability::Input,
|
||||
Capability::Players,
|
||||
];
|
||||
/// Whether a server mod may have it: the others act on a local player.
|
||||
pub fn on_server(self) -> bool {
|
||||
matches!(self, Capability::Storage | Capability::Players)
|
||||
}
|
||||
/// The WIT interface it grants, in `horizon:mods`.
|
||||
pub fn interface(self) -> &'static str {
|
||||
match self {
|
||||
@@ -117,6 +127,7 @@ impl Capability {
|
||||
Capability::Ui => "ui",
|
||||
Capability::Render => "render",
|
||||
Capability::Input => "input",
|
||||
Capability::Players => "players",
|
||||
}
|
||||
}
|
||||
/// May change in any release: a mod uses it only with
|
||||
@@ -141,6 +152,7 @@ impl Capability {
|
||||
Capability::Input => {
|
||||
"see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys"
|
||||
}
|
||||
Capability::Players => "see who is on the server and message them",
|
||||
}
|
||||
}
|
||||
/// The capability a component import needs, `Ok(None)` for one every
|
||||
@@ -175,6 +187,7 @@ impl fmt::Display for Capability {
|
||||
Capability::Ui => "ui",
|
||||
Capability::Render => "render",
|
||||
Capability::Input => "input",
|
||||
Capability::Players => "players",
|
||||
};
|
||||
f.write_str(name)
|
||||
}
|
||||
@@ -205,6 +218,20 @@ impl Manifest {
|
||||
"{MANIFEST}: capability registries needs api = \"0.2\""
|
||||
));
|
||||
}
|
||||
let server = m.side == Side::Server;
|
||||
if server != (m.api == SERVER_API) {
|
||||
return Err(format!(
|
||||
"{MANIFEST}: a server mod is side = \"server\" with api = \"{SERVER_API}\", and only it"
|
||||
));
|
||||
}
|
||||
if let Some(c) = m
|
||||
.capabilities
|
||||
.iter()
|
||||
.find(|c| c.on_server() != server && **c != Capability::Storage)
|
||||
{
|
||||
let side = if server { "client" } else { "server" };
|
||||
return Err(format!("{MANIFEST}: capability {c} is for {side} mods"));
|
||||
}
|
||||
if let Some(c) = m
|
||||
.capabilities
|
||||
.iter()
|
||||
@@ -435,12 +462,32 @@ capabilities = ["game-read", "hud"]
|
||||
fn refuses_bad_ids_and_apis() {
|
||||
let bad_id = EXAMPLE.replace("coords_hud", "Coords HUD");
|
||||
assert!(Manifest::parse(&bad_id).unwrap_err().contains("is not"));
|
||||
let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.3\"");
|
||||
assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.3"));
|
||||
let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.4\"");
|
||||
assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.4"));
|
||||
let unknown = format!("{EXAMPLE}network = true\n");
|
||||
assert!(Manifest::parse(&unknown).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_mods_are_api_0_3_with_server_capabilities() {
|
||||
let server = |api: &str, side: &str, caps: &str| {
|
||||
Manifest::parse(&format!(
|
||||
"id = \"w\"\nname = \"W\"\nversion = \"1\"\napi = \"{api}\"\nside = \"{side}\"\ncapabilities = [{caps}]\n"
|
||||
))
|
||||
};
|
||||
let m = server("0.3", "server", "\"players\", \"storage\"").unwrap();
|
||||
let imports = ["horizon:mods/players@0.1.0", "horizon:mods/storage@0.1.0"];
|
||||
assert_eq!(m.check_imports(imports), Ok(()));
|
||||
for (api, side) in [("0.3", "client"), ("0.3", "both"), ("0.1", "server")] {
|
||||
let e = server(api, side, "").unwrap_err();
|
||||
assert!(e.contains("a server mod is side"), "{e}");
|
||||
}
|
||||
let e = server("0.3", "server", "\"hud\"").unwrap_err();
|
||||
assert!(e.contains("capability hud is for client mods"), "{e}");
|
||||
let e = server("0.1", "client", "\"players\"").unwrap_err();
|
||||
assert!(e.contains("capability players is for server mods"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checks_extra_namespaces() {
|
||||
let content = "id = \"t_and_t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.2\"\ncapabilities = [\"registries\"]\n";
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
//! Loading and calling mods with wasmtime's component model.
|
||||
use crate::manifest::{Manifest, Package, Side};
|
||||
use server_bindings::{
|
||||
HorizonServerMod, exports::horizon::mods::server_events::Registration as ServerRegistration,
|
||||
horizon::mods::players,
|
||||
};
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
@@ -16,6 +20,17 @@ mod bindings {
|
||||
world: "horizon-mod",
|
||||
});
|
||||
}
|
||||
/// The server mods' world: `log` and `storage` are the client world's.
|
||||
mod server_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
path: "../horizon-mod-sdk/wit",
|
||||
world: "horizon-server-mod",
|
||||
with: {
|
||||
"horizon:mods/log": super::bindings::horizon::mods::log,
|
||||
"horizon:mods/storage": super::bindings::horizon::mods::storage,
|
||||
},
|
||||
});
|
||||
}
|
||||
/// Capability `ui`'s world beyond `horizon-mod` (docs/mods.md): a second
|
||||
/// world, so mods built before it (no `ui-events` export) still instantiate
|
||||
/// as `horizon-mod` and simply hear nothing of their widgets.
|
||||
@@ -34,6 +49,12 @@ use bindings::{
|
||||
exports::horizon::mods::events::Registration,
|
||||
horizon::mods::{chat, command, game, hud, log as mod_log, storage},
|
||||
};
|
||||
pub use server_bindings::{
|
||||
exports::horizon::mods::server_events::BlockPos,
|
||||
horizon::mods::players::{GameMode, Player as ServerPlayer},
|
||||
};
|
||||
type ClientEvents = bindings::exports::horizon::mods::events::Guest;
|
||||
type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest;
|
||||
/// The widget model a `ui` screen or settings page shows (WIT `interface
|
||||
/// ui`), for the game to draw with its menus' own widgets.
|
||||
pub use ui_bindings::horizon::mods::ui::{
|
||||
@@ -101,6 +122,26 @@ pub struct Snapshot {
|
||||
/// The HUD font's advance per character from U+0000
|
||||
/// (`render.text-width`); empty: 6 each.
|
||||
pub font_widths: Arc<[f32]>,
|
||||
/// The players on the server, for server mods.
|
||||
pub players: Vec<ServerPlayer>,
|
||||
}
|
||||
|
||||
/// Which mods a game starts: the window's game the client mods, the game
|
||||
/// simulating the world the server mods, single player in the frame both.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Runs {
|
||||
Client,
|
||||
Server,
|
||||
Both,
|
||||
}
|
||||
impl Runs {
|
||||
fn starts(self, side: Side) -> bool {
|
||||
match self {
|
||||
Runs::Both => true,
|
||||
Runs::Client => side != Side::Server,
|
||||
Runs::Server => side == Side::Server,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What mods asked the game to show since the last [`Mods::drain`].
|
||||
@@ -115,6 +156,20 @@ pub enum Output {
|
||||
Command { line: String },
|
||||
/// The mod was turned off: it trapped, overran or failed to start.
|
||||
Stopped { name: String, reason: String },
|
||||
/// `players.tell`: a line after the mod's name, to the player with this id.
|
||||
Tell {
|
||||
name: String,
|
||||
player: String,
|
||||
text: String,
|
||||
},
|
||||
/// `players.broadcast`: a line after the mod's name, to every player.
|
||||
Broadcast { name: String, text: String },
|
||||
/// A server mod command's feedback, to the player who typed it.
|
||||
Reply {
|
||||
player: String,
|
||||
text: String,
|
||||
error: bool,
|
||||
},
|
||||
/// `ui.open-screen`: the mod's entry in `entries()`; what it shows is
|
||||
/// [`Mods::screen`].
|
||||
OpenScreen { owner: usize },
|
||||
@@ -136,6 +191,9 @@ pub enum Status {
|
||||
/// Installed and turned off by the player.
|
||||
Off,
|
||||
Running,
|
||||
/// Turned on, and run by another game: a server mod in the window while
|
||||
/// the world runs on its server thread.
|
||||
Elsewhere,
|
||||
/// Could not load or start, or stopped while running.
|
||||
Failed(String),
|
||||
}
|
||||
@@ -165,10 +223,36 @@ impl Entry {
|
||||
|
||||
struct Running {
|
||||
store: Store<State>,
|
||||
exports: HorizonMod,
|
||||
/// The mod's `ui-events` export; none for a mod built before `ui`.
|
||||
/// The mod's `ui-events` export; none for a mod built before `ui`, or a
|
||||
/// server mod.
|
||||
ui: Option<UiHost>,
|
||||
hooks: Registration,
|
||||
hooks: Hooks,
|
||||
}
|
||||
|
||||
/// A running mod's exports and the hooks its `init` asked for.
|
||||
enum Hooks {
|
||||
Client(HorizonMod, Registration),
|
||||
Server(HorizonServerMod, ServerRegistration),
|
||||
}
|
||||
impl Hooks {
|
||||
fn client(&self) -> Option<&Registration> {
|
||||
match self {
|
||||
Hooks::Client(_, r) => Some(r),
|
||||
Hooks::Server(..) => None,
|
||||
}
|
||||
}
|
||||
fn server(&self) -> Option<&ServerRegistration> {
|
||||
match self {
|
||||
Hooks::Server(_, r) => Some(r),
|
||||
Hooks::Client(..) => None,
|
||||
}
|
||||
}
|
||||
fn commands(&self) -> &[String] {
|
||||
match self {
|
||||
Hooks::Client(_, r) => &r.commands,
|
||||
Hooks::Server(_, r) => &r.commands,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What capability `ui` pushed since the hooks last ran.
|
||||
@@ -221,13 +305,23 @@ pub struct Mods {
|
||||
}
|
||||
|
||||
impl Mods {
|
||||
/// Reads every mod at `paths` and starts those `enabled` says are on.
|
||||
/// A command that `reserved` (vanilla's commands) or an earlier mod
|
||||
/// already uses is refused.
|
||||
/// Reads every mod at `paths` and starts those `enabled` says are on,
|
||||
/// client and server mods alike. A command that `reserved` (vanilla's
|
||||
/// commands) or an earlier mod already uses is refused.
|
||||
pub fn load(
|
||||
paths: &[PathBuf],
|
||||
enabled: impl Fn(&str) -> bool,
|
||||
reserved: impl Fn(&str) -> bool,
|
||||
) -> Mods {
|
||||
Mods::load_for(Runs::Both, paths, enabled, reserved)
|
||||
}
|
||||
/// [`Mods::load`], starting only the mods `runs` says this game runs; the
|
||||
/// others that are on are [`Status::Elsewhere`].
|
||||
pub fn load_for(
|
||||
runs: Runs,
|
||||
paths: &[PathBuf],
|
||||
enabled: impl Fn(&str) -> bool,
|
||||
reserved: impl Fn(&str) -> bool,
|
||||
) -> Mods {
|
||||
let mut mods = Mods::default();
|
||||
for path in paths {
|
||||
@@ -245,7 +339,9 @@ impl Mods {
|
||||
Ok(package) => {
|
||||
let on = enabled(&package.manifest.id);
|
||||
entry.manifest = Some(package.manifest.clone());
|
||||
if on {
|
||||
if on && !runs.starts(package.manifest.side) {
|
||||
entry.status = Status::Elsewhere;
|
||||
} else if on {
|
||||
// Content is read before the world loads; a mod whose
|
||||
// content is refused stays off, with the reason.
|
||||
let content = crate::Content::read(path, &package.manifest);
|
||||
@@ -276,6 +372,8 @@ impl Mods {
|
||||
let mut linker = Linker::new(&engine);
|
||||
HorizonMod::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||||
.map_err(|e| e.to_string())?;
|
||||
players::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||||
.map_err(|e| e.to_string())?;
|
||||
UiHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||||
.map_err(|e| e.to_string())?;
|
||||
RenderHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||||
@@ -299,9 +397,6 @@ impl Mods {
|
||||
let Some(wasm) = &package.wasm else {
|
||||
return Ok(None);
|
||||
};
|
||||
if m.side == Side::Server {
|
||||
return Err("server mods do not run yet".into());
|
||||
}
|
||||
// Two running mods with the same id would share one `data_dir`
|
||||
// (capability `storage`): the first loaded keeps the id.
|
||||
if self
|
||||
@@ -311,11 +406,13 @@ impl Mods {
|
||||
{
|
||||
return Err(format!("another running mod already uses id {}", m.id));
|
||||
}
|
||||
let server = m.side == Side::Server;
|
||||
let taken: Vec<String> = self
|
||||
.entries
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref())
|
||||
.flat_map(|r| r.hooks.commands.iter().cloned())
|
||||
.filter(|r| r.hooks.server().is_some() == server)
|
||||
.flat_map(|r| r.hooks.commands().iter().cloned())
|
||||
.collect();
|
||||
let snapshot = self.snapshot.clone();
|
||||
let (engine, linker) = self.engine()?;
|
||||
@@ -357,15 +454,29 @@ impl Mods {
|
||||
let instance = linker
|
||||
.instantiate(&mut store, &component)
|
||||
.map_err(|e| reason(&e))?;
|
||||
let exports = HorizonMod::new(&mut store, &instance).map_err(|e| reason(&e))?;
|
||||
// `ui-events` is a mod built since `ui`'s; older mods have no export
|
||||
// and stay callable through `events` alone.
|
||||
let ui = UiHost::new(&mut store, &instance).ok();
|
||||
let mut hooks = exports
|
||||
.horizon_mods_events()
|
||||
.call_init(&mut store)
|
||||
.map_err(|e| reason(&e))??;
|
||||
hooks.commands.retain(|c| {
|
||||
let (mut hooks, ui) = if server {
|
||||
let exports = HorizonServerMod::new(&mut store, &instance).map_err(|e| reason(&e))?;
|
||||
let r = exports
|
||||
.horizon_mods_server_events()
|
||||
.call_init(&mut store)
|
||||
.map_err(|e| reason(&e))??;
|
||||
(Hooks::Server(exports, r), None)
|
||||
} else {
|
||||
let exports = HorizonMod::new(&mut store, &instance).map_err(|e| reason(&e))?;
|
||||
// `ui-events` is a mod built since `ui`'s; older mods have no export
|
||||
// and stay callable through `events` alone.
|
||||
let ui = UiHost::new(&mut store, &instance).ok();
|
||||
let r = exports
|
||||
.horizon_mods_events()
|
||||
.call_init(&mut store)
|
||||
.map_err(|e| reason(&e))??;
|
||||
(Hooks::Client(exports, r), ui)
|
||||
};
|
||||
let commands = match &mut hooks {
|
||||
Hooks::Client(_, r) => &mut r.commands,
|
||||
Hooks::Server(_, r) => &mut r.commands,
|
||||
};
|
||||
commands.retain(|c| {
|
||||
let free = !reserved(c) && !taken.contains(c);
|
||||
if !free {
|
||||
log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id);
|
||||
@@ -373,18 +484,19 @@ impl Mods {
|
||||
free
|
||||
});
|
||||
self.out.append(&mut store.data_mut().out);
|
||||
Ok(Some(Running {
|
||||
store,
|
||||
exports,
|
||||
ui,
|
||||
hooks,
|
||||
}))
|
||||
Ok(Some(Running { store, ui, hooks }))
|
||||
}
|
||||
|
||||
/// True when at least one mod runs: the game skips its mod work otherwise.
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.entries.iter().any(|e| e.run.is_some())
|
||||
}
|
||||
/// True when a server mod runs: the server skips its mod work otherwise.
|
||||
pub fn runs_server(&self) -> bool {
|
||||
self.entries
|
||||
.iter()
|
||||
.any(|e| e.run.as_ref().is_some_and(|r| r.hooks.server().is_some()))
|
||||
}
|
||||
pub fn entries(&self) -> &[Entry] {
|
||||
&self.entries
|
||||
}
|
||||
@@ -397,7 +509,7 @@ impl Mods {
|
||||
fn each(
|
||||
&mut self,
|
||||
fuel: u64,
|
||||
wants: impl Fn(&Registration) -> bool,
|
||||
wants: impl Fn(&Hooks) -> bool,
|
||||
mut f: impl FnMut(&mut Running) -> wasmtime::Result<()>,
|
||||
) {
|
||||
for i in 0..self.entries.len() {
|
||||
@@ -410,6 +522,38 @@ impl Mods {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// [`Mods::each`] over the client mods.
|
||||
fn each_client(
|
||||
&mut self,
|
||||
fuel: u64,
|
||||
wants: impl Fn(&Registration) -> bool,
|
||||
mut f: impl FnMut(&ClientEvents, &mut Store<State>) -> wasmtime::Result<()>,
|
||||
) {
|
||||
self.each(
|
||||
fuel,
|
||||
|h| h.client().is_some_and(&wants),
|
||||
|run| match &run.hooks {
|
||||
Hooks::Client(m, _) => f(m.horizon_mods_events(), &mut run.store),
|
||||
Hooks::Server(..) => Ok(()),
|
||||
},
|
||||
);
|
||||
}
|
||||
/// [`Mods::each`] over the server mods.
|
||||
fn each_server(
|
||||
&mut self,
|
||||
fuel: u64,
|
||||
wants: impl Fn(&ServerRegistration) -> bool,
|
||||
mut f: impl FnMut(&ServerEvents, &mut Store<State>) -> wasmtime::Result<()>,
|
||||
) {
|
||||
self.each(
|
||||
fuel,
|
||||
|h| h.server().is_some_and(&wants),
|
||||
|run| match &run.hooks {
|
||||
Hooks::Server(m, _) => f(m.horizon_mods_server_events(), &mut run.store),
|
||||
Hooks::Client(..) => Ok(()),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// One call into mod `i`; a trap or an overrun turns the mod off.
|
||||
fn call<R>(
|
||||
@@ -457,62 +601,39 @@ impl Mods {
|
||||
|
||||
/// A game tick.
|
||||
pub fn tick(&mut self, tick: u64) {
|
||||
self.each(
|
||||
FUEL_TICK,
|
||||
|h| h.tick,
|
||||
|run| {
|
||||
run.exports
|
||||
.horizon_mods_events()
|
||||
.call_tick(&mut run.store, tick)
|
||||
},
|
||||
);
|
||||
self.each_client(FUEL_TICK, |h| h.tick, |m, s| m.call_tick(s, tick));
|
||||
}
|
||||
/// A rendered frame, `seconds` after the last.
|
||||
pub fn frame(&mut self, seconds: f32) {
|
||||
self.each(
|
||||
FUEL_FRAME,
|
||||
|h| h.frame,
|
||||
|run| {
|
||||
run.exports
|
||||
.horizon_mods_events()
|
||||
.call_frame(&mut run.store, seconds)
|
||||
},
|
||||
);
|
||||
self.each_client(FUEL_FRAME, |h| h.frame, |m, s| m.call_frame(s, seconds));
|
||||
}
|
||||
/// A chat line the player received, as plain text.
|
||||
pub fn chat(&mut self, text: &str) {
|
||||
self.each(
|
||||
FUEL_EVENT,
|
||||
|h| h.chat,
|
||||
|run| {
|
||||
run.exports
|
||||
.horizon_mods_events()
|
||||
.call_chat(&mut run.store, text)
|
||||
},
|
||||
);
|
||||
self.each_client(FUEL_EVENT, |h| h.chat, |m, s| m.call_chat(s, text));
|
||||
}
|
||||
/// Whether a running mod owns `/name`.
|
||||
/// Whether a running client mod owns `/name`.
|
||||
pub fn has_command(&self, name: &str) -> bool {
|
||||
self.command_owner(name).is_some()
|
||||
self.command_owner(false, name).is_some()
|
||||
}
|
||||
fn command_owner(&self, name: &str) -> Option<usize> {
|
||||
fn command_owner(&self, server: bool, name: &str) -> Option<usize> {
|
||||
self.entries.iter().position(|e| {
|
||||
e.run
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.hooks.commands.iter().any(|c| c == name))
|
||||
e.run.as_ref().is_some_and(|r| {
|
||||
r.hooks.server().is_some() == server && r.hooks.commands().iter().any(|c| c == name)
|
||||
})
|
||||
})
|
||||
}
|
||||
/// Runs `line` (without its slash) if a mod owns its command; false
|
||||
/// when none does.
|
||||
/// Runs `line` (without its slash) if a client mod owns its command;
|
||||
/// false when none does.
|
||||
pub fn command(&mut self, line: &str) -> bool {
|
||||
let (name, args) = line.split_once(' ').unwrap_or((line, ""));
|
||||
let Some(i) = self.command_owner(name) else {
|
||||
let Some(i) = self.command_owner(false, name) else {
|
||||
return false;
|
||||
};
|
||||
let result = self.call(i, FUEL_EVENT, |run| {
|
||||
run.exports
|
||||
let result = self.call(i, FUEL_EVENT, |run| match &run.hooks {
|
||||
Hooks::Client(m, _) => m
|
||||
.horizon_mods_events()
|
||||
.call_command(&mut run.store, name, args)
|
||||
.call_command(&mut run.store, name, args),
|
||||
Hooks::Server(..) => Ok(Ok(None)),
|
||||
});
|
||||
match result {
|
||||
Some(Ok(Some(text))) => self.out.push(Output::Feedback { text, error: false }),
|
||||
@@ -521,14 +642,89 @@ impl Mods {
|
||||
}
|
||||
true
|
||||
}
|
||||
/// The commands running mods own, for suggestions.
|
||||
/// The commands running client mods own, for suggestions.
|
||||
pub fn commands(&self) -> impl Iterator<Item = &str> {
|
||||
self.owned_commands(false)
|
||||
}
|
||||
fn owned_commands(&self, server: bool) -> impl Iterator<Item = &str> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref())
|
||||
.flat_map(|r| r.hooks.commands.iter().map(String::as_str))
|
||||
.filter(move |r| r.hooks.server().is_some() == server)
|
||||
.flat_map(|r| r.hooks.commands().iter().map(String::as_str))
|
||||
}
|
||||
|
||||
/// A server tick.
|
||||
pub fn server_tick(&mut self, tick: u64) {
|
||||
self.each_server(FUEL_TICK, |h| h.tick, |m, s| m.call_tick(s, tick));
|
||||
}
|
||||
/// `player` joined the server (they are in the snapshot's players).
|
||||
pub fn player_joined(&mut self, player: &ServerPlayer) {
|
||||
self.each_server(
|
||||
FUEL_EVENT,
|
||||
|h| h.joins,
|
||||
|m, s| m.call_player_joined(s, player),
|
||||
);
|
||||
}
|
||||
/// `player` left the server (they are no longer in the snapshot's players).
|
||||
pub fn player_left(&mut self, player: &ServerPlayer) {
|
||||
self.each_server(
|
||||
FUEL_EVENT,
|
||||
|h| h.joins,
|
||||
|m, s| m.call_player_left(s, player),
|
||||
);
|
||||
}
|
||||
/// A chat message `player` sent, as plain text.
|
||||
pub fn player_chat(&mut self, player: &ServerPlayer, text: &str) {
|
||||
self.each_server(FUEL_EVENT, |h| h.chat, |m, s| m.call_chat(s, player, text));
|
||||
}
|
||||
/// `player` broke `state` at `pos`.
|
||||
pub fn block_broken(&mut self, player: &ServerPlayer, pos: BlockPos, state: &str) {
|
||||
self.each_server(
|
||||
FUEL_EVENT,
|
||||
|h| h.blocks,
|
||||
|m, s| m.call_block_broken(s, player, pos, state),
|
||||
);
|
||||
}
|
||||
/// `player` placed `state` at `pos`.
|
||||
pub fn block_placed(&mut self, player: &ServerPlayer, pos: BlockPos, state: &str) {
|
||||
self.each_server(
|
||||
FUEL_EVENT,
|
||||
|h| h.blocks,
|
||||
|m, s| m.call_block_placed(s, player, pos, state),
|
||||
);
|
||||
}
|
||||
/// The commands running server mods own, for the server's command tree.
|
||||
pub fn server_commands(&self) -> impl Iterator<Item = &str> {
|
||||
self.owned_commands(true)
|
||||
}
|
||||
/// Runs `line` (without its slash), typed by `player`, if a server mod
|
||||
/// owns its command; its feedback is an [`Output::Reply`]. False when
|
||||
/// none does.
|
||||
pub fn server_command(&mut self, player: &ServerPlayer, line: &str) -> bool {
|
||||
let (name, args) = line.split_once(' ').unwrap_or((line, ""));
|
||||
let Some(i) = self.command_owner(true, name) else {
|
||||
return false;
|
||||
};
|
||||
let result = self.call(i, FUEL_EVENT, |run| match &run.hooks {
|
||||
Hooks::Server(m, _) => {
|
||||
m.horizon_mods_server_events()
|
||||
.call_command(&mut run.store, player, name, args)
|
||||
}
|
||||
Hooks::Client(..) => Ok(Ok(None)),
|
||||
});
|
||||
let reply = |text, error| Output::Reply {
|
||||
player: player.id.clone(),
|
||||
text,
|
||||
error,
|
||||
};
|
||||
match result {
|
||||
Some(Ok(Some(text))) => self.out.push(reply(text, false)),
|
||||
Some(Err(text)) => self.out.push(reply(text, true)),
|
||||
Some(Ok(None)) | None => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// The running mods' HUD panels.
|
||||
pub fn panels(&self) -> impl Iterator<Item = &Panel> {
|
||||
self.entries
|
||||
@@ -544,9 +740,11 @@ impl Mods {
|
||||
/// Some running mod has a `frame` hook: the game refreshes the snapshot
|
||||
/// every frame for it.
|
||||
pub fn wants_frames(&self) -> bool {
|
||||
self.entries
|
||||
.iter()
|
||||
.any(|e| e.run.as_ref().is_some_and(|r| r.hooks.frame))
|
||||
self.entries.iter().any(|e| {
|
||||
e.run
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.hooks.client().is_some_and(|h| h.frame))
|
||||
})
|
||||
}
|
||||
/// Some running mod claimed items (capability `input`).
|
||||
pub fn claims_any(&self) -> bool {
|
||||
@@ -781,7 +979,7 @@ impl Mods {
|
||||
for i in 0..self.entries.len() {
|
||||
let entry = &self.entries[i];
|
||||
let now = modified(&entry.path);
|
||||
let was_on = entry.status != Status::Off;
|
||||
let was_on = !matches!(entry.status, Status::Off | Status::Elsewhere);
|
||||
if now == entry.modified || !was_on {
|
||||
continue;
|
||||
}
|
||||
@@ -890,20 +1088,51 @@ impl game::Host for State {
|
||||
self.snapshot.clock
|
||||
}
|
||||
}
|
||||
impl chat::Host for State {
|
||||
fn show(&mut self, text: String) {
|
||||
impl State {
|
||||
/// Queues a chat line unless the call already sent [`CHAT_PER_CALL`].
|
||||
fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool {
|
||||
let shown = self
|
||||
.out
|
||||
.iter()
|
||||
.filter(|o| matches!(o, Output::Chat { .. }))
|
||||
.filter(|o| {
|
||||
matches!(
|
||||
o,
|
||||
Output::Chat { .. } | Output::Tell { .. } | Output::Broadcast { .. }
|
||||
)
|
||||
})
|
||||
.count();
|
||||
if shown < CHAT_PER_CALL {
|
||||
let name = self.name.clone();
|
||||
self.out.push(Output::Chat {
|
||||
name,
|
||||
text: clip(text),
|
||||
});
|
||||
self.out.push(line(name));
|
||||
}
|
||||
shown < CHAT_PER_CALL
|
||||
}
|
||||
}
|
||||
impl chat::Host for State {
|
||||
fn show(&mut self, text: String) {
|
||||
self.say(|name| Output::Chat {
|
||||
name,
|
||||
text: clip(text),
|
||||
});
|
||||
}
|
||||
}
|
||||
impl players::Host for State {
|
||||
fn online(&mut self) -> Vec<ServerPlayer> {
|
||||
self.snapshot.players.clone()
|
||||
}
|
||||
fn tell(&mut self, player: String, text: String) -> bool {
|
||||
self.snapshot.players.iter().any(|p| p.id == player)
|
||||
&& self.say(|name| Output::Tell {
|
||||
name,
|
||||
player,
|
||||
text: clip(text),
|
||||
})
|
||||
}
|
||||
fn broadcast(&mut self, text: String) {
|
||||
self.say(|name| Output::Broadcast {
|
||||
name,
|
||||
text: clip(text),
|
||||
});
|
||||
}
|
||||
}
|
||||
/// A key a mod registered (capability `input`).
|
||||
|
||||
Binary file not shown.
@@ -75,6 +75,34 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "glow",
|
||||
"kind": "shader",
|
||||
"name": "Soft Glow",
|
||||
"summary": "A post-processing pass over the world.",
|
||||
"authors": [
|
||||
"Horizon"
|
||||
],
|
||||
"owners": [
|
||||
"ludovic111"
|
||||
],
|
||||
"license": "MIT",
|
||||
"source": "https://github.com/ludovic111/horizon-mods",
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"published": "2026-10-26",
|
||||
"api": "0.1",
|
||||
"game": "26.3",
|
||||
"file": {
|
||||
"name": "glow-1.0.0.hshader",
|
||||
"url": "https://github.com/ludovic111/horizon-mods/releases/download/glow-1.0.0/glow-1.0.0.hshader",
|
||||
"size": 689,
|
||||
"sha256": "331cfe29a666a0de804e9a9ff3d19d246eebcfbfa70b4f49bba8482d30ad9f02"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "skyblock_start",
|
||||
"kind": "world",
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! examples and a guest
|
||||
//! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`.
|
||||
use horizon_mods::{
|
||||
Clock, Corner, HeldItem, Mods, Output, Package, Player, Shape, Snapshot, Status,
|
||||
BlockPos, Clock, Corner, GameMode, HeldItem, Mods, Output, Package, Player, Runs, ServerPlayer,
|
||||
Shape, Snapshot, Status,
|
||||
manifest::componentize,
|
||||
testing::{Script, TestGame},
|
||||
};
|
||||
@@ -44,6 +45,8 @@ fn mods_dir() -> &'static Path {
|
||||
"-p",
|
||||
"predator-missile",
|
||||
"-p",
|
||||
"welcome",
|
||||
"-p",
|
||||
"horizon-mods-test-guest",
|
||||
"-p",
|
||||
"horizon-mods-test-ui-guest",
|
||||
@@ -66,6 +69,7 @@ fn mods_dir() -> &'static Path {
|
||||
let mods = [
|
||||
("coords_hud", example("coords-hud")),
|
||||
("predator_missile", example("predator-missile")),
|
||||
("welcome", example("welcome")),
|
||||
("horizon_mods_test_guest", GUEST_MANIFEST.to_string()),
|
||||
("horizon_mods_test_ui_guest", UI_MANIFEST.to_string()),
|
||||
];
|
||||
@@ -807,3 +811,74 @@ fn a_test_script_reloads_and_expects_a_stop() {
|
||||
"the scratch copy and its storage are removed"
|
||||
);
|
||||
}
|
||||
|
||||
fn alex() -> ServerPlayer {
|
||||
ServerPlayer {
|
||||
id: "00000000-0000-4000-8000-000000000001".into(),
|
||||
name: "Alex".into(),
|
||||
x: 0.5,
|
||||
y: 64.0,
|
||||
z: 0.5,
|
||||
dimension: "minecraft:the_nether".into(),
|
||||
game_mode: GameMode::Survival,
|
||||
health: 20.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_mod_runs_only_where_the_world_does() {
|
||||
// A fresh folder: what the mod stored in an earlier run is beside it.
|
||||
let dir = mods_dir().join("server");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("welcome.hmod");
|
||||
std::fs::copy(mods_dir().join("welcome.hmod"), &path).unwrap();
|
||||
let paths = std::slice::from_ref(&path);
|
||||
let window = Mods::load_for(Runs::Client, paths, |_| true, |_| false);
|
||||
assert_eq!(window.entries()[0].status, Status::Elsewhere);
|
||||
assert!(!window.is_running());
|
||||
|
||||
let mut mods = Mods::load_for(Runs::Server, paths, |_| true, |c| c == "give");
|
||||
assert!(mods.runs_server());
|
||||
assert_eq!(
|
||||
mods.server_commands().collect::<Vec<_>>(),
|
||||
["online", "mined"]
|
||||
);
|
||||
assert_eq!(mods.commands().count(), 0, "not the window's chat commands");
|
||||
let alex = alex();
|
||||
mods.set_snapshot(Snapshot {
|
||||
players: vec![alex.clone()],
|
||||
..Snapshot::default()
|
||||
});
|
||||
mods.player_joined(&alex);
|
||||
let greeted = [
|
||||
Output::Tell {
|
||||
name: "Welcome".into(),
|
||||
player: alex.id.clone(),
|
||||
text: "Welcome, Alex! 0 other player(s) online.".into(),
|
||||
},
|
||||
Output::Broadcast {
|
||||
name: "Welcome".into(),
|
||||
text: "Alex is here for the first time".into(),
|
||||
},
|
||||
];
|
||||
assert_eq!(mods.drain(), greeted);
|
||||
let stone = BlockPos { x: 1, y: 63, z: 0 };
|
||||
mods.block_broken(&alex, stone, "minecraft:stone");
|
||||
assert!(mods.server_command(&alex, "mined"));
|
||||
assert!(mods.server_command(&alex, "online"));
|
||||
let reply = |text: &str| Output::Reply {
|
||||
player: alex.id.clone(),
|
||||
text: text.into(),
|
||||
error: false,
|
||||
};
|
||||
assert_eq!(
|
||||
mods.drain(),
|
||||
[reply("You broke 1 block(s)"), reply("Alex (the_nether)")]
|
||||
);
|
||||
assert!(!mods.server_command(&alex, "where"));
|
||||
assert!(
|
||||
!mods.command("online"),
|
||||
"a server command isn't the window's"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -60,6 +60,10 @@ pub struct CheckedStage {
|
||||
pub label: String,
|
||||
pub module: naga::Module,
|
||||
pub info: ModuleInfo,
|
||||
/// The stage's WGSL without the entry points (the prelude, the shared
|
||||
/// files, the file), for a renderer that calls the stage function from
|
||||
/// its own shader (the sky).
|
||||
pub source: String,
|
||||
pub expressions: usize,
|
||||
pub texture_reads: usize,
|
||||
}
|
||||
@@ -169,6 +173,7 @@ pub fn check_stage(pack: &Pack, kind: StageKind, file: &str) -> Result<CheckedSt
|
||||
label: file.to_owned(),
|
||||
module,
|
||||
info,
|
||||
source: own.text,
|
||||
expressions,
|
||||
texture_reads,
|
||||
})
|
||||
|
||||
+11
-6
@@ -1,7 +1,7 @@
|
||||
# The registry index and `.hpack`
|
||||
|
||||
Horizon's registry lists what is made for Horizon and reviewed: mods (`.hmod`), modpacks (`.hpack`), resource packs
|
||||
and, once their format exists, Horizon shader packs. Submissions are pull requests in
|
||||
and Horizon shader packs (`.hshader`, [shaders.md](../shaders.md)). Submissions are pull requests in
|
||||
[ludovic111/horizon-mods](https://github.com/ludovic111/horizon-mods); merging one publishes it. The launcher and the
|
||||
website read one file, `index.json`, which that repository's CI builds. The Rust types and every check below are
|
||||
`horizon_mods::index` and `horizon_mods::modpack` (feature `index`); the sample is
|
||||
@@ -59,7 +59,8 @@ changing what one means, makes schema 2.
|
||||
2. With a project key: its signature verifies with that key (minisign's prehashed and legacy signatures both).
|
||||
3. What the file says matches the entry: a mod's `horizon-mod.toml` (id, version, API, side, capabilities) and its
|
||||
content's fence ([mods.md](../mods.md#content-mods-api-02)); a modpack's manifest (id, version, format, game,
|
||||
mods); a resource pack's `pack.mcmeta`.
|
||||
mods); a resource pack's `pack.mcmeta`; a shader pack's `horizon_shader_api::check` and manifest (id, version,
|
||||
shader API).
|
||||
4. A kind this build can't install is refused with "this Horizon can't install a … yet".
|
||||
|
||||
The game still checks a mod's component imports against its capabilities when it starts it, as for any mod.
|
||||
@@ -99,7 +100,7 @@ own check (`index::inspect`): a mod's API, side and capabilities, a modpack's mo
|
||||
|
||||
```toml
|
||||
id = "coords_hud" # the file's name, and the manifest's id
|
||||
kind = "mod" # mod | modpack | resourcepack; shader once its format exists
|
||||
kind = "mod" # mod | modpack | resourcepack | shader
|
||||
name = "Coordinates HUD"
|
||||
summary = "One line, at most 160 characters."
|
||||
description = """Markdown.""" # optional
|
||||
@@ -156,10 +157,14 @@ How the repository runs (its workflows are in `.github/workflows/`):
|
||||
- **Taking a file down** is a pull request adding it to `revoked.toml`. Removing an entry outright (a test, a project
|
||||
nobody installed) fails `registry review` on purpose and needs an administrator's merge.
|
||||
|
||||
Kinds open to submissions: `mod`, `modpack`, `resourcepack`. `shader` is in the schema and stays closed until
|
||||
Horizon's own shader pack format exists (Iris and OptiFine packs are for the Modrinth browser); its check will compile
|
||||
the pack in a headless Horizon. A new kind gets its own check before it opens.
|
||||
Kinds open to submissions: `mod`, `modpack`, `resourcepack`, `shader`. A shader pack (`.hshader`) passes
|
||||
`horizon_shader_api::check`, the check the game runs before it loads one (`horizon-shader check`, [shaders.md](../shaders.md)):
|
||||
every stage validated by naga and translated for Vulkan, Metal and DirectX 12; its manifest's id, version and shader
|
||||
API line are its facts. Iris and OptiFine packs are for the Modrinth browser. A new kind gets its own check before it
|
||||
opens.
|
||||
|
||||
## Changelog
|
||||
|
||||
- 2026-10-26: the launcher installs `shader` files into `shaderpacks/`; the sample index lists one (`glow`).
|
||||
- 2026-10-25: `shader` opens, checked by `horizon_shader_api::check`; its files are `.hshader`.
|
||||
- Schema 1 (2026-10-24): kinds `mod`, `modpack`, `resourcepack`, `shader`; `.hpack` format 1.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!-- Generated from crates/horizon-mod-sdk/wit/horizon.wit and the manifest's capabilities by crates/horizon-mods/tests/api_reference.rs; a test fails when this file is out of date. Update it with: HORIZON_WRITE_DOCS=1 cargo test -p horizon-mods --features pack --test api_reference -->
|
||||
# Mod API reference
|
||||
|
||||
The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, every interface, type, function and hook in it, and the capabilities a manifest may list. The guide is [mods.md](../mods.md); stability and versions: [stability.md](stability.md). Manifest `api` lines this game serves: `0.1`, `0.2`.
|
||||
The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, every interface, type, function and hook in it, and the capabilities a manifest may list. The guide is [mods.md](../mods.md); stability and versions: [stability.md](stability.md). Manifest `api` lines this game serves: `0.1`, `0.2`, `0.3`.
|
||||
|
||||
## Capabilities
|
||||
|
||||
@@ -16,12 +16,22 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
|
||||
| `ui` | [`ui`](#ui) | show its own screens and a settings page |
|
||||
| `render` | [`render`](#render) | draw on your screen, shake and zoom the camera |
|
||||
| `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys |
|
||||
| `players` | [`players`](#players) | see who is on the server and message them |
|
||||
|
||||
## World `horizon-mod`
|
||||
|
||||
A client mod: runs in the player's game.
|
||||
|
||||
- Imports (what the game offers): `log`, `game`, `chat`, `hud`, `storage`, `command`
|
||||
- Exports (what the mod provides): `events`
|
||||
|
||||
## World `horizon-server-mod`
|
||||
|
||||
A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): runs where the world is simulated, on the dedicated server, a LAN host and single player's own server.
|
||||
|
||||
- Imports (what the game offers): `log`, `storage`, `players`
|
||||
- Exports (what the mod provides): `server-events`
|
||||
|
||||
## World `horizon-ui-mod`
|
||||
|
||||
A mod with widgets (capability `ui`): the SDK builds every mod against this world. Mods built for `horizon-mod` alone (no `ui-events` export) still load and simply hear nothing of their widgets.
|
||||
@@ -434,3 +444,76 @@ What the game calls. Only the hooks `init` asks for are ever called.
|
||||
| `frame` | `func(seconds: f32)` | Each rendered frame, with the seconds since the last one. |
|
||||
| `command` | `func(name: string, args: string) -> result<option<string>, string>` | `/name args`: ok(some(text)) is shown as feedback, err(text) in red. |
|
||||
| `chat` | `func(text: string)` | Each chat line the player receives, as plain text. |
|
||||
|
||||
## `players`
|
||||
|
||||
Access: capability `players`.
|
||||
|
||||
Capability `players`, server mods only (manifest `api = "0.3"`, experimental): the players on the server, and messages to them.
|
||||
|
||||
### enum `game-mode`
|
||||
|
||||
| Case | |
|
||||
| --- | --- |
|
||||
| `survival` | |
|
||||
| `creative` | |
|
||||
| `adventure` | |
|
||||
| `spectator` | |
|
||||
|
||||
### record `player`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `id` | `string` | The player's UUID, `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`. |
|
||||
| `name` | `string` | |
|
||||
| `x` | `f64` | Feet position, in blocks. |
|
||||
| `y` | `f64` | |
|
||||
| `z` | `f64` | |
|
||||
| `dimension` | `string` | `minecraft:overworld`, `minecraft:the_nether`, ... |
|
||||
| `game-mode` | `game-mode` | |
|
||||
| `health` | `f32` | Hit points as vanilla counts them: 20 is full health without effects. |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `online` | `func() -> list<player>` | The players online, in the order they joined. |
|
||||
| `tell` | `func(player: string, text: string) -> bool` | A system message to one player, after the mod's name; false when no player with that id is online. Up to 8 messages per call. |
|
||||
| `broadcast` | `func(text: string)` | A system message to every player and the server's log, after the mod's name. Counts toward the same 8 per call. |
|
||||
|
||||
## `server-events`
|
||||
|
||||
Access: exported by the mod: the game calls it.
|
||||
|
||||
What the server calls in a server mod (manifest `api = "0.3"`, experimental). Only the hooks `init` asks for are ever called. The player in each event is as the server saw them when it happened.
|
||||
|
||||
### type `player`
|
||||
|
||||
`type player = player`
|
||||
|
||||
### record `registration`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `commands` | `list<string>` | Commands players may type, without the slash. A name vanilla already uses is refused (vanilla's command runs). |
|
||||
| `tick` | `bool` | Call `tick` every server tick (20 per second). |
|
||||
| `joins` | `bool` | Call `player-joined` and `player-left`. |
|
||||
| `chat` | `bool` | Call `chat` for each chat message a player sends. |
|
||||
| `blocks` | `bool` | Call `block-broken` and `block-placed`. |
|
||||
|
||||
### record `block-pos`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `x` | `s32` | |
|
||||
| `y` | `s32` | |
|
||||
| `z` | `s32` | |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `init` | `func() -> result<registration, string>` | Once, after loading. An error keeps the mod off and is logged. |
|
||||
| `tick` | `func(tick: u64)` | Each server tick, with the server's tick counter. |
|
||||
| `player-joined` | `func(player: player)` | A player joined the server; they are in `players.online` already. |
|
||||
| `player-left` | `func(player: player)` | A player left the server; they are no longer in `players.online`. |
|
||||
| `chat` | `func(player: player, text: string)` | A chat message a player sent, as plain text. |
|
||||
| `command` | `func(player: player, name: string, args: string) -> result<option<string>, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. |
|
||||
| `block-broken` | `func(player: player, pos: block-pos, state: string)` | A player broke the block at `pos` in their dimension: `state` is what was there, as `minecraft:oak_log[axis=y]`. |
|
||||
| `block-placed` | `func(player: player, pos: block-pos, state: string)` | A player placed `state` at `pos` in their dimension. |
|
||||
|
||||
+16
-11
@@ -13,14 +13,14 @@ the player before the mod is turned on, and checked against the component's real
|
||||
|
||||
| | Count |
|
||||
| --- | --- |
|
||||
| Interfaces the game offers | 5: `log`, `game`, `chat`, `hud`, `storage` |
|
||||
| Functions in them | 9 |
|
||||
| Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat` |
|
||||
| Capabilities | 5: `game-read`, `chat`, `hud`, `storage`, `registries` |
|
||||
| Manifest `api` lines served | 2: `0.1` (code), `0.2` (content) |
|
||||
| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers |
|
||||
| Interfaces the game offers | 6: `log`, `game`, `chat`, `hud`, `storage`; `players` for server mods |
|
||||
| Functions in them | 12 |
|
||||
| Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat`; a server mod 8: `init`, `tick`, `player-joined`, `player-left`, `chat`, `command`, `block-broken`, `block-placed` |
|
||||
| Capabilities | 6: `game-read`, `chat`, `hud`, `storage`, `registries`, `players` |
|
||||
| Manifest `api` lines served | 3: `0.1` (code), `0.2` (content), `0.3` (server mods, experimental) |
|
||||
| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (5 builders), `export_server_mod!` |
|
||||
| `cargo horizon-mod` | `new` (templates `code` and `content`), `build`, `run`, `test`, `check` |
|
||||
| Example mods | `coords-hud` (code), `ruby-content` (content) |
|
||||
| Example mods | `coords-hud` (code), `ruby-content` (content), `welcome` (server) |
|
||||
|
||||
## Guide
|
||||
|
||||
@@ -49,6 +49,8 @@ call, 4 MiB of storage, fuel per call).
|
||||
- `crates/horizon-mod-sdk/examples/coords-hud`: coordinates, facing and time on the HUD; `/where`, `/coords`; storage.
|
||||
- `crates/horizon-mod-sdk/examples/ruby-content`: no code; a gem and a block of ruby from vanilla templates, with
|
||||
their recipes, loot, tags, models, textures and names.
|
||||
- `crates/horizon-mod-sdk/examples/welcome`: a server mod; greets players who join, announces newcomers (kept in
|
||||
storage), `/online` and `/mined`.
|
||||
- `crates/horizon-mods/tests/guest`: a mod that misbehaves on command (spins, panics, grows its memory), for the
|
||||
sandbox tests.
|
||||
|
||||
@@ -78,15 +80,16 @@ scripting runtime in the game.
|
||||
## Stability
|
||||
|
||||
Preview ([stability.md](stability.md)): API 0.1 and content 0.2 are served together; a mod built for 0.1.0 keeps
|
||||
loading on every 0.1.x game. Server mods come as their own line, `api = "0.3"`, experimental first.
|
||||
loading on every 0.1.x game. Server mods are their own line, `api = "0.3"`, experimental: they may change in any
|
||||
release.
|
||||
|
||||
## Not there yet
|
||||
|
||||
What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
- **Server mods** (`api = "0.3"`): the same component running on the server thread and the dedicated server, with world events (block
|
||||
broken or placed, entity spawned or killed, player joined or left), game rules and server commands with typed
|
||||
arguments.
|
||||
- **Server mods in the game** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): the
|
||||
contract, runtime and SDK are here; next the server thread, LAN host and dedicated server start them and call
|
||||
their hooks, then entity events, game rules and server commands with typed arguments.
|
||||
- **World and blocks**: read blocks, block states and biomes in loaded chunks; change them through the server's block
|
||||
log, so clients and the parity harnesses see vanilla's updates.
|
||||
- **Items and inventories**: the player's inventory, held item and open container; item stacks with components.
|
||||
@@ -102,6 +105,8 @@ What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
## Changelog
|
||||
|
||||
- API 0.3 (server mods, experimental): world `horizon-server-mod`, capability `players`, the `server-events`
|
||||
hooks; SDK `server::ServerMod`; example `welcome`.
|
||||
- SDK: `cargo horizon-mod test` and `horizon_mods::testing`, test scripts in TOML; the template has one.
|
||||
- Experimental: `ui` button widget; `render.set-corner`, `text-width`, `frame-stats`; `input.mapping`,
|
||||
`clicks-per-second` (what the official FPS, keystrokes and zoom mods need).
|
||||
|
||||
+3
-2
@@ -91,11 +91,12 @@ pack exist ([stability.md](stability.md)).
|
||||
|
||||
## Not there yet
|
||||
|
||||
The stages and everything that runs a pack (the format above is read and checked). The order: the renderer hooks shared with the format loader, then the material and post
|
||||
stages with options and hot reload, then the overlay, lighting, sky and shadow stages.
|
||||
The material stage in the game (the sky and post stages run, with hot reload), option values other than the defaults,
|
||||
then the overlay, lighting and shadow stages.
|
||||
|
||||
## Changelog
|
||||
|
||||
- 2026-10-26: the sky stage in the game: the pack's `sky` gets vanilla's colour along each ray.
|
||||
- 2026-10-26: the post stage in the game (`HORIZON_SHADER_PACK`, hot reload with the last good pack kept).
|
||||
- 2026-10-25: `horizon-shader` (`new`, `check`, `pack`), three templates, the example pack and the guide.
|
||||
- 2026-10-25: the check (naga validation, signatures, options, budgets, SPIR-V/Metal/HLSL translation).
|
||||
|
||||
@@ -92,7 +92,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel
|
||||
| Mod API: `render` (HUD shapes, camera shake and zoom; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` |
|
||||
| Mod API: `input` (claimed items' use, the mod's keys, the mouse wheel) | experimental | manifest `experimental = ["input"]` |
|
||||
| Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` |
|
||||
| Server mods (events, world, server commands) | not started | manifest `api = "0.3"`, experimental first |
|
||||
| Server mods: world `horizon-server-mod`, `players`, `server-events` | experimental | manifest `api = "0.3"` |
|
||||
| Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | |
|
||||
| `cargo horizon-mod` (`new`, `build`, `run`), `horizon-mod-sdk` | preview | 0.1.0 |
|
||||
| Shader API | not started | |
|
||||
|
||||
@@ -51,7 +51,7 @@ file selects ~103.
|
||||
| 34 | Multiplayer and LAN screens, friends (44) | `L/multiplayer.rs`, `G/lan_screen.rs`, `G/friends.rs`, `L/friends_screen.rs`, `crates/horizon-friends/`, `crates/horizon-relay/` | lan, world_options; `python3 tools/test_friends.py` |
|
||||
| 35 | Dispensers (43) | `G/dispenser.rs`, `G/dispense_fixture.rs` (the harness side) | dispenser |
|
||||
| 36 | Audio and music (38) | `L/audio.rs`, `L/sound_engine.rs`, `L/sound_events.rs`, `L/music.rs`, `G/music.rs`, `L/ambience.rs`, `G/subtitle_hud.rs` | sound_engine, sound_event, music, situational_music, ambient_sound, subtitle |
|
||||
| 37 | Integrated server and levels (34) | `G/integrated.rs`, `G/levels.rs`, `G/server_travel.rs` | server_dimension_players, `lan_e2e --server-thread` (portals, levels, distance, lava) |
|
||||
| 37 | Integrated server and levels (34) | `G/integrated.rs`, `G/levels.rs`, `G/server_travel.rs` | server_dimension_players, `lan_e2e` (server-thread by default; portals, levels, distance, lava) |
|
||||
| 38 | Command parsing (34) | `L/command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`) | command_parse (corpus `tools/command_parse_corpus.py`) |
|
||||
| 39 | Benchmarks and telemetry (34) | `L/benchmark.rs`, `tools/perf_bench.py`, `L/telemetry.rs`, `crates/horizon-telemetry*/`, `crates/horizon-bench/` | `python3 -m unittest tests.test_perf_bench`; [benchmark.md](benchmark.md) |
|
||||
| 40 | Explosions and TNT (31) | `G/explosion.rs`, `G/tnt.rs` | lan_e2e blast; no dedicated harness yet |
|
||||
|
||||
+14
-19
@@ -1,6 +1,6 @@
|
||||
# Horizon extras
|
||||
|
||||
Optional conveniences built into the client: fullbright, dynamic lights, a minimap, auto-reconnect,
|
||||
Optional conveniences built into the client: fullbright, dynamic lights, auto-reconnect,
|
||||
Mouse Tweaks-style inventory controls and inventory sorting. **Every one is off by default**: a fresh
|
||||
install looks and behaves exactly like vanilla 26.3, and turning an extra off
|
||||
again restores vanilla's behaviour completely.
|
||||
@@ -12,8 +12,8 @@ again restores vanilla's behaviour completely.
|
||||
| Settings, parsing and saving | `crates/horizon-client/src/extras.rs` |
|
||||
| FPS and click counters (for mods) | `extras.rs` (pure logic, unit tested) |
|
||||
| Dynamic lights: item glow, nearest sources | `crates/horizon-client/src/dynamic_light.rs` (unit tested), `game/dynamic_lights.rs`, `terrain.wgsl` and `entity.wgsl` (`dynamic_block_light`) |
|
||||
| HUD drawing (minimap frame, corner stacking) | `crates/horizon-client/src/extras_hud.rs` |
|
||||
| Minimap colours, tiles and image | `crates/horizon-client/src/minimap.rs` |
|
||||
| HUD drawing (a mod's minimap, corner stacking) | `crates/horizon-client/src/extras_hud.rs` |
|
||||
| Minimap colours, tiles and image (for `render.set-minimap`) | `crates/horizon-client/src/minimap.rs` |
|
||||
| Reconnect policy and backoff | `crates/horizon-client/src/reconnect.rs` |
|
||||
| Game glue (input hooks, per-frame update) | `crates/horizon-client/src/game/extras.rs` |
|
||||
| Mouse Tweaks-style controls, sort buttons | `crates/horizon-client/src/game/tweaks.rs` |
|
||||
@@ -62,7 +62,7 @@ in Controls, and adding one would put a non-vanilla mapping into `options.txt`.
|
||||
|
||||
### Moved to the mod browser
|
||||
|
||||
The **FPS counter**, **Keystrokes** and **Zoom** are official mods now (`mods/official/`, [mods.md](mods.md#horizons-official-mods)),
|
||||
The **FPS counter**, **Keystrokes**, **Zoom** and the **Minimap** are official mods now (`mods/official/`, [mods.md](mods.md#horizons-official-mods)),
|
||||
with the same look and options. On the first start after the update, a player who had one on gets the mod installed
|
||||
from Horizon's registry and turned on, with their corner and options carried over (Zoom's key too, into
|
||||
`horizon-mods.txt`, when it wasn't Z), and reads one line in the chat ("Zoom moved to the mod browser: installed for
|
||||
@@ -71,19 +71,14 @@ SHA-256, signature, manifest); if it fails (offline), the next start tries again
|
||||
keys and lists what was done in `movedToMods`. Code: `crates/horizon-client/src/moved_extras.rs`,
|
||||
`game/moved_extras.rs`.
|
||||
|
||||
### Minimap (`minimap`, default off)
|
||||
- A corner map (top right by default), square or round, small/medium/large,
|
||||
zoom 0.5 to 4 blocks per pixel, rotating with the player or north up, with the
|
||||
player arrow (vanilla's map decoration sprite).
|
||||
- Colours are vanilla's `MapColor` per block, as map items use, with the map
|
||||
item's height shading and water-depth dithering.
|
||||
- Underground, in the Nether and under any roof, it maps the floor around the
|
||||
player's height instead of the top block, so caves read sensibly.
|
||||
- Cost: one cached 16x16 tile per loaded chunk (packed map colour and height).
|
||||
Tiles are filled nearest first and refreshed when blocks change, within a time
|
||||
budget of 0.3 ms a frame; composing the 128x128 image is a few thousand
|
||||
lookups, done only when the view moved or a tile changed, and uploaded into a
|
||||
dedicated atlas slot. With the minimap off nothing runs.
|
||||
The game still draws the minimap, for the mod (`render.set-minimap`, [mods.md](mods.md)):
|
||||
- a corner map (top right by default), square or round, small/medium/large, zoom 0.5 to 4 blocks per pixel, rotating
|
||||
with the player or north up, with the player arrow (vanilla's map decoration sprite);
|
||||
- vanilla's `MapColor` per block, as map items use, with the map item's height shading and water-depth dithering;
|
||||
- underground, in the Nether and under any roof, the floor around the player's height instead of the top block;
|
||||
- one cached 16x16 tile per loaded chunk (packed map colour and height), filled nearest first and refreshed when
|
||||
blocks change within 0.3 ms a frame; the 128x128 image is recomposed only when the view moved or a tile changed, and
|
||||
uploaded into a dedicated atlas slot. With no mod showing a map, nothing runs.
|
||||
|
||||
### Auto-reconnect (`autoReconnect`, default off)
|
||||
- On the "Connection lost" screen after a multiplayer connection drops, a
|
||||
@@ -140,11 +135,11 @@ and the container screen tests are unchanged).
|
||||
the world, like vanilla's HUD. Extras in the top left corner give way to the
|
||||
debug screen (F3), which shows the FPS anyway.
|
||||
- Corners stack: extras placed in the same corner stack downward (top corners)
|
||||
or upward (bottom corners) in the order minimap, then mods' panels. The top
|
||||
or upward (bottom corners) in the order a mod's minimap, then mods' panels. The top
|
||||
right corner starts below the status effect icons.
|
||||
|
||||
## Perf budget
|
||||
|
||||
Off: a flag check per frame per extra (no allocations, no world access).
|
||||
On: the minimap stays under 0.3 ms of CPU
|
||||
A mod's minimap stays under 0.3 ms of CPU
|
||||
per frame (tile budget) plus a 64 KiB texture upload when its image changes.
|
||||
|
||||
@@ -321,7 +321,7 @@ Search for packs Horizon loads.
|
||||
horizon-launcher mods search [TEXT]...
|
||||
|
||||
- `TEXT`
|
||||
- `--kind` (mod, resource, modpack)
|
||||
- `--kind` (mod, resource, modpack, shader)
|
||||
- `--everything`: Also what was made for other versions or runs only partly, each marked
|
||||
- `--source` (modrinth, curseforge, horizon)
|
||||
|
||||
|
||||
+10
-6
@@ -1,7 +1,7 @@
|
||||
# The launcher's mod browser
|
||||
|
||||
Search Modrinth (CurseForge support is coming soon) for Java mods, modpacks, resource packs and shader
|
||||
packs, see how well each one runs before installing it, and install it with its checksum checked. This is item 16 of the roadmap and issue #577. The code is in
|
||||
Search Modrinth (CurseForge support is coming soon) for Java mods, modpacks and resource packs, and Horizon's
|
||||
registry for Horizon's own mods, modpacks, resource packs and shader packs; see how well each one runs before installing it, and install it with its checksum checked. This is item 16 of the roadmap and issue #577. The code is in
|
||||
`launcher/src/browser.rs` and `launcher/src/browser/`.
|
||||
|
||||
## What it offers
|
||||
@@ -16,6 +16,7 @@ yet (Modrinth has no `horizon` loader).
|
||||
| Java mods (Fabric, NeoForge, Forge, Quilt) | ported into `horizon-mods/<mod id>/` and turned on | Checked from its jar before install: **Works**, **Partly** or **Doesn't run** ([below](#java-mods)) |
|
||||
| Resource packs | `resourcepacks/` beside `options.txt` | **Works** when made for 26.3 ([resource-packs.md](resource-packs.md) lists what Horizon reads). Older packs are **Partly**: they load with vanilla's compatibility warning |
|
||||
| Modpacks (`.mrpack`, CurseForge zip) | the Modpacks page's import | **Partly**: Horizon runs the mods it can port, from the player's own downloads ([modpacks.md](modpacks.md)) |
|
||||
| Shader packs (`.hshader`, Horizon's registry only) | `shaderpacks/` beside `options.txt` | **Works** when made for 26.3: checked by the game's own check before install ([shaders.md](shaders.md)). The `shaders/`-format packs on Modrinth and CurseForge are not offered |
|
||||
|
||||
By default a search shows only what runs: Java mods made for 26.3, resource packs made for 26.3, and every modpack. **Show everything** lists the rest of the kind too, each marked with how well it runs; what doesn't run is
|
||||
never offered for install.
|
||||
@@ -74,7 +75,8 @@ start); the hedge places and its recipe crafts 4.
|
||||
|
||||
## The Mods page
|
||||
|
||||
The launcher's **Mods** page has the three kinds as tabs (Mods, Modpacks, Resource packs), a search field (Enter searches), **Show everything** and
|
||||
The launcher's **Mods** page has the four kinds as tabs (Mods, Modpacks, Resource packs, Shader packs; the last
|
||||
searches Horizon's registry), a search field (Enter searches), **Show everything** and
|
||||
the source: Modrinth, with **CurseForge (coming soon)** beside it, disabled. Each result is an index row: its summary, author,
|
||||
downloads, source and licence, how well it runs (and why), **Page** (the project's page on its source) and
|
||||
**Install** (**Import** for a modpack). The Modpacks tab lists the imported packs first, with their coverage
|
||||
@@ -125,7 +127,8 @@ same name the player put there is never overwritten.
|
||||
|
||||
- **Install** picks the newest version that runs, then its required dependencies, checked before any download: a
|
||||
dependency that isn't a pack Horizon loads (a Java mod) stops the install. Dependencies go in first. A resource
|
||||
pack still has to be turned on in the game's Resource Packs screen, as in vanilla.
|
||||
pack still has to be turned on in the game's Resource Packs screen, as in vanilla, and a shader pack picked in
|
||||
the game's Shader Packs page.
|
||||
- **Update** installs the newer version and removes the old file.
|
||||
- **Remove** deletes the file and its entry. Packs installed as dependencies stay.
|
||||
- **A modpack** is downloaded (checked the same way) into `ports/downloads/`, imported, and ported straight away
|
||||
@@ -149,7 +152,7 @@ horizon-launcher mods remove faithful-32x
|
||||
|
||||
## Sources
|
||||
|
||||
**Horizon's registry.** Mods (`.hmod`) and resource packs made for Horizon, reviewed as pull requests in
|
||||
**Horizon's registry.** Mods (`.hmod`), modpacks (`.hpack`), resource packs and shader packs (`.hshader`) made for Horizon, reviewed as pull requests in
|
||||
[ludovic111/horizon-mods](https://github.com/ludovic111/horizon-mods) ([api/mod-index.md](api/mod-index.md)). The
|
||||
launcher reads its `index.json` (`browser/horizon.rs`; `HORIZON_MOD_INDEX=<file or https address>` reads a test
|
||||
registry instead, whose files may then be on disk) at most every ten minutes, and keeps the last copy in
|
||||
@@ -164,7 +167,8 @@ checked pack, `pack.json` and `home/`, the profile's game folder, where each of
|
||||
like any registry mod and turned on or off as the pack says; its overrides (settings, resource packs, a mod's saved
|
||||
settings) are copied in on the first install only, so the player's changes survive updates. A pack whose mod was taken
|
||||
down installs nothing. It is listed on the Modpacks tab with **Play** and **Remove**, and plays like an imported pack
|
||||
(`modpacks::apply_profile`). Shader packs are listed by the index but not installed by this launcher yet.
|
||||
(`modpacks::apply_profile`). A shader pack goes to `shaderpacks/<file>` once `check_file` has run the game's own
|
||||
check on it (`horizon_shader_api::check`); a taken-down one is named, for the player to remove.
|
||||
|
||||
```sh
|
||||
horizon-launcher mods search --source horizon --kind mod coords # with whether it is signed and what it may do
|
||||
|
||||
+35
-2
@@ -15,7 +15,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
|
||||
| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, command, ui; tick, frame, chat and command hooks |
|
||||
| SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 |
|
||||
| Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands |
|
||||
| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom |
|
||||
| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap |
|
||||
| Runtime | `crates/horizon-mods` | wasmtime 48 LTS, component model |
|
||||
| Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new [--template code\|content] / build / run / test / check`, and the registry's CI (`registry build / review / list`) |
|
||||
| In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods |
|
||||
@@ -120,7 +120,7 @@ loading. Ordered by what the first native ports need:
|
||||
| `world-read` | blocks and biomes around the player, within the render distance | minimaps, schematics |
|
||||
| `render` (world) | world-space lines, boxes and billboards, beside the HUD shapes `render` has | Litematica-style placement, waypoints |
|
||||
| `registries` | new blocks, items, entities and recipes, mostly data: JSON models, textures, loot and recipes in the `.hmod`'s `assets/` and `data/` | server side; see [Multiplayer](#multiplayer) |
|
||||
| `server` | world events (block break/place, entity spawn/death, player join), game rules, server commands | runs where the world is simulated |
|
||||
| `server` | world events (entity spawn/death), game rules, world read/write, typed server commands | after [server mods 0.3](#server-mods-api-03-experimental)'s players, chat, blocks and commands |
|
||||
| `net` | a mod's own client↔server channel (custom payloads) | only between the two halves of the same mod |
|
||||
|
||||
There is no file, socket, process or raw-input interface, on purpose.
|
||||
@@ -452,6 +452,38 @@ none.
|
||||
"top": "carve", "bottom": "none", "rigid_junctions": true, "inflate": true } }
|
||||
```
|
||||
|
||||
### Server mods (API 0.3, experimental)
|
||||
|
||||
A server mod runs where the world is simulated: on the dedicated server, on a
|
||||
LAN host and on single player's own server, never in a player's window. Its
|
||||
manifest says `side = "server"` and `api = "0.3"` (and only a server mod may);
|
||||
its component targets the WIT world `horizon-server-mod` instead of
|
||||
`horizon-mod`. Experimental: it may change in any release
|
||||
([stability](api/stability.md)).
|
||||
|
||||
| Interface | Capability | Functions |
|
||||
|---|---|---|
|
||||
| `log` | always | as for client mods |
|
||||
| `storage` | `storage` | as for client mods, in the server's `horizon-mods/` |
|
||||
| `players` | `players` | `online()`: id, name, position, dimension, game mode, health of each player on; `tell(id, text)`, `broadcast(text)`: system messages after the mod's name, 8 per call |
|
||||
|
||||
| Hook (export `server-events`) | When |
|
||||
|---|---|
|
||||
| `init() -> result<registration, string>` | once, after loading |
|
||||
| `tick(tick)` | each server tick |
|
||||
| `player-joined(player)`, `player-left(player)` | `registration.joins` |
|
||||
| `chat(player, text)` | `registration.chat`: each chat message a player sends |
|
||||
| `command(player, name, args)` | `/name args` typed by a player, for a command it registered; `ok(some)` is that player's feedback, `err` their red error |
|
||||
| `block-broken(player, pos, state)`, `block-placed(player, pos, state)` | `registration.blocks`, with the state as `minecraft:oak_log[axis=y]` |
|
||||
|
||||
Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for
|
||||
client mods; `players` is for server mods. In Rust: `impl
|
||||
horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is
|
||||
[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs). The
|
||||
runtime, the registry's `check` and the SDK run them today; the game starts
|
||||
them once its server code calls these hooks (the next step), and until then a
|
||||
server mod that is turned on shows as run elsewhere.
|
||||
|
||||
## Publish your mod
|
||||
|
||||
Horizon's registry lists mods, modpacks (`.hpack`) and resource packs made for Horizon, each reviewed before it is
|
||||
@@ -490,6 +522,7 @@ so the same rustc and `Cargo.lock` give the same file.
|
||||
| FPS Counter | `fps_overlay` | Extras > FPS counter | `corner`: `top_left` (default), `top_right`, `bottom_left`, `bottom_right`; `lows`: `false` (default), `true` |
|
||||
| Keystrokes | `keystrokes` | Extras > Keystrokes | `corner`: as above, default `top_left`; `cps`: `true` (default), `false` |
|
||||
| Zoom | `zoom` | Extras > Zoom | `level`: `2`, `3`, `4` (default), `6`, `8`, `10`; `smooth`: `true` (default), `false`; `sensitivity` (slower turning): `true` (default), `false`. The key is the game's: `key.zoom.zoom` in `horizon-mods.txt`, default `key.keyboard.z` |
|
||||
| Minimap | `minimap` | Extras > Minimap | `corner`: as above, default `top_right`; `size`: `64`, `96` (default), `128`; `shape`: `square` (default), `round`; `zoom` (blocks per pixel): `0.5`, `1` (default), `2`, `4`; `rotate`: `false` (default), `true`. The game draws the map (`render.set-minimap`) |
|
||||
|
||||
## Versions and compatibility
|
||||
|
||||
|
||||
@@ -111,3 +111,53 @@ and shrieker. They supplement the deterministic component comparisons.
|
||||
## Reading vanilla
|
||||
|
||||
Besides the Vineflower sources in `.local/minecraft/<version>/sources/`, `tools/rea_vanilla.py` queries the shipped bytecode through REA (callers through lambdas, overloads, a second decompiler); see [decompilation status](decompilation-status.md#querying-the-shipped-bytecode-with-rea).
|
||||
|
||||
## Player-facing integration and deterministic fixtures
|
||||
|
||||
`python3 tools/lan_e2e.py` runs every LAN check with an integrated server thread,
|
||||
the same path as normal single player. `python3 tools/test_friends.py --client
|
||||
target/fast/horizon-client --relay target/fast/horizon-relay --baseline` covers
|
||||
plain LAN, direct invitations, a local relay and ended invitations in that mode.
|
||||
Both accept `--in-frame` for comparison and retain `--server-thread` for existing
|
||||
callers. Run Linux games under `xvfb-run -a` when no display is available. Each
|
||||
process gets scratch game, launcher, XDG data and config homes; telemetry, audio
|
||||
and launcher self-update are disabled.
|
||||
|
||||
`lan_integration` and `friends_integration` register these suites with `parity.py`.
|
||||
`friends_integration` (under a minute) is selected like any harness when the
|
||||
drivers or game implementation change. `lan_integration` is the whole LAN suite
|
||||
(~40 minutes on a loaded runner, and single checks flake under load), so
|
||||
`tools/parity_hosts.json` lists it under `named_only`: no automatic selection
|
||||
(`--changed`, `--failed`, `--flake-check`, CI, parity-main) picks it; it runs
|
||||
when named and in the nightly audit (`--all`). LAN writes `results.json`
|
||||
with the host mode and each result beside its screenshots and logs. A skipped
|
||||
case is recorded explicitly and does not count as passing coverage.
|
||||
|
||||
The game-binary fixture audit keeps these complementary direct rule tests:
|
||||
|
||||
- `command_harness.rs`: command feedback, styled spans and result callbacks,
|
||||
held player position, explicit ticks and portal completion matching
|
||||
`VanillaCommandExecOracle`. LAN `commands`, `feedback`, `styles`, `levels` and
|
||||
`portals` cover command input, packet feedback and travel across the boundary.
|
||||
- `dispense_fixture.rs`: seeded synthetic worlds, block/event traces, item
|
||||
use/mining and combat hooks matching `VanillaDispenserOracle`. These isolate
|
||||
rule results and RNG order; LAN machines, crafting, clicks, fireball, mining
|
||||
and combat exercise real input and server handling separately. The new
|
||||
`dispenser_input_host` / `dispenser_input_guest` checks press a button and
|
||||
verify authoritative inventory consumption and exactly one drop on both clients.
|
||||
- `sculk_fixture.rs`: scripted events and exact per-tick sculk/warden traces
|
||||
matching `VanillaSculkOracle`; introducing wall-clock network ticks would
|
||||
destroy that deterministic oracle contract. `sculk_input_host` and
|
||||
`sculk_input_guest` separately exercise real footsteps reaching a sensor;
|
||||
failures remain visible rather than changing the oracle trace.
|
||||
- `net_harness.rs`: already a real network client of a dedicated server; keep
|
||||
its handshake, world loading, chat and command packet assertions.
|
||||
|
||||
Library probes, `lan_bot`'s protocol hub fixture, generation/save tests and
|
||||
streaming/mesh tests remain fast deterministic coverage. They do not become
|
||||
full game launches. Setup and authoritative reads use the owning server;
|
||||
interactions stay on the client. `server-hold on|off` provides a prediction-test
|
||||
barrier between server ticks, including player packet handling, while transport
|
||||
threads and control calls remain responsive. `stall MILLISECONDS` stalls only
|
||||
the window to test recovery from a hung frame without process signals interrupting
|
||||
socket reads. Neither mechanism changes normal gameplay.
|
||||
|
||||
+9
-7
@@ -13,8 +13,9 @@ Horizon's own format.
|
||||
| Authoring tool | `horizon-shader` (same crate) | `new`, `check`, `pack` |
|
||||
| Templates | `crates/horizon-shader-api/templates/` | post, sky, material |
|
||||
| Example pack | `crates/horizon-shader-api/packs/golden_hour` | a warm sky and two post passes |
|
||||
| In the game: the post stage | Options > Horizon Settings > Shader Packs | post passes, hot reload |
|
||||
| In the game: sky and material; the launcher and the registry | | not yet |
|
||||
| In the game: the sky and post stages | Options > Horizon Settings > Shader Packs | sky, post passes, hot reload |
|
||||
| The registry and the launcher | `shader` kind ([api/mod-index.md](api/mod-index.md)); the Mods page's Shader packs tab | checked, then installed into `shaderpacks/` |
|
||||
| In the game: the material stage | | not yet |
|
||||
|
||||
## Quick start
|
||||
|
||||
@@ -52,8 +53,8 @@ it on Options > Horizon Settings > Shader Packs, which lists Horizon's packs, ma
|
||||
name>` runs a pack whatever the page says, for development. The game checks the pack first, and refuses one that
|
||||
fails, with its problems in the chat. While it runs, the game looks at the pack twice a second: save a file
|
||||
and the pack is checked and rebuilt in place ("Shader pack ... reloaded"); if the new version fails, the chat says
|
||||
where and the last good version keeps drawing. The post passes run today; the sky and material stages are checked
|
||||
but not drawn yet.
|
||||
where and the last good version keeps drawing. The sky and post stages run today; the material stage is checked but
|
||||
not drawn yet.
|
||||
|
||||
## A pack
|
||||
|
||||
@@ -88,7 +89,7 @@ by Horizon: a pack changes how things look, not how they are drawn.
|
||||
|
||||
| Stage | Your function | What it does |
|
||||
| --- | --- | --- |
|
||||
| `[sky]` | `fn sky(input: SkyInput) -> vec4<f32>` | the sky's colour along each view ray; the sun, moon, stars and clouds are drawn over it |
|
||||
| `[sky]` | `fn sky(input: SkyInput) -> vec4<f32>` | the sky's colour along each view ray, opaque (alpha is ignored), drawn where vanilla draws its sky dome (the Overworld's sky; not the Nether's or the End's); the sun, moon, stars and clouds are drawn over it |
|
||||
| `[material]` | `fn material(input: MaterialInput) -> Surface` | the lit colour of each point of a block's surface, before the alpha test and fog |
|
||||
| `[[post]]` | `fn post(input: PostInput) -> vec4<f32>` | a full-screen pass over the world's picture (up to 8, in order), under the hand and HUD |
|
||||
|
||||
@@ -131,8 +132,9 @@ one keeps drawing), the launcher before it installs one, and the registry's CI b
|
||||
|
||||
`[budget] gpu_ms` is the GPU time your pack aims to add to a frame. To compare, open F3 in the game: while it is
|
||||
open, each pass is timed on the GPU and the overlay shows the pack's total and its costliest passes, by their `name`
|
||||
(the median of the last 15 timed frames). Timing waits for nothing, so it does not slow the game.
|
||||
(the median of the last 15 timed frames). Timing waits for nothing, so it does not slow the game. In a timed frame the sky
|
||||
stage draws in a pass of its own (it shares the world's pass otherwise), so its time includes clearing the picture.
|
||||
|
||||
## Next
|
||||
|
||||
The material and sky stages in the game, and the registry's `shader` kind with installs from the launcher.
|
||||
The material stage in the game.
|
||||
|
||||
Generated
+95
-7
@@ -565,7 +565,16 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
"bit-vec 0.8.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
|
||||
dependencies = [
|
||||
"bit-vec 0.9.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -574,6 +583,12 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.3"
|
||||
@@ -611,7 +626,7 @@ dependencies = [
|
||||
"ash-window",
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"codespan-reporting",
|
||||
"codespan-reporting 0.12.0",
|
||||
"glow",
|
||||
"gpu-alloc",
|
||||
"gpu-alloc-ash",
|
||||
@@ -621,7 +636,7 @@ dependencies = [
|
||||
"libloading",
|
||||
"log",
|
||||
"mint",
|
||||
"naga",
|
||||
"naga 25.0.1",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
@@ -1037,6 +1052,15 @@ dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codespan-reporting"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
|
||||
dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "color_quant"
|
||||
version = "1.1.0"
|
||||
@@ -2295,7 +2319,7 @@ dependencies = [
|
||||
"log",
|
||||
"lyon",
|
||||
"metal",
|
||||
"naga",
|
||||
"naga 25.0.1",
|
||||
"num_cpus",
|
||||
"objc",
|
||||
"oo7",
|
||||
@@ -2560,6 +2584,9 @@ name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
@@ -2700,6 +2727,7 @@ dependencies = [
|
||||
name = "horizon-mods"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-shader-api",
|
||||
"log",
|
||||
"minisign-verify",
|
||||
"serde",
|
||||
@@ -2742,6 +2770,19 @@ dependencies = [
|
||||
"ring",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-shader-api"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"naga 30.0.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"toml 1.1.8+spec-1.1.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-telemetry"
|
||||
version = "0.1.0"
|
||||
@@ -3543,10 +3584,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b977c445f26e49757f9aca3631c3b8b836942cb278d69a92e7b80d3b24da632"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"bit-set",
|
||||
"bit-set 0.8.0",
|
||||
"bitflags 2.13.2",
|
||||
"cfg_aliases",
|
||||
"codespan-reporting",
|
||||
"codespan-reporting 0.12.0",
|
||||
"half",
|
||||
"hashbrown 0.15.5",
|
||||
"hexf-parse",
|
||||
@@ -3555,12 +3596,50 @@ dependencies = [
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"rustc-hash 1.1.0",
|
||||
"spirv",
|
||||
"spirv 0.3.0+sdk-1.3.268.0",
|
||||
"strum 0.26.3",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "naga"
|
||||
version = "30.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"bit-set 0.10.0",
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
"cfg_aliases",
|
||||
"codespan-reporting 0.13.1",
|
||||
"half",
|
||||
"hashbrown 0.17.1",
|
||||
"indexmap",
|
||||
"libm",
|
||||
"log",
|
||||
"naga-types",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"rustc-hash 1.1.0",
|
||||
"spirv 0.4.0+sdk-1.4.341.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "naga-types"
|
||||
version = "30.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"indexmap",
|
||||
"rustc-hash 1.1.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nanorand"
|
||||
version = "0.7.0"
|
||||
@@ -5405,6 +5484,15 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spirv"
|
||||
version = "0.4.0+sdk-1.4.341.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
|
||||
+10
-1
@@ -28,16 +28,20 @@ pub enum Kind {
|
||||
Modpack,
|
||||
/// A Java mod: its content is ported ([`java`]).
|
||||
Mod,
|
||||
/// One of Horizon's own shader packs (`.hshader`, docs/shaders.md), from Horizon's registry
|
||||
/// only.
|
||||
Shader,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub const ALL: [Kind; 3] = [Kind::Mod, Kind::Modpack, Kind::ResourcePack];
|
||||
pub const ALL: [Kind; 4] = [Kind::Mod, Kind::Modpack, Kind::ResourcePack, Kind::Shader];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Mod => "Mods",
|
||||
Kind::ResourcePack => "Resource packs",
|
||||
Kind::Modpack => "Modpacks",
|
||||
Kind::Shader => "Shader packs",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +50,7 @@ impl Kind {
|
||||
pub fn folder(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Kind::ResourcePack => Some("resourcepacks"),
|
||||
Kind::Shader => Some("shaderpacks"),
|
||||
Kind::Modpack | Kind::Mod => None,
|
||||
}
|
||||
}
|
||||
@@ -237,6 +242,9 @@ pub trait Source: Send + Sync {
|
||||
|
||||
/// What the launcher says wherever CurseForge would be.
|
||||
pub const CURSEFORGE_SOON: &str = "CurseForge support is coming soon.";
|
||||
/// What another source answers for shader packs: Horizon's own are on its registry only.
|
||||
pub const SHADERS_ON_HORIZON: &str =
|
||||
"Horizon's shader packs are on Horizon's registry: pick Horizon.";
|
||||
|
||||
/// The sources this launcher uses: Modrinth and Horizon's registry. CurseForge support is coming
|
||||
/// soon: its API needs a paid key, so no search or install goes to it; `curseforge` is kept for
|
||||
@@ -277,6 +285,7 @@ pub fn support(kind: Kind, game_versions: &[String], loaders: &[String]) -> Supp
|
||||
Kind::Modpack => {
|
||||
Support::Partial("Horizon runs the mods it can port, from your own downloads.".into())
|
||||
}
|
||||
Kind::Shader => Support::No("Not one of Horizon's own shader packs.".into()),
|
||||
Kind::Mod => {
|
||||
if !loaders.iter().any(|l| java::LOADERS.contains(&l.as_str())) {
|
||||
Support::No("Not a Fabric, NeoForge or Forge mod.".into())
|
||||
|
||||
@@ -24,11 +24,16 @@ fn class(kind: Kind) -> u64 {
|
||||
Kind::ResourcePack => 12,
|
||||
Kind::Modpack => 4471,
|
||||
Kind::Mod => 6,
|
||||
Kind::Shader => 6552,
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of a CurseForge class; its shader packs (the shaders/ format) are not offered.
|
||||
fn kind_of(class_id: u64) -> Option<Kind> {
|
||||
Kind::ALL.into_iter().find(|k| class(*k) == class_id)
|
||||
Kind::ALL
|
||||
.into_iter()
|
||||
.filter(|k| *k != Kind::Shader)
|
||||
.find(|k| class(*k) == class_id)
|
||||
}
|
||||
|
||||
/// The key: the environment's, else the one built in. Empty counts as none.
|
||||
@@ -196,6 +201,9 @@ impl Source for CurseForge {
|
||||
}
|
||||
|
||||
fn search(&self, query: &Query) -> Result<Vec<Project>, String> {
|
||||
if query.kind == Kind::Shader {
|
||||
return Err(super::SHADERS_ON_HORIZON.into());
|
||||
}
|
||||
let found = self.get(&search_url(query))?;
|
||||
Ok(found["data"]
|
||||
.as_array()
|
||||
|
||||
@@ -111,13 +111,14 @@ fn fetch_index() -> Result<(Index, String), String> {
|
||||
}
|
||||
|
||||
/// The browser's kind for a registry kind; None for one the launcher doesn't install yet
|
||||
/// (shader packs, kinds newer than this launcher).
|
||||
/// (kinds newer than this launcher).
|
||||
fn kind_of(kind: &index::Kind) -> Option<Kind> {
|
||||
match kind {
|
||||
index::Kind::Mod => Some(Kind::Mod),
|
||||
index::Kind::ResourcePack => Some(Kind::ResourcePack),
|
||||
index::Kind::Modpack => Some(Kind::Modpack),
|
||||
index::Kind::Shader | index::Kind::Other(_) => None,
|
||||
index::Kind::Shader => Some(Kind::Shader),
|
||||
index::Kind::Other(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,6 +373,7 @@ fn relative(kind: Kind, id: &str, file_name: &str) -> Result<String, String> {
|
||||
match kind {
|
||||
Kind::Mod => Ok(format!("{}/{id}.hmod", java::MODS_DIR)),
|
||||
Kind::ResourcePack => Ok(format!("resourcepacks/{file_name}")),
|
||||
Kind::Shader => Ok(format!("shaderpacks/{file_name}")),
|
||||
Kind::Modpack => Err("A modpack installs as its own profile (pack::install).".into()),
|
||||
}
|
||||
}
|
||||
@@ -418,7 +420,8 @@ fn newest<'a>(index: &Index, p: &'a index::Project) -> Result<&'a index::Version
|
||||
})
|
||||
}
|
||||
|
||||
/// Installs version `v` of the registry's mod or resource pack `p` into the game folder `home`.
|
||||
/// Installs version `v` of the registry's mod, resource pack or shader pack `p` into the game
|
||||
/// folder `home`.
|
||||
fn install_version(
|
||||
index: &Index,
|
||||
local: bool,
|
||||
@@ -447,13 +450,17 @@ fn install_version(
|
||||
other.title
|
||||
));
|
||||
}
|
||||
if (target.exists() && old.as_ref().is_none_or(|o| o.file != relative)) || folder_mod.exists() {
|
||||
let clash = target.exists() && old.as_ref().is_none_or(|o| o.file != relative);
|
||||
if project.kind == Kind::Mod && (clash || folder_mod.exists()) {
|
||||
return Err(format!(
|
||||
"A mod with the id {} is already in {}: move it away first.",
|
||||
p.id,
|
||||
java::MODS_DIR
|
||||
));
|
||||
}
|
||||
if clash {
|
||||
return Err(format!("{relative} is already there: move it away first."));
|
||||
}
|
||||
let line = format!("{} {}", p.name, v.version);
|
||||
let file = &version_of(index, p, v).files[0];
|
||||
let staging = home.join("mod-browser/downloads");
|
||||
@@ -518,7 +525,7 @@ pub fn turn_off_revoked(index: &Index, home: &Path) -> Vec<String> {
|
||||
e.title, r.reason
|
||||
));
|
||||
}
|
||||
} else if e.kind == Kind::ResourcePack {
|
||||
} else if matches!(e.kind, Kind::ResourcePack | Kind::Shader) {
|
||||
out.push(format!(
|
||||
"{} was taken down: {} Remove it.",
|
||||
e.title, r.reason
|
||||
|
||||
@@ -48,6 +48,7 @@ fn searches_by_kind_and_words() {
|
||||
// Modpacks under Modpacks; a kind this launcher can't install yet (a world) never.
|
||||
assert_eq!(found("", Kind::Modpack), ["cozy"]);
|
||||
assert!(found("skyblock", Kind::ResourcePack).is_empty());
|
||||
assert_eq!(found("", Kind::Shader), ["glow"]);
|
||||
let p = hud(&index);
|
||||
assert_eq!(p.support(), super::super::Support::Works);
|
||||
assert_eq!(p.page, "https://playhorizon.dev/mods/coords_hud");
|
||||
@@ -95,6 +96,41 @@ fn installs_checked_turns_on_and_removes() {
|
||||
fs::remove_dir_all(&home).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_a_shader_pack_into_shaderpacks() {
|
||||
let index = sample();
|
||||
let home = scratch("shader");
|
||||
let p = project_of(index.project("glow").unwrap()).unwrap();
|
||||
assert_eq!(p.support(), super::super::Support::Works);
|
||||
let done = install_from(&index, true, &p, &home, &|_, _| {}).unwrap();
|
||||
assert_eq!(done[0].file, "shaderpacks/glow-1.0.0.hshader");
|
||||
assert_eq!(done[0].kind, Kind::Shader);
|
||||
assert!(home.join("shaderpacks/glow-1.0.0.hshader").is_file());
|
||||
// Not a mod: nothing turns on in horizon-mods.txt; the game's Shader Packs page picks it.
|
||||
assert!(!home.join("horizon-mods.txt").exists());
|
||||
|
||||
let mut revoked = index.clone();
|
||||
revoked.revoked.push(index::Revoked {
|
||||
id: "glow".into(),
|
||||
sha256: None,
|
||||
reason: "Test.".into(),
|
||||
date: String::new(),
|
||||
});
|
||||
let said = turn_off_revoked(&revoked, &home);
|
||||
assert_eq!(said, ["Soft Glow was taken down: Test. Remove it."]);
|
||||
|
||||
installed::remove(&home, "glow").unwrap();
|
||||
assert!(!home.join("shaderpacks/glow-1.0.0.hshader").exists());
|
||||
// A file of the same name the registry didn't put there is left alone.
|
||||
fs::write(home.join("shaderpacks/glow-1.0.0.hshader"), b"mine").unwrap();
|
||||
let e = install_from(&index, true, &p, &home, &|_, _| {}).unwrap_err();
|
||||
assert_eq!(
|
||||
e,
|
||||
"shaderpacks/glow-1.0.0.hshader is already there: move it away first."
|
||||
);
|
||||
fs::remove_dir_all(&home).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_changed_file_a_taken_id_and_local_files_from_the_real_registry() {
|
||||
let index = sample();
|
||||
|
||||
@@ -13,12 +13,15 @@ fn project_type(kind: Kind) -> &'static str {
|
||||
Kind::ResourcePack => "resourcepack",
|
||||
Kind::Modpack => "modpack",
|
||||
Kind::Mod => "mod",
|
||||
Kind::Shader => "shader",
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of a Modrinth project; its shader packs (the shaders/ format) are not offered.
|
||||
fn kind_of(project_type: &str) -> Option<Kind> {
|
||||
Kind::ALL
|
||||
.into_iter()
|
||||
.filter(|k| *k != Kind::Shader)
|
||||
.find(|k| self::project_type(*k) == project_type)
|
||||
}
|
||||
|
||||
@@ -170,6 +173,9 @@ impl Source for Modrinth {
|
||||
}
|
||||
|
||||
fn search(&self, query: &Query) -> Result<Vec<Project>, String> {
|
||||
if query.kind == Kind::Shader {
|
||||
return Err(super::SHADERS_ON_HORIZON.into());
|
||||
}
|
||||
let found = get(&search_url(query))?;
|
||||
Ok(found["hits"]
|
||||
.as_array()
|
||||
|
||||
@@ -210,6 +210,8 @@ enum KindArg {
|
||||
Mod,
|
||||
Resource,
|
||||
Modpack,
|
||||
/// Horizon's own shader packs (Horizon's registry only)
|
||||
Shader,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, clap::ValueEnum)]
|
||||
@@ -1120,6 +1122,7 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> {
|
||||
KindArg::Resource => Kind::ResourcePack,
|
||||
KindArg::Modpack => Kind::Modpack,
|
||||
KindArg::Mod => Kind::Mod,
|
||||
KindArg::Shader => Kind::Shader,
|
||||
};
|
||||
let query = Query {
|
||||
everything,
|
||||
|
||||
@@ -394,7 +394,7 @@ mod tests {
|
||||
let kinds = &schema["inputSchema"]["properties"]["kind"]["enum"];
|
||||
assert!(
|
||||
kinds.as_array().unwrap().contains(&json!("modpack"))
|
||||
&& !kinds.as_array().unwrap().contains(&json!("shader")),
|
||||
&& kinds.as_array().unwrap().contains(&json!("shader")),
|
||||
"{kinds}"
|
||||
);
|
||||
assert_eq!(
|
||||
|
||||
@@ -54,11 +54,11 @@ enum Page {
|
||||
}
|
||||
|
||||
impl Page {
|
||||
/// `HORIZON_LAUNCHER_PAGE=mods` (or `modpacks`, `servers`, `versions`, `notes`, `settings`)
|
||||
/// opens on that page, for screenshots; Home otherwise.
|
||||
/// `HORIZON_LAUNCHER_PAGE=mods` (or `modpacks`, `shaders`, `servers`, `versions`, `notes`,
|
||||
/// `settings`) opens on that page, for screenshots; Home otherwise.
|
||||
fn from_env() -> Page {
|
||||
match std::env::var("HORIZON_LAUNCHER_PAGE").as_deref() {
|
||||
Ok("mods" | "modpacks") => Page::Mods,
|
||||
Ok("mods" | "modpacks" | "shaders") => Page::Mods,
|
||||
Ok("servers") => Page::Servers,
|
||||
Ok("versions") => Page::Versions,
|
||||
Ok("notes") => Page::Notes,
|
||||
|
||||
+19
-10
@@ -14,10 +14,11 @@ use horizon_port_pack::check::Check;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The kinds, as the Mods page's tabs: name and icon.
|
||||
const KINDS: [(PackKind, &str, &str); 3] = [
|
||||
const KINDS: [(PackKind, &str, &str); 4] = [
|
||||
(PackKind::Mod, "Mods", "box"),
|
||||
(PackKind::Modpack, "Modpacks", "archive"),
|
||||
(PackKind::ResourcePack, "Resource packs", "image"),
|
||||
(PackKind::Shader, "Shader packs", "zap"),
|
||||
];
|
||||
/// Java mods checked at once.
|
||||
const CHECKING: usize = 2;
|
||||
@@ -99,14 +100,18 @@ impl Mods {
|
||||
|
||||
pub(super) fn new(cx: &mut App) -> Self {
|
||||
let (tx, rx) = channel();
|
||||
let page = std::env::var("HORIZON_LAUNCHER_PAGE");
|
||||
let kind = match page.as_deref() {
|
||||
Ok("modpacks") => PackKind::Modpack,
|
||||
Ok("shaders") => PackKind::Shader,
|
||||
_ => PackKind::Mod,
|
||||
};
|
||||
Self {
|
||||
kind: if std::env::var("HORIZON_LAUNCHER_PAGE").as_deref() == Ok("modpacks") {
|
||||
PackKind::Modpack
|
||||
} else {
|
||||
PackKind::Mod
|
||||
},
|
||||
// `HORIZON_LAUNCHER_SOURCE=horizon` opens on Horizon's registry, for screenshots.
|
||||
kind,
|
||||
// `HORIZON_LAUNCHER_SOURCE=horizon` opens on Horizon's registry, for screenshots;
|
||||
// shader packs are only there.
|
||||
source: match std::env::var("HORIZON_LAUNCHER_SOURCE").as_deref() {
|
||||
_ if kind == PackKind::Shader => SourceId::Horizon,
|
||||
Ok("horizon") => SourceId::Horizon,
|
||||
_ => SourceId::Modrinth,
|
||||
},
|
||||
@@ -602,9 +607,9 @@ impl Launcher {
|
||||
}
|
||||
let header = page_header(
|
||||
"Mods",
|
||||
"Mods made for Horizon from its own reviewed registry, and Java mods, modpacks and \
|
||||
resource packs from Modrinth: Horizon ports what a Java mod carries (blocks, items, \
|
||||
recipes, worldgen) and says before you install what runs. Each file is checked \
|
||||
"Mods and shader packs made for Horizon from its own reviewed registry, and Java \
|
||||
mods, modpacks and resource packs from Modrinth: Horizon ports what a Java mod \
|
||||
carries (blocks, items, recipes, worldgen) and says before you install what runs. Each file is checked \
|
||||
against its source's checksum before it reaches your game folder.",
|
||||
&t,
|
||||
);
|
||||
@@ -615,6 +620,10 @@ impl Launcher {
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
if this.mods.kind != kind {
|
||||
this.mods.kind = kind;
|
||||
// Horizon's own shader packs are on its registry only.
|
||||
if kind == PackKind::Shader {
|
||||
this.mods.source = SourceId::Horizon;
|
||||
}
|
||||
// Categories and loaders differ by kind.
|
||||
this.mods.browse.filters = Default::default();
|
||||
this.mods.browse.open = None;
|
||||
|
||||
@@ -10,6 +10,8 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GlyphSource;
|
||||
import net.minecraft.client.gui.font.glyphs.BakedGlyph;
|
||||
@@ -31,9 +33,13 @@ import net.minecraft.util.RandomSource;
|
||||
*/
|
||||
public final class ParityFont {
|
||||
public static ResourceManager resources() throws Exception {
|
||||
return resources(Path.of("/nonexistent-horizon-assets"));
|
||||
}
|
||||
|
||||
public static ResourceManager resources(Path assets) throws Exception {
|
||||
var method = net.minecraft.client.resources.ClientPackSource.class.getDeclaredMethod("createVanillaPackSource", Path.class);
|
||||
method.setAccessible(true);
|
||||
var pack = (net.minecraft.server.packs.VanillaPackResources) method.invoke(null, Path.of("/nonexistent-horizon-assets"));
|
||||
var pack = (net.minecraft.server.packs.VanillaPackResources) method.invoke(null, assets);
|
||||
return pack.asResourceManager();
|
||||
}
|
||||
|
||||
@@ -50,6 +56,38 @@ public final class ParityFont {
|
||||
}
|
||||
}
|
||||
}
|
||||
return create(providers);
|
||||
}
|
||||
|
||||
/** The full default font, including references and the external Unihex fallback. */
|
||||
public static Font createDefault(ResourceManager resources) throws Exception {
|
||||
List<GlyphProvider> providers = new ArrayList<>();
|
||||
loadProviders(resources, Identifier.withDefaultNamespace("default"), providers, new HashSet<>());
|
||||
return create(providers);
|
||||
}
|
||||
|
||||
private static void loadProviders(ResourceManager resources, Identifier font, List<GlyphProvider> providers,
|
||||
Set<Identifier> visiting) throws Exception {
|
||||
if (!visiting.add(font)) throw new IllegalArgumentException("Cyclic font reference: " + font);
|
||||
var file = font.withPath("font/" + font.getPath() + ".json");
|
||||
try (var reader = new InputStreamReader(resources.open(file), StandardCharsets.UTF_8)) {
|
||||
var json = JsonParser.parseReader(reader).getAsJsonObject();
|
||||
for (var element : json.getAsJsonArray("providers")) {
|
||||
var conditional = GlyphProviderDefinition.Conditional.CODEC.parse(JsonOps.INSTANCE, element).getOrThrow();
|
||||
if (!conditional.filter().apply(Set.of())) continue;
|
||||
var definition = conditional.definition().unpack();
|
||||
if (definition.left().isPresent()) {
|
||||
providers.add(definition.left().orElseThrow().load(resources));
|
||||
} else {
|
||||
loadProviders(resources, definition.right().orElseThrow().id(), providers, visiting);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
visiting.remove(font);
|
||||
}
|
||||
}
|
||||
|
||||
private static Font create(List<GlyphProvider> providers) {
|
||||
GlyphSource source = new GlyphSource() {
|
||||
@Override
|
||||
public BakedGlyph getGlyph(int codepoint) {
|
||||
|
||||
@@ -370,7 +370,7 @@ public final class VanillaPackScreenOracle {
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
font = ParityFont.create(ParityFont.resources());
|
||||
font = ParityFont.createDefault(ParityFont.resources(Path.of(args[2])));
|
||||
Minecraft mc = alloc(Minecraft.class);
|
||||
put(mc, Minecraft.class, "font", font);
|
||||
put(mc, Minecraft.class, "lastInputType", InputType.MOUSE);
|
||||
|
||||
@@ -230,7 +230,7 @@ public final class VanillaTabListOracle {
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
Font font = ParityFont.create(ParityFont.resources());
|
||||
Font font = ParityFont.createDefault(ParityFont.resources(Path.of(args[2])));
|
||||
var gson = new Gson();
|
||||
var out = new StringBuilder();
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
@@ -284,6 +284,8 @@ public final class VanillaTabListOracle {
|
||||
put(mc, Minecraft.class, "user", user);
|
||||
var skins = skinManager(c);
|
||||
put(mc, Minecraft.class, "skinManager", skins);
|
||||
var profiles = new ArrayList<GameProfile>();
|
||||
var lookups = new ArrayList<CompletableFuture<?>>();
|
||||
for (var p : c.getAsJsonArray("players")) {
|
||||
var o = p.getAsJsonObject();
|
||||
var uuid = UUID.fromString(o.get("uuid").getAsString());
|
||||
@@ -296,12 +298,22 @@ public final class VanillaTabListOracle {
|
||||
: new Property("textures", t.get("value").getAsString(), sig.getAsString()));
|
||||
}
|
||||
var profile = new GameProfile(uuid, o.get("name").getAsString(), new PropertyMap(properties));
|
||||
// Let the lookup's unpacking and downloads run before the first frame,
|
||||
// as they would have by the time a player list shows.
|
||||
try {
|
||||
skins.get(profile).get(1, java.util.concurrent.TimeUnit.SECONDS);
|
||||
} catch (java.util.concurrent.TimeoutException pending) {
|
||||
}
|
||||
profiles.add(profile);
|
||||
lookups.add(skins.get(profile));
|
||||
}
|
||||
// Start every lookup before waiting: intentionally pending fake
|
||||
// downloads must not add a second for each player in the list.
|
||||
// Keep the same observation window and leave those futures pending.
|
||||
try {
|
||||
CompletableFuture.allOf(lookups.toArray(CompletableFuture[]::new))
|
||||
.get(1, java.util.concurrent.TimeUnit.SECONDS);
|
||||
} catch (java.util.concurrent.TimeoutException pending) {
|
||||
}
|
||||
int profileIndex = 0;
|
||||
for (var p : c.getAsJsonArray("players")) {
|
||||
var o = p.getAsJsonObject();
|
||||
var profile = profiles.get(profileIndex++);
|
||||
var uuid = profile.id();
|
||||
var info = new PlayerInfo(profile, false);
|
||||
put(info, PlayerInfo.class, "gameMode", GameType.byId(o.get("gameMode").getAsInt()));
|
||||
put(info, PlayerInfo.class, "latency", o.get("latency").getAsInt());
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "minimap"
|
||||
version = "1.0.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "Horizon's official minimap: a map of the terrain around you in a corner."
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
horizon-mod-sdk = { path = "../../../crates/horizon-mod-sdk" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,9 @@
|
||||
id = "minimap"
|
||||
name = "Minimap"
|
||||
version = "1.0.0"
|
||||
description = "A map of the terrain around you in a corner, in map colours, square or round, north up or turning with you. Horizon's own, formerly an extra."
|
||||
authors = ["Horizon"]
|
||||
api = "0.1"
|
||||
side = "client"
|
||||
capabilities = ["render", "ui", "storage"]
|
||||
experimental = ["render", "ui"]
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Horizon's official minimap, formerly the built-in extra: a map of the
|
||||
//! terrain around the player in a corner (`render.set-minimap`; the game
|
||||
//! keeps its tiles). Its settings page has the extra's five options, kept in
|
||||
//! the mod's storage (`corner`, `size`, `shape`, `zoom`, `rotate`) with the
|
||||
//! extra's values, where the game writes a player's old extra settings when
|
||||
//! it installs the mod for them.
|
||||
use horizon_mod_sdk::{
|
||||
Mod, Registration,
|
||||
render::{self, Corner, Minimap as MapView},
|
||||
storage,
|
||||
ui::{self, ButtonWidget, Widget},
|
||||
};
|
||||
|
||||
/// (corner, stored value, label), in the extra's order.
|
||||
const CORNERS: [(Corner, &str, &str); 4] = [
|
||||
(Corner::TopLeft, "top_left", "Top left"),
|
||||
(Corner::TopRight, "top_right", "Top right"),
|
||||
(Corner::BottomLeft, "bottom_left", "Bottom left"),
|
||||
(Corner::BottomRight, "bottom_right", "Bottom right"),
|
||||
];
|
||||
/// (side in GUI pixels, label).
|
||||
const SIZES: [(u8, &str); 3] = [(64, "Small"), (96, "Medium"), (128, "Large")];
|
||||
/// Blocks per map pixel.
|
||||
const ZOOMS: [f32; 4] = [0.5, 1.0, 2.0, 4.0];
|
||||
/// Settings page buttons.
|
||||
const CORNER_BUTTON: u32 = 1;
|
||||
const SIZE_BUTTON: u32 = 2;
|
||||
const SHAPE_BUTTON: u32 = 3;
|
||||
const ZOOM_BUTTON: u32 = 4;
|
||||
const ROTATE_BUTTON: u32 = 5;
|
||||
|
||||
/// Indexes into the tables above, and the two switches.
|
||||
struct Minimap {
|
||||
corner: usize,
|
||||
size: usize,
|
||||
round: bool,
|
||||
zoom: usize,
|
||||
rotate: bool,
|
||||
}
|
||||
|
||||
impl Minimap {
|
||||
fn show(&self) {
|
||||
render::set_minimap(Some(MapView {
|
||||
corner: CORNERS[self.corner].0,
|
||||
size: f32::from(SIZES[self.size].0),
|
||||
blocks_per_pixel: ZOOMS[self.zoom],
|
||||
rotate: self.rotate,
|
||||
round: self.round,
|
||||
}));
|
||||
}
|
||||
fn page(&self) {
|
||||
let button = |id, label: String| Widget::Button(ButtonWidget { id, label });
|
||||
let n = ZOOMS[self.zoom];
|
||||
let blocks = if n < 1.0 {
|
||||
"½ block".to_owned()
|
||||
} else if n == 1.0 {
|
||||
"1 block".to_owned()
|
||||
} else {
|
||||
format!("{n} blocks")
|
||||
};
|
||||
ui::set_settings(&[
|
||||
button(CORNER_BUTTON, format!("Corner: {}", CORNERS[self.corner].2)),
|
||||
button(SIZE_BUTTON, format!("Size: {}", SIZES[self.size].1)),
|
||||
button(
|
||||
SHAPE_BUTTON,
|
||||
format!("Shape: {}", if self.round { "Round" } else { "Square" }),
|
||||
),
|
||||
button(ZOOM_BUTTON, format!("Zoom: {blocks} per pixel")),
|
||||
button(
|
||||
ROTATE_BUTTON,
|
||||
format!(
|
||||
"Turn with the player: {}",
|
||||
if self.rotate { "ON" } else { "OFF" }
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
fn save(&self) {
|
||||
let _ = storage::set("corner", CORNERS[self.corner].1.as_bytes());
|
||||
let _ = storage::set("size", SIZES[self.size].0.to_string().as_bytes());
|
||||
let _ = storage::set("shape", if self.round { b"round" } else { b"square" });
|
||||
let _ = storage::set("zoom", ZOOMS[self.zoom].to_string().as_bytes());
|
||||
let _ = storage::set("rotate", if self.rotate { b"true" } else { b"false" });
|
||||
}
|
||||
}
|
||||
|
||||
fn stored(key: &str) -> Option<String> {
|
||||
storage::get(key)
|
||||
.and_then(|v| String::from_utf8(v).ok())
|
||||
.map(|v| v.trim().to_owned())
|
||||
}
|
||||
|
||||
impl Mod for Minimap {
|
||||
fn init() -> Result<(Self, Registration), String> {
|
||||
// The extra's defaults: top right, medium, square, 1 block per
|
||||
// pixel, north up. An unknown value keeps the default.
|
||||
let find = |key: &str, values: &[String], default: usize| {
|
||||
stored(key)
|
||||
.and_then(|v| values.iter().position(|s| *s == v))
|
||||
.unwrap_or(default)
|
||||
};
|
||||
let corners: Vec<String> = CORNERS.iter().map(|c| c.1.to_owned()).collect();
|
||||
let sizes: Vec<String> = SIZES.iter().map(|s| s.0.to_string()).collect();
|
||||
let zooms: Vec<String> = ZOOMS.iter().map(f32::to_string).collect();
|
||||
let map = Minimap {
|
||||
corner: find("corner", &corners, 1),
|
||||
size: find("size", &sizes, 1),
|
||||
round: stored("shape").as_deref() == Some("round"),
|
||||
zoom: find("zoom", &zooms, 1),
|
||||
rotate: stored("rotate").as_deref() == Some("true"),
|
||||
};
|
||||
map.show();
|
||||
map.page();
|
||||
Ok((map, Registration::new()))
|
||||
}
|
||||
fn ui_select(&mut self, id: u32, _row: u32) {
|
||||
let next = |i: usize, n: usize| (i + 1) % n;
|
||||
match id {
|
||||
CORNER_BUTTON => self.corner = next(self.corner, CORNERS.len()),
|
||||
SIZE_BUTTON => self.size = next(self.size, SIZES.len()),
|
||||
SHAPE_BUTTON => self.round = !self.round,
|
||||
ZOOM_BUTTON => self.zoom = next(self.zoom, ZOOMS.len()),
|
||||
ROTATE_BUTTON => self.rotate = !self.rotate,
|
||||
_ => return,
|
||||
}
|
||||
self.save();
|
||||
self.show();
|
||||
self.page();
|
||||
}
|
||||
fn ui_settings_opened(&mut self) {
|
||||
self.page();
|
||||
}
|
||||
}
|
||||
|
||||
horizon_mod_sdk::export_mod!(Minimap);
|
||||
@@ -29,6 +29,7 @@ EXEMPT = {
|
||||
"build_release.py": "builds and packs the release",
|
||||
"release_train.py": "release bookkeeping",
|
||||
"pr_ready.py": "runs cargo checks and parity.py",
|
||||
"test_friends_integration_parity.py": "builds binaries; test_friends.Game isolates every game through integration_env",
|
||||
"port_harness.py": "ports Java code, starts no game",
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Automated game runs must never inherit a real player's data directories."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.integration_env import game_environment, run_game, require_server_reports
|
||||
|
||||
|
||||
class IntegrationEnvironmentTests(unittest.TestCase):
|
||||
def test_all_data_homes_and_network_settings_are_overridden(self):
|
||||
keys = ('HORIZON_HOME', 'HORIZON_LAUNCHER_HOME', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME')
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
env = game_environment({**dict.fromkeys(keys, '/real/player'), 'DISPLAY': ':123'}, root)
|
||||
homes = [Path(env[key]) for key in keys]
|
||||
self.assertEqual(len(set(homes)), 4)
|
||||
self.assertTrue(all(p.is_dir() and p.is_relative_to(root) for p in homes))
|
||||
self.assertEqual(env['DISPLAY'], ':123')
|
||||
self.assertEqual(env['HORIZON_TELEMETRY_URL'], 'off')
|
||||
self.assertEqual(env['HORIZON_LAUNCHER_NO_SELF_UPDATE'], '1')
|
||||
self.assertEqual(env['HORIZON_NO_AUDIO'], '1')
|
||||
|
||||
def test_each_fixture_process_gets_fresh_homes_and_cleanup(self):
|
||||
script = ('import json, os; from pathlib import Path; '
|
||||
'homes = [os.environ[k] for k in '
|
||||
'("HORIZON_HOME", "HORIZON_LAUNCHER_HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME")]; '
|
||||
'assert all(Path(p).is_dir() for p in homes); print(json.dumps(homes))')
|
||||
runs = [json.loads(run_game([sys.executable, '-c', script], env=os.environ,
|
||||
capture_output=True, text=True, check=True).stdout) for _ in range(2)]
|
||||
self.assertFalse(set(runs[0]) & set(runs[1]))
|
||||
self.assertTrue(all(not Path(p).exists() for homes in runs for p in homes))
|
||||
|
||||
|
||||
class PreparedReportTests(unittest.TestCase):
|
||||
def test_partial_report_install_shadows_complete_fallback(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
resources = Path(root) / 'horizon-client' / '26.3'
|
||||
fallback = Path(root) / 'datagen' / 'out' / 'reports'
|
||||
resources.mkdir(parents=True)
|
||||
fallback.mkdir(parents=True)
|
||||
for name in ('registries.json', 'commands.json'):
|
||||
(fallback / name).write_text('{}')
|
||||
self.assertEqual(require_server_reports(resources).resolve(), fallback.resolve())
|
||||
(resources / 'registries.json').write_text('{}')
|
||||
with self.assertRaisesRegex(ValueError, 'installed together'):
|
||||
require_server_reports(resources)
|
||||
(resources / 'commands.json').write_text('{}')
|
||||
self.assertEqual(require_server_reports(resources), resources)
|
||||
@@ -145,6 +145,11 @@ class ParityRunnerTests(unittest.TestCase):
|
||||
with mock.patch.object(parity.sys, "platform", "darwin"):
|
||||
self.assertEqual(parity.platform_skips(config), {"options": "libm"})
|
||||
|
||||
def test_named_only_harnesses_are_listed_from_the_host_config(self):
|
||||
self.assertEqual(parity.named_only({"named_only": {"lan_integration": "slow"}}), {"lan_integration": "slow"})
|
||||
self.assertEqual(parity.named_only({}), {})
|
||||
self.assertIn("lan_integration", parity.named_only(parity.host_config()))
|
||||
|
||||
def test_a_pass_from_another_worktree_counts_only_for_the_same_content(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
elsewhere, here, shared = Path(temp, "a"), Path(temp, "b"), Path(temp, "shared")
|
||||
|
||||
@@ -75,6 +75,8 @@ def game_env(screen, home=None):
|
||||
extra['HORIZON_HOME'] = home
|
||||
if sys.platform == 'darwin':
|
||||
return lab.game_env(**extra)
|
||||
if not shutil.which('vscreen') and os.environ.get('DISPLAY'):
|
||||
return lab.game_env(**extra)
|
||||
env = lab.game_env(VSCREEN=screen, **extra)
|
||||
subprocess.run(['vscreen', 'up'], env=env, check=False, capture_output=True)
|
||||
text = subprocess.run(['vscreen', 'env'], env=env, capture_output=True, text=True, check=True).stdout
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Per-process scratch data for game integration tests (never a player's home)."""
|
||||
from pathlib import Path
|
||||
from contextlib import contextmanager
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
from . import lab
|
||||
except ImportError:
|
||||
import lab
|
||||
|
||||
|
||||
def game_environment(base, root):
|
||||
root = Path(root)
|
||||
env = dict(base, HORIZON_TELEMETRY_URL='off')
|
||||
for key, folder in [('HORIZON_HOME', 'home'), ('HORIZON_LAUNCHER_HOME', 'launcher'),
|
||||
('XDG_DATA_HOME', 'data'), ('XDG_CONFIG_HOME', 'config')]:
|
||||
path = root / folder
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
env[key] = str(path)
|
||||
return lab.game_env(env)
|
||||
|
||||
|
||||
def run_game(command, **kwargs):
|
||||
"""Run a headless game fixture with the same isolation as real-client tests."""
|
||||
with tempfile.TemporaryDirectory(prefix='hz-fixture-') as root:
|
||||
kwargs['env'] = game_environment(kwargs.pop('env', os.environ), root)
|
||||
if any(key in kwargs['env'] for key in
|
||||
('HORIZON_COMMAND_SCRIPT', 'HORIZON_DISPENSE_FIXTURE', 'HORIZON_SCULK_FIXTURE')):
|
||||
# These compare seeded rule/callback traces, not the client/server boundary.
|
||||
command = [*command, '--in-frame']
|
||||
return subprocess.run(command, **kwargs)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def suite_lock():
|
||||
"""Real-client CI suites share a GPU, even when parity.py runs harnesses in parallel."""
|
||||
import fcntl
|
||||
with (Path(tempfile.gettempdir()) / 'horizon-integration-gpu.lock').open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def require_server_reports(resources):
|
||||
"""Match Builtin.find: a registry report shadows later fallback directories."""
|
||||
resources = Path(resources)
|
||||
reports = next((p for p in (resources, resources / '../../datagen/out/reports',
|
||||
resources / '../datagen/out/reports')
|
||||
if (p / 'registries.json').is_file()), None)
|
||||
if reports is None or not (reports / 'commands.json').is_file():
|
||||
raise ValueError(f'incomplete prepared resources in {resources}: registries.json and '
|
||||
'commands.json must be installed together; prepare the pinned resources again')
|
||||
return reports
|
||||
+237
-59
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""LAN multiplayer end to end: a host opens its world to LAN and a guest joins, both real games.
|
||||
|
||||
Two Horizon clients run side by side under horizon-ctl, each in its own scratch folder. The host
|
||||
The host uses its integrated server thread by default; --in-frame compares the fallback, and
|
||||
--server-thread remains accepted. Two Horizon clients run under horizon-ctl in scratch folders. The host
|
||||
creates a survival world and opens it to LAN with commands allowed; the guest connects to it by
|
||||
address. The script then checks, from both sides, what a guest's game used to get wrong (#366):
|
||||
|
||||
@@ -272,7 +273,6 @@ import math
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -284,11 +284,12 @@ from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from agent_control_e2e import Cli, Failed, game_env # noqa: E402
|
||||
import lab # noqa: E402
|
||||
from integration_env import game_environment, require_server_reports # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
# The host plays single player on its server thread (--server-thread).
|
||||
SERVER_THREAD = False
|
||||
# Match normal single player; --in-frame is the comparison path.
|
||||
SERVER_THREAD = True
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater']
|
||||
|
||||
|
||||
@@ -302,6 +303,7 @@ class Game:
|
||||
os.symlink(resources, self.work / '.local/horizon-client' / lab.VERSION)
|
||||
self.socket = self.work / 'c.sock'
|
||||
env = game_env(os.environ.get('VSCREEN', 'lan-e2e'), home=self.work / 'home')
|
||||
env = game_environment(env, self.work)
|
||||
self.d = Cli(ctl, self.socket, self.work, env)
|
||||
self.d.name = name
|
||||
|
||||
@@ -327,6 +329,28 @@ class Game:
|
||||
def wait(self, ticks):
|
||||
self.d('wait', ticks=ticks)
|
||||
|
||||
def script(self, lines):
|
||||
"""Keep tick-sensitive input in one ctl process, through the normal control commands."""
|
||||
result = subprocess.run(self.d.base + ['script'], input='\n'.join(lines) + '\n',
|
||||
cwd=self.work, env=self.d.env, capture_output=True, text=True,
|
||||
timeout=600)
|
||||
replies = [json.loads(line) for line in result.stdout.splitlines() if line.strip()]
|
||||
ticks = [r['ticks'] for r in replies if 'ticks' in r]
|
||||
print(f'[{self.name}] script {lines} -> {replies[-1] if replies else result.stderr[:400]}; ticks={ticks}')
|
||||
assert result.returncode == 0 and replies and not any('error' in r for r in replies), result.stdout
|
||||
return replies[-1]
|
||||
|
||||
def until(self, observe, predicate, ticks=100):
|
||||
"""Wait for an observable answer, within the existing tick budget."""
|
||||
last = observe()
|
||||
for _ in range(ticks):
|
||||
if predicate(last):
|
||||
return last
|
||||
self.wait(1)
|
||||
last = observe()
|
||||
assert predicate(last), f'{self.name}: state did not arrive within {ticks} ticks: {last}'
|
||||
return last
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.d('quit')
|
||||
@@ -534,6 +558,8 @@ def check_sign(host, guest, out):
|
||||
host.shot(out, 'sign')
|
||||
assert placed and 'sign' in placed, f'the guest placed {placed}'
|
||||
host_unaffected(host, "the guest's sign")
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.raw('wait-for', 'screen', 'playing')
|
||||
return placed
|
||||
|
||||
|
||||
@@ -678,7 +704,7 @@ def check_levels(host, guest, out):
|
||||
for name, step in LEVEL_STEPS:
|
||||
try:
|
||||
steps[name] = step(host, guest, out)
|
||||
except (Failed, AssertionError, StopIteration, KeyError) as e:
|
||||
except (Failed, AssertionError, StopIteration, KeyError, TypeError, IndexError) as e:
|
||||
steps[name], failed = repr(e), failed + [name]
|
||||
for g in (host, guest):
|
||||
back_to_game(g)
|
||||
@@ -751,10 +777,12 @@ def level_ticking(host, guest, out):
|
||||
has its own id across the levels."""
|
||||
gx, gy, gz = pos_of(guest)
|
||||
hx, hy, hz = pos_of(host)
|
||||
# A floor of its own beside the host (earlier checks may have broken the open one there).
|
||||
bx, by, bz = int(hx // 1), int(hy // 1), int(hz // 1)
|
||||
host('command', command=f'fill {bx - 4} {by - 1} {bz - 4} {bx + 4} {by - 1} {bz - 2} minecraft:stone')
|
||||
host('command', command=f'fill {bx - 4} {by} {bz - 4} {bx + 4} {by + 4} {bz - 2} minecraft:air')
|
||||
# Clear the whole walking area in each level: normal pig AI can leave a
|
||||
# narrow landing strip during the fall/observation window.
|
||||
for game, x, y, z in ((host, hx, hy, hz), (guest, gx, gy, gz)):
|
||||
bx, by, bz = int(x // 1), int(y // 1), int(z // 1)
|
||||
game('command', command=f'fill {bx - 12} {by - 1} {bz - 12} {bx + 12} {by - 1} {bz + 12} minecraft:stone')
|
||||
game('command', command=f'fill {bx - 12} {by} {bz - 12} {bx + 12} {by + 6} {bz + 12} minecraft:air')
|
||||
guest('command', command=f'summon minecraft:pig {gx + 2.5:.2f} {gy + 3:.2f} {gz:.2f}')
|
||||
guest('command', command=f'summon minecraft:armor_stand {gx - 2.5:.2f} {gy + 3:.2f} {gz:.2f}')
|
||||
host('command', command=f'summon minecraft:pig {hx + 2.5:.2f} {hy + 3:.2f} {hz - 3:.2f}')
|
||||
@@ -766,6 +794,7 @@ def level_ticking(host, guest, out):
|
||||
mobs = [m for m in g.raw('mobs', 8)['near'] if m['kind'] == 'minecraft:pig']
|
||||
stands = [o for o in g('status')['objects'] if o['kind'] == 'minecraft:armor_stand']
|
||||
seen[name] = {'pigs': [(m['id'], round(m['pos'][1], 2)) for m in mobs],
|
||||
'pig_positions': [m['pos'] for m in mobs],
|
||||
'stands': [(o['id'], round(o['position'][1], 2)) for o in stands], 'floor': floor}
|
||||
finally:
|
||||
guest('command', command='kill @e[type=!minecraft:player,distance=..8]')
|
||||
@@ -1993,12 +2022,11 @@ def chat_input(game):
|
||||
def complete(guest, text):
|
||||
"""Opens the chat on `/`, types `text` and presses Tab: the input after it."""
|
||||
guest.raw('key', 'slash', 'tap')
|
||||
guest.wait(3)
|
||||
guest.until(lambda: guest('screen').get('screen'), lambda s: s == 'chat', ticks=3)
|
||||
guest.raw('type', text)
|
||||
guest.wait(2)
|
||||
guest.until(lambda: guest('screen').get('chat_suggestions'), bool, ticks=2)
|
||||
guest.raw('key', 'tab', 'tap')
|
||||
guest.wait(2)
|
||||
return chat_input(guest)
|
||||
return guest.until(lambda: chat_input(guest), lambda value: value != '/' + text, ticks=2)
|
||||
|
||||
|
||||
def check_commands(host, guest, out):
|
||||
@@ -2408,7 +2436,8 @@ def check_predict(host, guest, out):
|
||||
seen = {}
|
||||
creaks = lambda game: sum(n for s, n in game('status')['heard'].items() if 'door' in s)
|
||||
heard = {'guest': creaks(guest), 'host': creaks(host)}
|
||||
os.kill(host.pid, signal.SIGSTOP)
|
||||
host.raw('server-hold', 'on')
|
||||
held_at = host.raw('simulation')['game_time']
|
||||
try:
|
||||
guest.raw('interact', *wood)
|
||||
seen['guest_frozen'] = (state(guest, wood), state(guest, (wood[0], wood[1] + 1, wood[2])))
|
||||
@@ -2416,8 +2445,9 @@ def check_predict(host, guest, out):
|
||||
seen['guest_heard_frozen'] = creaks(guest) - heard['guest']
|
||||
guest.raw('interact', *iron)
|
||||
seen['guest_iron_frozen'] = state(guest, iron)
|
||||
assert host.raw('simulation')['game_time'] == held_at, 'server barrier advanced the world'
|
||||
finally:
|
||||
os.kill(host.pid, signal.SIGCONT)
|
||||
host.raw('server-hold', 'off')
|
||||
guest.wait(20)
|
||||
seen['guest_after'] = state(guest, wood)
|
||||
seen['host_after'] = state(host, wood)
|
||||
@@ -2529,7 +2559,11 @@ def check_swings(host, guest, out):
|
||||
guest.wait(10)
|
||||
guest.raw('select', 'minecraft:wooden_hoe')
|
||||
before = guest('state')['swings']
|
||||
guest.raw('interact', *soil)
|
||||
guest.raw('look-at', soil[0] + 0.5, soil[1] + 1, soil[2] + 0.5)
|
||||
guest.wait(1)
|
||||
target = guest('state')['looking_at']['block']
|
||||
assert target and target['pos'] == list(soil) and target['face'] == 'up', target
|
||||
guest.raw('mouse', 'right', 'click')
|
||||
guest.wait(10)
|
||||
hoe = {'swings': guest('state')['swings'] - before, 'soil': host.raw('block', *soil)['block']}
|
||||
guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:stone')
|
||||
@@ -2636,16 +2670,22 @@ def check_xp(host, guest, out):
|
||||
x, y, z = pos_of(guest)
|
||||
# Three orbs of 7 points 4 blocks east of the guest (out of reach, within the 8 blocks orbs
|
||||
# follow from): they fly to the guest.
|
||||
# Freeze setup so command/IPC latency cannot let all three be collected
|
||||
# before the two-tick in-flight observation.
|
||||
host('command', command='tick freeze')
|
||||
for _ in range(3):
|
||||
guest('command', command=f'summon minecraft:experience_orb {x + 4:.2f} {y + 0.5:.2f} {z:.2f} {{Value:7s}}')
|
||||
host('command', command='tick step 2')
|
||||
guest.wait(2)
|
||||
seen = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0)
|
||||
guest.shot(out, 'xp-orbs')
|
||||
host('command', command='tick unfreeze')
|
||||
guest.wait(60)
|
||||
xp = guest('state')['player']['xp']
|
||||
host_xp = host('state')['player']['xp']
|
||||
left = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0)
|
||||
finally:
|
||||
host('command', command='tick unfreeze')
|
||||
host('command', command='gamemode survival')
|
||||
# Back where it stood: a spectator sinks (Player.travel keeps 0.6 of its fall speed each tick,
|
||||
# about 0.2 blocks from standing), and a later check that makes it survival again would land
|
||||
@@ -2671,9 +2711,7 @@ def check_time(host, guest, out):
|
||||
guest.wait(20)
|
||||
# A stalled game runs at most 10 missed ticks when it wakes (DeltaTracker); the server's
|
||||
# game time, sent every second, moves the guest's clock on (ClientClockManager.tick).
|
||||
os.kill(guest.pid, signal.SIGSTOP)
|
||||
time.sleep(4)
|
||||
os.kill(guest.pid, signal.SIGCONT)
|
||||
guest.raw('stall', 4000)
|
||||
guest.wait(60)
|
||||
stalled = times()
|
||||
detail = {'paused': paused, 'after_stall': stalled}
|
||||
@@ -3126,12 +3164,10 @@ def same_light(host, guest, lo, hi, what, ticks=100):
|
||||
def check_flight(host, guest, out):
|
||||
def double_jump(game):
|
||||
# LocalPlayer.aiStep: a second jump press within 7 ticks of the first toggles flight.
|
||||
lines = []
|
||||
for hold in (1, 4):
|
||||
game.raw('key', 'space', 'down')
|
||||
game.wait(hold)
|
||||
game.raw('key', 'space', 'up')
|
||||
game.wait(2)
|
||||
game.wait(10)
|
||||
lines += ['key space down', f'wait {hold}', 'key space up', 'wait 2']
|
||||
game.script(lines + ['wait 10'])
|
||||
return game('state')['player']
|
||||
|
||||
def set_mode(game, mode):
|
||||
@@ -3146,6 +3182,9 @@ def check_flight(host, guest, out):
|
||||
|
||||
players = [('guest', guest)] + ([('host', host)] if SERVER_THREAD else [])
|
||||
seen = {}
|
||||
# The rule is seven simulation ticks, independent of wall time. A slow
|
||||
# server clock leaves enough time to deliver the key events even on busy CI.
|
||||
host('command', command='tick rate 4')
|
||||
try:
|
||||
for name, game in players:
|
||||
set_mode(game, 'creative')
|
||||
@@ -3159,6 +3198,7 @@ def check_flight(host, guest, out):
|
||||
'stayed': round(later['position'][1] - up['position'][1], 2),
|
||||
'survival_flying': fell['flying']}
|
||||
finally:
|
||||
host('command', command='tick rate 20')
|
||||
for _, game in players:
|
||||
game('command', command='gamemode survival')
|
||||
for name, s in seen.items():
|
||||
@@ -3673,15 +3713,16 @@ def leave_vehicle(player, kind):
|
||||
|
||||
def break_vehicle(player, vehicle_id, kind):
|
||||
"""Hit it with fists until it breaks: VehicleEntity.tick takes 1 off its damage every tick."""
|
||||
for _ in range(10):
|
||||
here = [o for o in player('status')['objects'] if o['id'] == vehicle_id]
|
||||
if not here:
|
||||
return
|
||||
vp = here[0]['position']
|
||||
player.raw('look-at', f'{vp[0]:.2f}', f'{vp[1] + 0.3:.2f}', f'{vp[2]:.2f}')
|
||||
player.raw('mouse', 'left', 'click')
|
||||
player.wait(2)
|
||||
raise AssertionError(f'ten hits left the {kind} in place')
|
||||
here = [o for o in player('status')['objects'] if o['id'] == vehicle_id]
|
||||
if not here:
|
||||
return
|
||||
vp = here[0]['position']
|
||||
# Keep the original ten hits/two-tick spacing in one connection. Starting
|
||||
# several ctl processes per hit lets the vehicle's damage decay between hits.
|
||||
player.script([f'look-at {vp[0]:.2f} {vp[1] + 0.3:.2f} {vp[2]:.2f}',
|
||||
*[line for _ in range(10) for line in ('mouse left click', 'wait 2')]])
|
||||
assert not any(o['id'] == vehicle_id for o in player('status')['objects']), \
|
||||
f'ten hits left the {kind} in place'
|
||||
|
||||
|
||||
def check_boats(host, guest, out):
|
||||
@@ -4338,10 +4379,8 @@ def check_deflect(host, guest, out):
|
||||
(Player.attack: AIM_DEFLECT on #redirectable_projectile; Ghast.isReflectedFireball). The ghast is caged
|
||||
(a window toward the host); the game runs at 4 ticks a second, and once the fireball is within 4.5 blocks
|
||||
the host looks at the ghast and clicks."""
|
||||
if SERVER_THREAD:
|
||||
# The fireball's position and the host's hurts are read from the host's own level.
|
||||
return 'skipped (in-frame only)'
|
||||
x, y, z = (int(v // 1) for v in pos_of(host))
|
||||
back = pos_of(host)
|
||||
x, y, z = (int(v // 1) for v in back)
|
||||
guest('command', command='gamemode creative')
|
||||
host('command', command='gamemode survival')
|
||||
host('command', command='difficulty normal')
|
||||
@@ -4362,23 +4401,36 @@ def check_deflect(host, guest, out):
|
||||
try:
|
||||
deadline = time.monotonic() + 120
|
||||
while time.monotonic() < deadline:
|
||||
balls = [q for q in host.raw('status')['projectiles'] if q['kind'] == 'LargeFireball']
|
||||
# Aim and click at the projectile the client actually sees. Holding
|
||||
# non-player simulation keeps the reach window open while ordinary
|
||||
# player input and its attack packet cross the connection.
|
||||
balls = [q for q in host('status')['projectiles'] if q['kind'] == 'LargeFireball']
|
||||
near = min((math.dist(q['position'], eye) for q in balls), default=None)
|
||||
if near is not None and near < 4.5:
|
||||
ball = min(balls, key=lambda q: math.dist(q['position'], eye))
|
||||
host('command', command='tick freeze')
|
||||
held_tick = host.raw('simulation')['game_time']
|
||||
g = [m['pos'] for m in host.raw('mobs', 60).get('near', []) if m['kind'].endswith('ghast')][0]
|
||||
host.raw('look-at', f'{g[0]:.2f}', f'{g[1] + 2:.2f}', f'{g[2]:.2f}')
|
||||
host.raw('mouse', 'left', 'down')
|
||||
host.raw('mouse', 'left', 'up')
|
||||
host.script([f'look-at {g[0]:.2f} {g[1] + 2:.2f} {g[2]:.2f}',
|
||||
'wait 1', 'mouse left click', 'wait 1'])
|
||||
host.until(lambda: host.raw('simulation')['projectiles'],
|
||||
lambda qs: any(q.get('id') == ball['id'] and q.get('player_owned') for q in qs),
|
||||
ticks=60)
|
||||
assert host.raw('simulation')['game_time'] == held_tick, 'the deflection barrier advanced simulation'
|
||||
host('command', command='tick unfreeze')
|
||||
turned = near
|
||||
break
|
||||
host('command', command='tick rate 20')
|
||||
host.wait(60)
|
||||
ghast = [m for m in host.raw('mobs', 60).get('near', []) if m['kind'].endswith('ghast') and m['health'] > 0]
|
||||
hurt = [h for pl in host.raw('hurtlog')['players'] if pl['name'] == 'host' for h in pl['hurts']
|
||||
hurt = [h for pl in host.raw('hurtlog')['players'] if pl['name'] == (host.player if SERVER_THREAD else 'host') for h in pl['hurts']
|
||||
if 'fireball' in h['source'] or 'explosion' in h['source']]
|
||||
finally:
|
||||
host('command', command='tick unfreeze')
|
||||
host('command', command='tick rate 20')
|
||||
host('command', command='kill @e[type=minecraft:ghast]')
|
||||
host('command', command=f'tp @s {back[0]} {back[1]} {back[2]}')
|
||||
host.until(lambda: pos_of(host), lambda p: math.dist(p, back) < 0.1)
|
||||
host('command', command=f'fill {gx - 3} {gy - 1} {gz - 3} {gx + 24} {gy + 8} {gz + 3} minecraft:air')
|
||||
guest('command', command='gamemode survival')
|
||||
assert turned is not None, f'no fireball came within 4.5 blocks (nearest {near})'
|
||||
@@ -4564,8 +4616,22 @@ def run(ctl, out, resources, checks):
|
||||
guest.shot(out, 'joined')
|
||||
for name in checks:
|
||||
try:
|
||||
results[name] = {'pass': True, 'detail': CHECK_FNS[name](host, guest, out)}
|
||||
except (Failed, AssertionError, StopIteration, KeyError) as e:
|
||||
# Cases assert their own deaths, menus and held actions before returning.
|
||||
# Do not let those states turn later independent cases into false failures.
|
||||
for game in (host, guest):
|
||||
game.raw('release')
|
||||
back_to_game(game)
|
||||
state = game('state')
|
||||
assert state.get('player') is not None, f'{game.name} lost its session before {name}: {state}'
|
||||
if state.get('screen') == 'dead' or state['player']['health'] <= 0:
|
||||
game.raw('respawn')
|
||||
game.until(lambda: game('state'),
|
||||
lambda s: s.get('screen') == 'playing' and s['player']['health'] > 0,
|
||||
ticks=40)
|
||||
detail = CHECK_FNS[name](host, guest, out)
|
||||
skipped = isinstance(detail, str) and detail.startswith('skipped')
|
||||
results[name] = {'pass': not skipped, 'skipped': skipped, 'detail': detail}
|
||||
except (Failed, AssertionError, StopIteration, KeyError, TypeError, IndexError) as e:
|
||||
results[name] = {'pass': False, 'detail': repr(e)}
|
||||
for g in (host, guest):
|
||||
back_to_game(g)
|
||||
@@ -4584,14 +4650,19 @@ def main():
|
||||
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
|
||||
parser.add_argument('--check', action='append', choices=CHECKS, help='run only these checks (repeatable)')
|
||||
parser.add_argument('--out', default=str(ROOT / '.local/lan-e2e'), help='screenshots and game logs go here')
|
||||
parser.add_argument('--server-thread', action='store_true', help="the host's world runs on its server thread")
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument('--server-thread', dest='server_thread', action='store_true', default=True,
|
||||
help='host on its server thread (default; retained for existing callers)')
|
||||
mode.add_argument('--in-frame', dest='server_thread', action='store_false',
|
||||
help='host the world in the window, for comparison')
|
||||
args = parser.parse_args()
|
||||
global SERVER_THREAD
|
||||
SERVER_THREAD = args.server_thread
|
||||
if args.bin_dir:
|
||||
bins = Path(args.bin_dir).resolve()
|
||||
else:
|
||||
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'],
|
||||
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client',
|
||||
'--bin', 'horizon-client', '--bin', 'horizon-ctl'],
|
||||
cwd=ROOT, check=True)
|
||||
meta = json.loads(subprocess.run(['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=ROOT,
|
||||
capture_output=True, text=True, check=True).stdout)
|
||||
@@ -4599,9 +4670,16 @@ def main():
|
||||
resources = lab.RESOURCES.resolve()
|
||||
if not (resources / 'horizon-resources.json').exists():
|
||||
sys.exit(f'no prepared resources in {resources}')
|
||||
out = Path(args.out)
|
||||
try:
|
||||
require_server_reports(resources)
|
||||
except ValueError as error:
|
||||
sys.exit(str(error))
|
||||
out = Path(args.out).resolve()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
print(f'LAN host mode: {"server-thread" if SERVER_THREAD else "in-frame"}')
|
||||
results = run(bins / 'horizon-ctl', out, resources, args.check or CHECKS)
|
||||
(out / 'results.json').write_text(json.dumps({'mode': 'server-thread' if SERVER_THREAD else 'in-frame',
|
||||
'checks': results}, indent=2) + '\n')
|
||||
print(json.dumps(results, indent=1))
|
||||
sys.exit(0 if results and all(r['pass'] for r in results.values()) else 1)
|
||||
|
||||
@@ -4658,16 +4736,33 @@ def check_keep_inventory(host, guest, out):
|
||||
neither; with it on, nothing drops and it respawns with both (#1284)."""
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
seen = {}
|
||||
# Totem coverage leaves both players near one health. Protect the waiting
|
||||
# player from residual fire/damage while the other player's death is tested.
|
||||
for game in (host, guest):
|
||||
game('command', command='gamemode creative')
|
||||
game('command', command='effect clear @s')
|
||||
game('command', command='effect give @s minecraft:instant_health 1 5 true')
|
||||
host('command', command=f'setworldspawn {hx} {hy} {hz}')
|
||||
host('command', command='gamerule respawn_radius 0')
|
||||
# Keep the inactive player alive and away from the death drops. Earlier
|
||||
# fixtures may leave a personal respawn point or an unsafe waiting position.
|
||||
host('command', command=f'fill {hx - 6} {hy - 1} {hz - 6} {hx + 6} {hy - 1} {hz + 6} minecraft:stone')
|
||||
host('command', command=f'fill {hx - 6} {hy} {hz - 6} {hx + 6} {hy + 3} {hz + 6} minecraft:air')
|
||||
for game, dz in ((host, -3), (guest, 3)):
|
||||
waiting = (hx - 3.5, hy, hz + dz + 0.5)
|
||||
game('command', command=f'spawnpoint @s {hx} {hy} {hz}')
|
||||
game('command', command=f'tp @s {waiting[0]} {waiting[1]} {waiting[2]}')
|
||||
game.until(lambda: pos_of(game), lambda p: math.dist(p, waiting) < 0.1)
|
||||
try:
|
||||
for keep in ('false', 'true'):
|
||||
host('command', command=f'gamerule keep_inventory {keep}')
|
||||
for game, dz in ((host, -3), (guest, 3)):
|
||||
# 14 blocks from the world spawn: nothing dropped is picked up on respawning.
|
||||
x, z = hx + 14, hz + dz
|
||||
host('command', command=f'fill {x - 2} {hy - 1} {z - 1} {x + 2} {hy - 1} {z + 1} minecraft:stone')
|
||||
host('command', command=f'fill {x - 2} {hy} {z - 1} {x + 2} {hy + 2} {z + 1} minecraft:air')
|
||||
# Death drops scatter several blocks before landing. Keep the
|
||||
# entire observation area solid so they cannot fall off a ledge.
|
||||
host('command', command=f'fill {x - 6} {hy - 1} {z - 6} {x + 6} {hy - 1} {z + 6} minecraft:stone')
|
||||
host('command', command=f'fill {x - 6} {hy} {z - 6} {x + 6} {hy + 3} {z + 6} minecraft:air')
|
||||
host('command', command='kill @e[type=minecraft:item]')
|
||||
game('command', command='gamemode survival')
|
||||
game('command', command='clear @s')
|
||||
@@ -4675,8 +4770,10 @@ def check_keep_inventory(host, guest, out):
|
||||
game('command', command='item replace entity @s armor.head with minecraft:iron_helmet')
|
||||
game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5}')
|
||||
game.wait(20)
|
||||
assert game('state').get('screen') == 'playing', f'{game.name} died during setup'
|
||||
game('command', command='kill @s')
|
||||
game.wait(30)
|
||||
assert game('state').get('screen') == 'dead', f'{game.name} did not die'
|
||||
dropped = sorted((e['item']['item'], e['item']['count'])
|
||||
for e in game.raw('entities', 8, 'minecraft:item')['entities'])
|
||||
game.shot(out, f'keepinv-{keep}')
|
||||
@@ -4686,12 +4783,14 @@ def check_keep_inventory(host, guest, out):
|
||||
seen[f'{game.name}-keep-{keep}'] = {
|
||||
'dropped': dropped,
|
||||
'kept': {item: server_count(game, item) for item in ('diamond', 'iron_helmet')}}
|
||||
game('command', command='gamemode creative')
|
||||
finally:
|
||||
host('command', command='gamerule keep_inventory false')
|
||||
host('command', command='gamerule respawn_radius 10')
|
||||
host('command', command='kill @e[type=minecraft:item]')
|
||||
for game in (host, guest):
|
||||
game('command', command='clear @s')
|
||||
game('command', command='gamemode survival')
|
||||
face_each_other(host, guest)
|
||||
for case, s in seen.items():
|
||||
want = ({'dropped': [], 'kept': {'diamond': 7, 'iron_helmet': 1}} if case.endswith('true') else
|
||||
@@ -4709,6 +4808,16 @@ def check_signs(host, guest, out):
|
||||
seen = {}
|
||||
for game, other, dz in ((host, guest, -2), (guest, host, 2)):
|
||||
spot = (hx + 2, hy, hz + dz)
|
||||
for viewer in (game, other):
|
||||
back_to_game(viewer)
|
||||
# Earlier death/travel checks leave the players at different spawn points.
|
||||
# Give this placement case its own floor, line of sight and reachable target.
|
||||
host('command', command=f'fill {spot[0] - 3} {hy - 1} {spot[2] - 1} {spot[0] + 3} {hy - 1} {spot[2] + 1} minecraft:stone')
|
||||
host('command', command=f'fill {spot[0] - 3} {hy} {spot[2] - 1} {spot[0] + 3} {hy + 3} {spot[2] + 1} minecraft:air')
|
||||
for viewer, dx in ((game, -2), (other, 2)):
|
||||
at = (spot[0] + dx + 0.5, hy, spot[2] + 0.5)
|
||||
viewer('command', command=f'tp @s {at[0]} {at[1]} {at[2]}')
|
||||
viewer.until(lambda: pos_of(viewer), lambda p: math.dist(p, at) < 0.1)
|
||||
game('command', command=f'setblock {spot[0]} {spot[1] - 1} {spot[2]} minecraft:stone')
|
||||
game('command', command=f'setblock {spot[0]} {spot[1]} {spot[2]} minecraft:air')
|
||||
game('command', command='gamemode survival')
|
||||
@@ -4716,7 +4825,12 @@ def check_signs(host, guest, out):
|
||||
game('command', command='give @s minecraft:oak_sign 1')
|
||||
game.wait(10)
|
||||
game.raw('place', *spot, '--item', 'minecraft:oak_sign')
|
||||
game.wait(10)
|
||||
game.until(lambda: game('state').get('screen'), lambda s: s == 'sign', ticks=10)
|
||||
# Drain the placement's initial block-entity data before typing. The
|
||||
# reply travels on the same connection after that data, unlike a local
|
||||
# screen check which may see the editor before the initial data arrives.
|
||||
server_reply(game, f'data get block {spot[0]} {spot[1]} {spot[2]} front_text.messages',
|
||||
'following block data')
|
||||
opened = {g.name: g('state').get('screen') for g in (game, other)}
|
||||
game.shot(out, 'signs-editor')
|
||||
lines = [f'{game.name} wrote', 'line two']
|
||||
@@ -4724,11 +4838,13 @@ def check_signs(host, guest, out):
|
||||
game.raw('key', 'enter', 'tap')
|
||||
game.raw('type', lines[1])
|
||||
game.raw('key', 'esc', 'tap')
|
||||
game.wait(20)
|
||||
game.until(lambda: game('state').get('screen'), lambda s: s == 'playing', ticks=20)
|
||||
back_to_game(other)
|
||||
shown = {g.name: g.until(lambda: (g.raw('block', *spot).get('sign') or {}).get('front'),
|
||||
lambda front: front == lines + ['', ''], ticks=20)
|
||||
for g in (game, other)}
|
||||
seen[game.name] = {'opened': opened,
|
||||
'shown': {g.name: (g.raw('block', *spot).get('sign') or {}).get('front')
|
||||
for g in (game, other)}}
|
||||
'shown': shown}
|
||||
other.shot(out, 'signs-shown')
|
||||
for name, s in seen.items():
|
||||
other = 'guest' if name == 'host' else 'host'
|
||||
@@ -5079,8 +5195,12 @@ def check_fishing(host, guest, out):
|
||||
tracked to the clients as a fishing bobber under its owner), lands on the ground and reels back
|
||||
in; cast into open water with Lure III, a fish bites and reeling in
|
||||
during the bite catches it for 1 (#1348)."""
|
||||
# Both players need a safe floor for the entire other player's fishing wait.
|
||||
apart(host, guest)
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
host('command', command='weather clear')
|
||||
for game in (host, guest):
|
||||
game('command', command='effect give @s minecraft:instant_health 1 5 true')
|
||||
seen = {}
|
||||
try:
|
||||
for game, other, dz in ((host, guest, -5), (guest, host, 5)):
|
||||
@@ -5396,12 +5516,8 @@ def check_digging(host, guest, out):
|
||||
before = heard('minecraft:block.stone.break')
|
||||
guest.raw('look-at', *at(stone))
|
||||
guest.raw('mouse', 'left', 'down')
|
||||
time.sleep(0.4)
|
||||
os.kill(guest.pid, signal.SIGSTOP)
|
||||
try:
|
||||
time.sleep(1.0)
|
||||
finally:
|
||||
os.kill(guest.pid, signal.SIGCONT)
|
||||
guest.wait(8)
|
||||
guest.raw('stall', 1000)
|
||||
resumed = {'guest': guest.raw('block', *stone).get('block'), 'server': host.raw('block', *stone).get('block'),
|
||||
'mining': guest('state').get('mining')}
|
||||
# Let go once it breaks: past it the crosshair reaches the floor.
|
||||
@@ -5597,6 +5713,68 @@ CHECKS += ['knockback']
|
||||
CHECK_FNS.update(knockback=check_knockback)
|
||||
|
||||
|
||||
|
||||
def check_fixture_input(host, guest, out, kind, role):
|
||||
"""Complement seeded rules with real client input and authoritative observations."""
|
||||
player = host if role == 'host' else guest
|
||||
hx, y, hz = (int(v // 1) for v in pos_of(host))
|
||||
x, z = hx + 6, hz + (-8 if role == 'host' else 8)
|
||||
sensor, dispenser, button = (x + 3, y, z + 1), (x, y, z + 3), (x, y, z + 2)
|
||||
player('command', command='gamemode survival')
|
||||
player('command', command='item replace entity @s weapon.mainhand with minecraft:air')
|
||||
host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 5} {y - 1} {z + 5} minecraft:stone')
|
||||
host('command', command=f'fill {x - 2} {y} {z - 2} {x + 5} {y + 3} {z + 5} minecraft:air')
|
||||
start = (x + 0.5, y, z + 0.5)
|
||||
player('command', command=f'tp @s {start[0]} {start[1]} {start[2]} 0 0')
|
||||
player.until(lambda: pos_of(player), lambda p: math.dist(p, start) < 0.1)
|
||||
player.raw('look', 0, 0)
|
||||
try:
|
||||
if kind == 'sculk':
|
||||
player.wait(2) # finish setup movement before installing the listener
|
||||
host.raw('setblock', *sensor, 'minecraft:sculk_sensor')
|
||||
phase = lambda: host.raw('getblock', *sensor)['block']
|
||||
host.until(phase, lambda state: 'sculk_sensor_phase=inactive' in state)
|
||||
player.wait(10)
|
||||
assert 'sculk_sensor_phase=inactive' in phase(), 'setup activated the sensor before player input'
|
||||
player.raw('key', 'w', 'down')
|
||||
try:
|
||||
player.wait(15) # defined input duration; no wall-clock simulation sleep
|
||||
finally:
|
||||
player.raw('key', 'w', 'up')
|
||||
moved = {'client': math.dist(pos_of(player), start),
|
||||
'server': math.dist(server_player(host, player)['position'], start)}
|
||||
assert all(d > 1 for d in moved.values()), f'{role} did not walk on both sides: {moved}'
|
||||
active = host.until(phase, lambda state: 'sculk_sensor_phase=active' in state, ticks=85)
|
||||
for viewer in (host, guest):
|
||||
viewer.until(lambda: state_of(viewer, sensor, 'sculk_sensor_phase'), lambda v: v == 'active')
|
||||
return {'moved': moved, 'phase': active}
|
||||
host.raw('setblock', *dispenser, 'minecraft:dispenser[facing=east]')
|
||||
host.raw('container', *dispenser, 'minecraft:diamond', 1)
|
||||
host.raw('setblock', *button, 'minecraft:stone_button[face=wall,facing=north]')
|
||||
player.until(lambda: player.raw('block', *button)['block'], lambda v: v == 'minecraft:stone_button')
|
||||
player.raw('interact', *button)
|
||||
slots = host.until(lambda: host.raw('container', *dispenser)['slots'], lambda v: all(s is None for s in v))
|
||||
dropped = {}
|
||||
for viewer in (host, guest):
|
||||
dropped[viewer.name] = viewer.until(
|
||||
lambda: [e for e in viewer.raw('entities', 24, 'minecraft:item')['entities']
|
||||
if e.get('item', {}).get('item') == 'minecraft:diamond'
|
||||
and math.dist(e['pos'], (x + 1.5, y + 0.5, z + 3.5)) < 3],
|
||||
lambda drops: len(drops) == 1 and drops[0]['item']['count'] == 1)
|
||||
player.shot(out, f'{kind}-input')
|
||||
return {'slots': slots, 'drops': dropped}
|
||||
finally:
|
||||
player.raw('key', 'w', 'up')
|
||||
host('command', command=f'fill {x - 2} {y} {z - 2} {x + 5} {y + 3} {z + 5} minecraft:air')
|
||||
|
||||
|
||||
for _kind in ('sculk', 'dispenser'):
|
||||
for _role in ('host', 'guest'):
|
||||
_name = f'{_kind}_input_{_role}'
|
||||
CHECKS.append(_name)
|
||||
CHECK_FNS[_name] = lambda h, g, o, kind=_kind, role=_role: check_fixture_input(h, g, o, kind, role)
|
||||
|
||||
|
||||
def check_hero_trading(host, guest, out):
|
||||
"""Villager.updateSpecialPrices keeps the trading player's Hero effect: the offer sent to the
|
||||
client and the server's payment consumption agree, independently of the other player's effect."""
|
||||
|
||||
@@ -9,13 +9,16 @@ import subprocess
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
from .integration_env import run_game
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
from integration_env import run_game
|
||||
|
||||
|
||||
def run_logged(command, build, name, timeout=900, **kwargs):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
subprocess.run([str(c) for c in command], cwd=lab.ROOT, check=True, timeout=timeout,
|
||||
runner = run_game if Path(command[0]).name == 'horizon-client' else subprocess.run
|
||||
runner([str(c) for c in command], cwd=lab.ROOT, check=True, timeout=timeout,
|
||||
stdout=log, stderr=subprocess.STDOUT, **kwargs)
|
||||
|
||||
|
||||
|
||||
+14
-1
@@ -11,6 +11,9 @@
|
||||
python3 tools/parity.py --list # what would run, without running it
|
||||
python3 tools/parity.py --status # last result of every harness
|
||||
|
||||
Harnesses in parity_hosts.json's "named_only" run only when named or with --all
|
||||
(the nightly audit): no automatic selection picks them.
|
||||
|
||||
Each harness runs unmodified, in parallel, under a tracer that records what it
|
||||
read: its Python modules, Java oracle sources, other repository files, and the
|
||||
Rust sources of every probe it executed (from Cargo's dep-info). A harness
|
||||
@@ -1306,6 +1309,12 @@ def platform_skips(config):
|
||||
return dict(config.get("linux_only", {}))
|
||||
|
||||
|
||||
def named_only(config):
|
||||
"""Harnesses tools/parity_hosts.json keeps out of every automatic selection (--changed, --failed, the default,
|
||||
--flake-check): they run only when named or with --all, the nightly audit. {name: reason}"""
|
||||
return dict(config.get("named_only", {}))
|
||||
|
||||
|
||||
def finished_run(failed):
|
||||
"""Record that this run completed, for tools/gate.py: a crashed runner never writes it."""
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
@@ -1390,9 +1399,13 @@ def main():
|
||||
for name in [name for name in chosen if base_name(name) in skips and not args.names]:
|
||||
print(f"skipped on {sys.platform}: {name}: {skips[base_name(name)]}", flush=True)
|
||||
chosen.remove(name)
|
||||
manual = {} if args.names or args.all else named_only(host_config())
|
||||
for name in [name for name in chosen if base_name(name) in manual]:
|
||||
print(f"not selected (runs when named, and nightly): {name}: {manual[base_name(name)]}", flush=True)
|
||||
chosen.remove(name)
|
||||
rounds = {name: args.repeat for name in chosen} if args.repeat > 1 else {}
|
||||
if args.flake_check:
|
||||
changed = changed_harnesses(found, records, args.flake_check)
|
||||
changed = {name for name in changed_harnesses(found, records, args.flake_check) if base_name(name) not in manual}
|
||||
for name in sorted(changed):
|
||||
# A pass counts for a changed harness only if it held over enough runs.
|
||||
if name not in chosen and records.get(name, {}).get("rounds", 1) < args.flake_rounds:
|
||||
|
||||
@@ -36,5 +36,8 @@
|
||||
"local_only": {
|
||||
"save_roundtrip": "runs the game on a virtual screen (vscreen) with a null ALSA device, or offscreen in the logged-in macOS session"
|
||||
},
|
||||
"linux_only": {}
|
||||
"linux_only": {},
|
||||
"named_only": {
|
||||
"lan_integration": "the whole lan_e2e suite: ~40 min a run on a loaded runner, and single checks flake under load; run it by name, or tools/lan_e2e.py"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,9 +25,11 @@ import sys
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
from .integration_env import run_game
|
||||
from . import command_exec_corpus as corpus_module
|
||||
except ImportError:
|
||||
import lab
|
||||
from integration_env import run_game
|
||||
import test_rust_parity as base
|
||||
import command_exec_corpus as corpus_module
|
||||
|
||||
@@ -55,7 +57,8 @@ def main():
|
||||
|
||||
def run(command, name, **kw):
|
||||
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
|
||||
result = subprocess.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT, **kw)
|
||||
runner = run_game if Path(command[0]).name == 'horizon-client' else subprocess.run
|
||||
result = runner(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT, **kw)
|
||||
if result.returncode:
|
||||
tail = (build / (name + '.log')).read_text(errors='replace')[-3000:]
|
||||
sys.exit(f'{name} failed ({result.returncode}):\n{tail}')
|
||||
|
||||
@@ -65,13 +65,16 @@ import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import tempfile
|
||||
import time
|
||||
import zlib
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as oh, test_rust_parity as base
|
||||
from .integration_env import game_environment, run_game
|
||||
from .lab import free_port # the other server harnesses import it from here
|
||||
except ImportError:
|
||||
from integration_env import game_environment, run_game
|
||||
import lab
|
||||
import oracle_harness as oh
|
||||
import test_rust_parity as base
|
||||
@@ -124,9 +127,11 @@ class Server:
|
||||
self.log_path = directory.parent / f'{log_name}.log'
|
||||
self.log = self.log_path.open('w', encoding='utf-8')
|
||||
self.lines = []
|
||||
self.process = subprocess.Popen(list(map(str, command)), cwd=directory, stdin=subprocess.PIPE,
|
||||
self.scratch = tempfile.TemporaryDirectory(prefix='hz-server-')
|
||||
env = game_environment(os.environ, self.scratch.name)
|
||||
self.process = subprocess.Popen(list(map(str, command)), cwd=directory, env=env, stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||
encoding='utf-8', errors='replace', env=lab.game_env())
|
||||
encoding='utf-8', errors='replace')
|
||||
self.reader = threading.Thread(target=self._read, daemon=True)
|
||||
self.reader.start()
|
||||
|
||||
@@ -163,6 +168,7 @@ class Server:
|
||||
self.process.wait()
|
||||
self.reader.join(timeout=10)
|
||||
self.log.close()
|
||||
self.scratch.cleanup()
|
||||
|
||||
|
||||
def settle(server, ticks=600, timeout=600):
|
||||
@@ -372,7 +378,7 @@ def horizon_client_joins(vanilla_server, binary, world, build, reference):
|
||||
server.wait_for(r'Done \(')
|
||||
env = lab.game_env(HORIZON_NET_REPORT=report)
|
||||
with (build / 'horizon-client-run.log').open('w') as log:
|
||||
subprocess.run([str(c) for c in [binary, '--resources', lab.RESOURCES, '--render-distance', 2,
|
||||
run_game([str(c) for c in [binary, '--resources', lab.RESOURCES, '--render-distance', 2,
|
||||
'--server', f'127.0.0.1:{port}', '--name', PLAYER]],
|
||||
cwd=client_dir, env=env, stdout=log, stderr=subprocess.STDOUT, timeout=300, check=True)
|
||||
server.wait_for(r'left the game', timeout=30)
|
||||
|
||||
@@ -17,7 +17,9 @@ import random
|
||||
import subprocess
|
||||
try:
|
||||
from . import block_update_harness as h, lab, test_rust_parity as base
|
||||
from .integration_env import run_game
|
||||
except ImportError:
|
||||
from integration_env import run_game
|
||||
import block_update_harness as h
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
@@ -349,7 +351,8 @@ def voice(line):
|
||||
|
||||
|
||||
def run(command, **kwargs):
|
||||
done = subprocess.run(command, capture_output=True, text=True, **kwargs)
|
||||
runner = run_game if str(command[0]).endswith('/horizon-client') else subprocess.run
|
||||
done = runner(command, capture_output=True, text=True, **kwargs)
|
||||
if done.returncode:
|
||||
print((done.stdout + done.stderr)[-4000:])
|
||||
raise SystemExit(f'{command[0]} failed')
|
||||
|
||||
@@ -29,6 +29,15 @@ def corpus():
|
||||
if v[k] is not None:v[k]=[bits(n) for n in v[k]]
|
||||
return v
|
||||
def row(ops,player=False,order=(0,1,2)):return dict(ops=ops,player=player,order=order)
|
||||
# Dropped items: the 0.25-wide box is deflated by Entity before scanning.
|
||||
# Cover surface grazing, buoyancy depth, cell boundaries and repeated pushes.
|
||||
for x in [.5, 1.0, 15.99]:
|
||||
for y in [0, .1, .7, 8/9-.1, 8/9-.001, 8/9, 1]:
|
||||
for flow in [(0,0,0),(1,0,0),(-1,0,1),(0,-1,0)]:
|
||||
update=op(bounds=[x-.124,y+.001,.376,x+.124,y+.249,.624],
|
||||
base_y=y,eye=y+.2125,block=[int(x),int(y),0],
|
||||
default=cell(flow=flow))
|
||||
yield row([update,op(mode='apply'),update,op(mode='apply')])
|
||||
values=[-float('inf'),-1,-.0,0,.1,.39999998,.4,.40000004,8/9,1,2,float('inf'),float('nan')]
|
||||
for kind in range(5):
|
||||
for height in values:
|
||||
|
||||
+31
-16
@@ -15,8 +15,9 @@ is off: nothing leaves the machine.
|
||||
|
||||
python3 tools/test_friends.py --client target/fast/horizon-client --relay target/fast/horizon-relay
|
||||
|
||||
`--server-thread` runs the host's world on its integrated server's own
|
||||
thread (the window is a client of it, as Open to LAN publishes it).
|
||||
The host runs on its integrated server thread by default (the window is a
|
||||
client of it). `--in-frame` compares the fallback; `--server-thread` is accepted
|
||||
for compatibility.
|
||||
|
||||
`--role host|guest` runs one side only (two machines, e.g. over a tailnet):
|
||||
the host prints the code, the guest takes it with `--code` (`--relay-url`
|
||||
@@ -36,8 +37,10 @@ import urllib.request
|
||||
|
||||
try:
|
||||
from . import lab
|
||||
from .integration_env import game_environment, require_server_reports
|
||||
except ImportError:
|
||||
import lab
|
||||
from integration_env import game_environment, require_server_reports
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -84,7 +87,7 @@ class Game:
|
||||
prefix = []
|
||||
extra = []
|
||||
# The host's world on its server thread (`--server-thread`), else in the window.
|
||||
server_thread = False
|
||||
server_thread = True
|
||||
|
||||
def __init__(self, client, resources, work, name, env):
|
||||
# Either way explicitly, whatever the game's default.
|
||||
@@ -96,7 +99,8 @@ class Game:
|
||||
self.process = subprocess.Popen(Game.prefix + [
|
||||
str(client), '--resources', str(resources), '--render-distance', '2', '--test-terrain',
|
||||
'--control-socket', str(self.endpoint), '--timeout-seconds', '600',
|
||||
] + Game.extra, cwd=self.home, env=lab.game_env(HORIZON_HOME=self.home, **env),
|
||||
] + Game.extra, cwd=self.home,
|
||||
env={**game_environment({**os.environ, **env}, self.home), 'HORIZON_HOME': str(self.home)},
|
||||
stdout=self.log, stderr=subprocess.STDOUT)
|
||||
wait_for(self.endpoint, 'screen', lambda v: v['screen'] == 'title', 120, f'{name} title')
|
||||
|
||||
@@ -149,10 +153,11 @@ def play_together(host, guest, name, round_index):
|
||||
before = guest_pos(host, name)
|
||||
guest('look 0 0')
|
||||
guest('key w down')
|
||||
time.sleep(1.5)
|
||||
guest('key w up')
|
||||
host.wait('lan status', lambda v: math.dist(before, next(g['position'] for g in v['guests'] if g['name'] == name)) > 1.0,
|
||||
20, 'guest movement on the host')
|
||||
try:
|
||||
host.wait('lan status', lambda v: math.dist(before, next(g['position'] for g in v['guests'] if g['name'] == name)) > 1.0,
|
||||
20, 'guest movement on the host')
|
||||
finally:
|
||||
guest('key w up')
|
||||
# The host moves; the guest sees the host's player there.
|
||||
hp = host('status')['player']['position']
|
||||
target = [hp[0] + 3.0, hp[1], hp[2] + 1.0]
|
||||
@@ -179,10 +184,11 @@ def play_together(host, guest, name, round_index):
|
||||
guest.wait('status', lambda v: v['target']['pos'] == block, 10, 'the guest aiming at the block')
|
||||
# Held for a few ticks, as a player clicks (creative breaks at once).
|
||||
guest('mouse left down')
|
||||
time.sleep(0.25)
|
||||
guest('mouse left up')
|
||||
host.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:air', 20,
|
||||
'the guest breaking the block, on the host')
|
||||
try:
|
||||
host.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:air', 20,
|
||||
'the guest breaking the block, on the host')
|
||||
finally:
|
||||
guest('mouse left up')
|
||||
guest.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:air', 20,
|
||||
'the broken block on the guest')
|
||||
|
||||
@@ -250,7 +256,7 @@ def full(args, work):
|
||||
join(guest, code, 'Guest')
|
||||
play_together(host, guest, 'Guest', 1)
|
||||
assert host('friends status')['direct'] == 1, host('friends status')
|
||||
print('code alone: chat, movement and blocks both ways, no server involved')
|
||||
print('code alone: chat, movement and blocks both ways, no relay involved')
|
||||
leave(host, guest, 'Guest')
|
||||
host('friends stop')
|
||||
assert host('friends status')['code'] is None
|
||||
@@ -316,8 +322,8 @@ def one_side(args, work):
|
||||
if args.role == 'host':
|
||||
code = host_world(game)
|
||||
print(f'CODE {code}', flush=True)
|
||||
game.wait('lan status', lambda v: v['guests'], args.wait, 'a guest')
|
||||
game.wait('lan status', lambda v: not v['guests'], args.wait, 'the guest leaving')
|
||||
game.wait('lan status', lambda v: any(g['name'] == 'Remote' for g in v['guests']), args.wait, 'a guest')
|
||||
game.wait('lan status', lambda v: all(g['name'] != 'Remote' for g in v['guests']), args.wait, 'the guest leaving')
|
||||
print(f'host: {game("friends status")}')
|
||||
else:
|
||||
join(game, args.code, 'Remote')
|
||||
@@ -347,16 +353,25 @@ def main():
|
||||
parser.add_argument('--hold', type=float, default=0, help='guest: stay this many seconds before leaving')
|
||||
parser.add_argument('--baseline', action='store_true', help='first run the same checks over plain LAN')
|
||||
parser.add_argument('--offscreen', action='store_true', help='run the games without a window')
|
||||
parser.add_argument('--server-thread', action='store_true', help="the host's world on its server thread")
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument('--server-thread', dest='server_thread', action='store_true', default=True,
|
||||
help='host on its server thread (default; retained for existing callers)')
|
||||
mode.add_argument('--in-frame', dest='server_thread', action='store_false',
|
||||
help='host the world in the window, for comparison')
|
||||
parser.add_argument('--xvfb', action='store_true', help='run the games under xvfb-run (headless Linux)')
|
||||
args = parser.parse_args()
|
||||
Game.prefix = ['xvfb-run', '-a'] if args.xvfb else []
|
||||
Game.extra = ['--offscreen'] if args.offscreen else []
|
||||
Game.server_thread = args.server_thread
|
||||
args.client, args.resources = args.client.resolve(), args.resources.resolve()
|
||||
try:
|
||||
require_server_reports(args.resources)
|
||||
except ValueError as error:
|
||||
parser.error(str(error))
|
||||
# Short: Unix socket paths are limited to about 100 bytes.
|
||||
with tempfile.TemporaryDirectory(prefix='hzf-', dir='/tmp') as directory:
|
||||
work = Path(directory)
|
||||
print(f'Friends host mode: {"server-thread" if Game.server_thread else "in-frame"}')
|
||||
if args.role:
|
||||
return one_side(args, work)
|
||||
assert args.relay, 'give --relay (the relay binary, run locally for the relay half)'
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real clients over LAN, direct invitations and a local relay, with a server-thread host.
|
||||
|
||||
Registered with parity.py so changes to the drivers and the game binary select
|
||||
this integration coverage in CI as well as the deterministic library probes.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import lab
|
||||
import test_friends
|
||||
from integration_env import suite_lock
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client',
|
||||
'-p', 'horizon-relay', '--bin', 'horizon-client', '--bin', 'horizon-ctl',
|
||||
'--bin', 'horizon-relay'], cwd=lab.ROOT, check=True)
|
||||
metadata = json.loads(subprocess.check_output(
|
||||
['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=lab.ROOT, text=True))
|
||||
bins = Path(metadata['target_directory']) / 'fast'
|
||||
sys.argv = [sys.argv[0], '--client', str(bins / 'horizon-client'),
|
||||
'--relay', str(bins / 'horizon-relay'), '--baseline',
|
||||
*(['--offscreen'] if sys.platform == 'darwin' else [])]
|
||||
with suite_lock():
|
||||
# The wrapper only selects binaries; test_friends isolates each game
|
||||
# through integration_env and lab.game_env.
|
||||
test_friends.main()
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Register the real-client LAN suite with parity.py's traced harness selection.
|
||||
|
||||
The assertions live in lan_e2e; this is integration coverage, alongside the
|
||||
fast vanilla differential probes. The host uses the normal server thread.
|
||||
Linux runners need a display (for example xvfb-run -a).
|
||||
"""
|
||||
import lan_e2e
|
||||
from integration_env import suite_lock
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
with suite_lock():
|
||||
lan_e2e.main()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user