Merge main and preserve both HUD regression tests

This commit is contained in:
rdbtCVS
2026-10-15 01:00:00 +01:00
104 changed files with 8194 additions and 753 deletions
+2
View File
@@ -80,6 +80,7 @@ jobs:
name: parity-logs
path: .local/parity-runner/logs/
if-no-files-found: ignore
retention-days: 3
# Horizon never downloads the game. These jobs need a self-hosted Linux runner
# (label horizon-game) holding the maintainer's own copy: the official launcher's
# game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
@@ -541,3 +542,4 @@ jobs:
dist/client-graphics-smoke.json
dist/client-graphics-macos-title.json
dist/client-graphics-macos-world.json
retention-days: 3
+6 -4
View File
@@ -1,7 +1,8 @@
name: launcher
# Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a
# push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme),
# every hour (a release the cooldown held goes out) and by hand, tools/release_train.py decides as for the game.
# every 10 minutes (a release waiting for merges to settle goes out) and by hand, tools/release_train.py decides as
# for the game.
# A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull
# request is labelled feature. The version is given to the build (HORIZON_LAUNCHER_VERSION): no bump commits.
# Never marked latest. Pushes to launcher branches only build. RELEASES_PAUSED=1 stops releases.
@@ -17,7 +18,7 @@ on:
- 'crates/horizon-theme/**'
- '.github/workflows/launcher.yml'
schedule:
- cron: '47 * * * *'
- cron: '7-59/10 * * * *'
workflow_dispatch:
inputs:
dry_run:
@@ -25,7 +26,7 @@ on:
type: boolean
default: true
force:
description: Release even without launcher changes, within the cooldown or while paused
description: Release even without launcher changes, before merges settle or while paused
type: boolean
default: false
@@ -208,7 +209,7 @@ jobs:
with:
name: ${{ matrix.asset }}
path: launcher/out/*
retention-days: 7
retention-days: 3
release:
needs: [decide, build]
@@ -249,3 +250,4 @@ jobs:
with:
name: launcher-release-notes
path: notes/
retention-days: 3
+1 -1
View File
@@ -76,4 +76,4 @@ jobs:
name: nightly-parity-logs
path: .local/parity-runner/logs/
if-no-files-found: ignore
retention-days: 14
retention-days: 7
+9 -7
View File
@@ -1,8 +1,9 @@
name: release
# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every hour (a release
# held by the cooldown goes out without another merge) and by hand, tools/release_train.py decides: a release
# when a pull request merged since the last one changed what players run and that release is 3 hours old, or at
# once for a pull request labelled release-now. RELEASES_PAUSED=1 (repository variable) stops them.
# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides:
# a release when pull requests merged since the last one changed what players run and the newest merged 15 minutes
# ago (the oldest an hour ago, if merges never pause), or at once for a pull request labelled release-now.
# RELEASES_PAUSED=1 (repository variable) stops them.
# Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and
# Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then
# publishes vYYYY.MM.DD[.N] with notes from the merged pull requests.
@@ -14,7 +15,7 @@ on:
types: [completed]
branches: [main]
schedule:
- cron: '17 * * * *'
- cron: '2-59/10 * * * *'
workflow_dispatch:
inputs:
dry_run:
@@ -22,7 +23,7 @@ on:
type: boolean
default: true
force:
description: Release even without player-facing changes, within the cooldown or while paused
description: Release even without player-facing changes, before merges settle or while paused
type: boolean
default: false
permissions:
@@ -180,7 +181,7 @@ jobs:
name: ${{ matrix.asset }}
path: dist/${{ matrix.asset }}
if-no-files-found: error
retention-days: 7
retention-days: 3
publish:
needs: [decide, build]
@@ -221,3 +222,4 @@ jobs:
with:
name: release-notes
path: notes/
retention-days: 3
@@ -21,6 +21,7 @@ fn stack(spec: &str) -> LootStack {
enchantments: Vec::new(),
potion: None,
map: false,
exploration: None,
ominous_amplifier: None,
};
for e in parts {
@@ -0,0 +1,124 @@
//! Compare the read + Value parse stages in BlockFacts::load and Assets::load.
//! Usage: json_load_bench RESOURCE_ROOT [REPETITIONS]; see tools/json_load_fixtures.py.
use serde_json::Value;
use std::{
fs::{self, File},
hint::black_box,
io::BufReader,
path::Path,
time::{Duration, Instant},
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn reader(path: &Path) -> Result<Value> {
Ok(serde_json::from_reader(BufReader::new(File::open(path)?))?)
}
fn slice(path: &Path) -> Result<Value> {
Ok(serde_json::from_slice(&fs::read(path)?)?)
}
fn measure(path: &Path, load: fn(&Path) -> Result<Value>) -> Result<Duration> {
let start = Instant::now();
let value = black_box(load(black_box(path))?);
let elapsed = start.elapsed();
// Value destruction is excluded; the temporary byte buffer is released by slice().
drop(value);
Ok(elapsed)
}
fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let root = args
.next()
.ok_or("usage: json_load_bench ROOT [REPETITIONS]")?;
let repetitions: usize = args.next().map_or(Ok(15), |s| s.parse())?;
if repetitions == 0 {
return Err("REPETITIONS must be positive".into());
}
for name in ["gameplay-facts.json", "facts.json"] {
let path = Path::new(&root).join(name);
// Validate complete parsed trees on the exact files being timed.
assert_eq!(reader(&path)?, slice(&path)?);
for _ in 0..2 {
measure(&path, reader)?;
measure(&path, slice)?;
}
let (mut before, mut after) = (Vec::new(), Vec::new());
for i in 0..repetitions {
// Alternate order to reduce filesystem cache / frequency bias.
if i % 2 == 0 {
before.push(measure(&path, reader)?);
after.push(measure(&path, slice)?);
} else {
after.push(measure(&path, slice)?);
before.push(measure(&path, reader)?);
}
}
before.sort_unstable();
after.sort_unstable();
let median = |samples: &[Duration]| {
(samples[(samples.len() - 1) / 2].as_secs_f64()
+ samples[samples.len() / 2].as_secs_f64())
* 500.0
};
let (before, after) = (median(&before), median(&after));
println!(
"{name}: {} bytes; {repetitions} samples; reader {before:.3} ms; slice {after:.3} ms; {:.2}x",
fs::metadata(&path)?.len(),
before / after
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reader_and_slice_preserve_values_and_error_categories() -> Result<()> {
let path =
std::env::temp_dir().join(format!("horizon-json-load-{}.json", std::process::id()));
let check = || -> Result<()> {
fs::write(
&path,
br#"{"states":[{"id":0,"hardness":-1.5,"name":"escaped\n\u2603","outline":[[0,0,0,1,1,1]],"enabled":true}],"defaults":null}"#,
)?;
assert_eq!(reader(&path)?, slice(&path)?);
for invalid in [
&b"{\"states\":["[..],
&b"{\"states\":tru}"[..],
&b"{} trailing"[..],
&b"{\"name\":\"\xff\"}"[..],
] {
fs::write(&path, invalid)?;
let before = reader(&path).unwrap_err();
let after = slice(&path).unwrap_err();
assert_eq!(
before
.downcast_ref::<serde_json::Error>()
.unwrap()
.classify(),
after
.downcast_ref::<serde_json::Error>()
.unwrap()
.classify()
);
}
fs::remove_file(&path)?;
for load in [reader, slice] {
let error = load(&path).unwrap_err();
assert_eq!(
error.downcast_ref::<std::io::Error>().unwrap().kind(),
std::io::ErrorKind::NotFound
);
}
Ok(())
};
let result = check();
let _ = fs::remove_file(path);
result
}
}
@@ -0,0 +1,205 @@
//! Compare the exact read/deserialize sequences used by the model loaders.
//! Run with `cargo run -p horizon-client --profile fast --example json_readers_bench`.
//! Optional arguments: resource directory, repetitions (default 9).
use serde_json::{Map, Value, json};
use std::{
collections::BTreeMap,
fmt::Debug,
fs::{self, File},
hint::black_box,
io::BufReader,
path::{Path, PathBuf},
time::Instant,
};
type Result<T> = horizon_client::Result<T>;
#[derive(Clone, Copy)]
enum Reader {
File,
Buffered,
Slice,
}
const READERS: [Reader; 3] = [Reader::File, Reader::Buffered, Reader::Slice];
// These match the map types and reader expressions at all three production sites.
macro_rules! reader {
($name:ident, $map:ty) => {
fn $name(path: &Path, reader: Reader) -> Result<$map> {
Ok(match reader {
Reader::File => serde_json::from_reader(File::open(path)?)?,
Reader::Buffered => serde_json::from_reader(BufReader::new(File::open(path)?))?,
Reader::Slice => serde_json::from_slice(&fs::read(path)?)?,
})
}
};
}
reader!(prepare_facts, Map<String, Value>);
reader!(catalog_facts, BTreeMap<String, Value>);
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Result<Self> {
let root =
std::env::temp_dir().join(format!("horizon-json-readers-{}", std::process::id()));
fs::create_dir(&root)?;
Ok(Self(root))
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn fixtures(root: &Path) -> Result<()> {
let states: Vec<_> = (0..56)
.map(|i| {
json!({"facing": (["north", "east", "south", "west"][i % 4]),
"powered": if i / 4 % 2 == 0 { "false" } else { "true" },
"age": (i / 8).to_string()})
})
.collect();
let mut models = Map::new();
let mut render = Map::new();
for i in 0..1024 {
let name = format!("minecraft:fixture_block_{i:04}");
models.insert(
name.clone(),
json!({
"schema": {"facing": {"named": ["north", "east", "south", "west"]},
"powered": {"named": ["false", "true"]}, "age": {"integer": [0, 6]}},
"states": states
}),
);
render.insert(
name,
json!({"rule": "never", "can_occlude": true, "bars_tag": false}),
);
}
fs::write(root.join("model-states.json"), serde_json::to_vec(&models)?)?;
fs::write(
root.join("render-definitions.json"),
serde_json::to_vec(&render)?,
)?;
Ok(())
}
fn benchmark<T: PartialEq + Debug>(
label: &str,
path: &Path,
repetitions: usize,
read: impl Fn(&Path, Reader) -> Result<T>,
) -> Result<()> {
let expected = read(path, Reader::File)?;
for reader in READERS {
assert_eq!(expected, read(path, reader)?);
for _ in 0..2 {
black_box(read(black_box(path), reader)?);
}
}
drop(expected);
let mut samples: [Vec<f64>; 3] = std::array::from_fn(|_| Vec::new());
for repetition in 0..repetitions {
// Rotate reader order to distribute drift across implementations.
for offset in 0..3 {
let index = (repetition + offset) % 3;
let start = Instant::now();
let value = black_box(read(black_box(path), READERS[index])?);
samples[index].push(start.elapsed().as_secs_f64() * 1000.0);
drop(value); // Match the loaders: retain the parsed tree after loading.
}
}
let median: Vec<_> = samples
.iter_mut()
.map(|s| {
s.sort_by(f64::total_cmp);
s[s.len() / 2]
})
.collect();
println!(
"{label}: {} bytes, {repetitions} samples/reader, median ms: File={:.3}, BufReader={:.3}, read+slice={:.3}; slice speedup={:.2}x",
fs::metadata(path)?.len(),
median[0],
median[1],
median[2],
median[0] / median[2]
);
Ok(())
}
fn main() -> Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
let fixture = if args.is_empty() {
Some(Fixture::new()?)
} else {
None
};
let root = fixture
.as_ref()
.map(|f| f.0.clone())
.unwrap_or_else(|| PathBuf::from(&args[0]));
if fixture.is_some() {
fixtures(&root)?;
println!(
"Generated representative fixtures: 1024 blocks, 57344 model states; warm filesystem cache."
);
}
let repetitions = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9);
assert!(repetitions > 0, "repetitions must be positive");
benchmark(
"prepare model states",
&root.join("model-states.json"),
repetitions,
prepare_facts,
)?;
benchmark(
"catalog model states",
&root.join("model-states.json"),
repetitions,
catalog_facts,
)?;
benchmark(
"render definitions",
&root.join("render-definitions.json"),
repetitions,
catalog_facts,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reader_equivalence_and_errors() -> Result<()> {
let fixture = Fixture::new()?;
let path = fixture.0.join("test.json");
fs::write(&path, br#"{"minecraft:stone":{"schema":{},"states":[{}]},"unicode":"\u2603","duplicate":1,"duplicate":2}"#)?;
let expected = prepare_facts(&path, Reader::File)?;
for reader in READERS {
assert_eq!(expected, prepare_facts(&path, reader)?);
assert_eq!(
expected.iter().collect::<BTreeMap<_, _>>(),
catalog_facts(&path, reader)?.iter().collect()
);
}
for invalid in [b"{\"a\": ".as_slice(), b"{} trailing", b"{\"a\":\"\xff\"}"] {
fs::write(&path, invalid)?;
for reader in READERS {
let error = prepare_facts(&path, reader).unwrap_err();
assert!(error.downcast_ref::<serde_json::Error>().is_some());
assert!(catalog_facts(&path, reader).is_err());
}
}
fs::remove_file(&path)?;
for reader in READERS {
let error = prepare_facts(&path, reader).unwrap_err();
assert_eq!(
error.downcast_ref::<std::io::Error>().unwrap().kind(),
std::io::ErrorKind::NotFound
);
}
Ok(())
}
}
+19
View File
@@ -594,6 +594,7 @@ pub fn conditions(v: &Value, ctx: &Entities, w: &dyn World) -> bool {
w,
)
}
"minecraft:match_block" => ctx.block_pos.is_some_and(|b| block(v, b, w)),
"minecraft:block_state_property" => ctx.block_pos.is_some_and(|b| {
let mut pred = serde_json::Map::new();
pred.insert("blocks".into(), v["block"].clone());
@@ -952,6 +953,24 @@ mod tests {
}
}
#[test]
fn bucket_axolotl_block_advancements_require_the_placed_block() {
let ctx = Entities {
this: None,
origin: [0.0; 3],
tool: None,
block_pos: Some([0; 3]),
};
let stone = serde_json::json!({"type":"minecraft:match_block","blocks":"minecraft:stone"});
let wheat = serde_json::json!({"type":"minecraft:match_block","blocks":"minecraft:wheat"});
assert!(conditions(&stone, &ctx, &Flat));
assert!(!conditions(&wheat, &ctx, &Flat));
let absent = Entities {
block_pos: None,
..ctx
};
assert!(!conditions(&stone, &absent, &Flat));
}
#[test]
fn predicates_match_tags_ranges_and_locations() {
let w = Flat;
let stone = ItemView {
+4 -3
View File
@@ -9,7 +9,7 @@ use horizon_world::{
use serde_json::Value;
use std::{
collections::BTreeSet,
fs::File,
fs::{self, File},
io::{self, BufReader},
path::Path,
sync::Arc,
@@ -55,6 +55,7 @@ pub struct Assets {
pub properties: Properties,
pub material_states: [BlockStateId; 6],
pub sprite_size: u32,
pub sprite_minimum_size: u32,
pub pixels: Vec<u8>,
pub texture_layers: u32,
pub model_catalog: crate::models::StateModels,
@@ -97,8 +98,7 @@ impl Assets {
if manifest["data_version"].as_i64() != Some(i64::from(DATA_VERSION)) {
return Err(invalid("resources do not match Horizon's pinned data version").into());
}
let facts: Value =
serde_json::from_reader(BufReader::new(File::open(root.join("facts.json"))?))?;
let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?;
let states = facts["states"]
.as_array()
.ok_or_else(|| invalid("missing registry state facts"))?;
@@ -240,6 +240,7 @@ impl Assets {
properties,
material_states,
sprite_size: sprites.size,
sprite_minimum_size: sprites.minimum_size,
texture_layers: u32::try_from(sprites.layers.len())?,
pixels: sprites.pixels,
model_catalog: models.catalog,
+5
View File
@@ -617,6 +617,11 @@ impl Audio {
let seed = self.random.next_long();
self.play_seeded(event, at, volume, pitch, seed);
}
/// `LivingEntity.handleDamageEvent`'s pitch, `(r - r) * 0.2 + 1`, drawn on the
/// client (the entity's own random there, never the server's world random).
pub fn hurt_pitch(&mut self) -> f32 {
(self.random.next_float() - self.random.next_float()) * 0.2 + 1.0
}
/// `AbstractWidget.playButtonClickSound`: an unseeded, relative UI sound.
pub fn play_button_click(&mut self) {
self.play_instance(
+8 -4
View File
@@ -3,7 +3,13 @@
use crate::Result;
use horizon_world::registry::{BlockRegistry, BlockStateId};
use serde_json::Value;
use std::{collections::HashMap, fs::File, io::BufReader, path::Path, sync::Arc};
use std::{
collections::HashMap,
fs::{self, File},
io::BufReader,
path::Path,
sync::Arc,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RenderShape {
@@ -106,9 +112,7 @@ pub struct BlockFacts {
}
impl BlockFacts {
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
let raw: Value = serde_json::from_reader(BufReader::new(File::open(
root.join("gameplay-facts.json"),
)?))?;
let raw: Value = serde_json::from_slice(&fs::read(root.join("gameplay-facts.json"))?)?;
let entries = raw["states"]
.as_array()
.ok_or("missing gameplay state facts")?;
+4
View File
@@ -283,9 +283,11 @@ impl PlayerEffects {
levitation: self.amplifier("levitation"),
resistance: self.amplifier("resistance"),
fire_resistance: self.get("fire_resistance").is_some(),
dolphins_grace: self.get("dolphins_grace").is_some(),
weaving: self.get("weaving").is_some(),
water_breathing: self.get("water_breathing").is_some()
|| self.get("conduit_power").is_some(),
breath_of_the_nautilus: self.get("breath_of_the_nautilus").is_some(),
protection: Vec::new(),
}
}
@@ -379,9 +381,11 @@ pub struct StatusFlags {
pub levitation: Option<i32>,
pub resistance: Option<i32>,
pub fire_resistance: bool,
pub dolphins_grace: bool,
/// Weaving: cobwebs hold half as much (`WebBlock.entityInside`).
pub weaving: bool,
pub water_breathing: bool,
pub breath_of_the_nautilus: bool,
/// Armor enchantment protection per damage type id (`EnchantmentHelper.getDamageProtection`).
pub protection: Vec<(String, f32)>,
}
+228
View File
@@ -12,6 +12,8 @@ use horizon_world::block_collision::BlockCollisionRegistry;
#[derive(Clone, Debug)]
pub struct ItemEntity {
pub health: i32,
pub fire_ticks: i32,
pub id: u32,
pub stack: ItemStack,
pub position: Vec3,
@@ -22,6 +24,17 @@ pub struct ItemEntity {
pub pickup_delay: u32,
pub bob_offset: f32,
}
/// Environment results needed by the entity owner, including lethal lava damage.
#[derive(Debug)]
pub struct ItemEnvironmentTick {
pub alive: bool,
pub lava_hurt: bool,
}
impl ItemEnvironmentTick {
pub fn should_play_lava_hurt_sound(&self, tick: u32) -> bool {
self.lava_hurt && (!self.alive || tick.is_multiple_of(10))
}
}
impl ItemEntity {
pub const WIDTH: f64 = 0.25;
pub fn bounds(&self) -> Aabb {
@@ -35,6 +48,52 @@ impl ItemEntity {
),
)
}
pub fn environment_tick(
&mut self,
world: &World,
facts: &BlockFacts,
registry: &horizon_world::registry::BlockRegistry,
items: &crate::items::Items,
) -> ItemEnvironmentTick {
let at = world.block(
self.position.x.floor() as i32,
(self.position.y + 0.1).floor() as i32,
self.position.z.floor() as i32,
);
let fluid = facts.get(at).fluid;
let fire_immune = items.resists_fire(&self.stack, "minecraft:in_fire");
if fluid == Fluid::Water || fire_immune {
self.fire_ticks = 0;
}
if self.fire_ticks > 0 {
if self.fire_ticks % 20 == 0
&& fluid != Fluid::Lava
&& !items.resists_fire(&self.stack, "minecraft:on_fire")
{
self.health -= 1;
}
self.fire_ticks -= 1;
}
let mut lava_hurt = false;
if fluid == Fluid::Lava && !fire_immune {
self.fire_ticks = self.fire_ticks.max(300);
if !items.resists_fire(&self.stack, "minecraft:lava") {
self.health -= 4;
lava_hurt = true;
}
}
let fire_damage = crate::motion::environment::fire_contact(world, registry, self.bounds());
if fire_damage > 0.0 && !fire_immune {
self.fire_ticks = self.fire_ticks.max(160);
if !items.resists_fire(&self.stack, "minecraft:in_fire") {
self.health -= fire_damage as i32;
}
}
ItemEnvironmentTick {
alive: self.health > 0,
lava_hurt,
}
}
/// Returns false when the item should be removed.
pub fn tick(
&mut self,
@@ -59,6 +118,12 @@ 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 {
self.velocity = Vec3::new(
self.velocity.x * 0.95,
self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 },
self.velocity.z * 0.95,
);
} else {
self.velocity.y -= 0.04;
}
@@ -359,6 +424,8 @@ impl ItemFrame {
/// An armor stand (`ArmorStand`).
#[derive(Clone, Debug)]
pub struct ArmorStand {
pub fire_ticks: i32,
pub health: f32,
pub id: u32,
pub position: Vec3,
pub velocity: Vec3,
@@ -378,6 +445,8 @@ impl ArmorStand {
pub const SLOTS: [&'static str; 6] = ["mainhand", "offhand", "feet", "legs", "chest", "head"];
pub fn new(id: u32, position: Vec3, yaw: f32) -> Self {
Self {
fire_ticks: 0,
health: 20.0,
id,
position,
velocity: Vec3::ZERO,
@@ -392,6 +461,53 @@ impl ArmorStand {
last_hit: i64::MIN / 2,
}
}
pub fn environment_tick(
&mut self,
world: &World,
facts: &BlockFacts,
registry: &horizon_world::registry::BlockRegistry,
) -> bool {
let (lo, hi) = (self.bounds().min_position(), self.bounds().max_position());
let mut water = false;
let mut lava = false;
for x in lo.x.floor() as i32..=hi.x.floor() as i32 {
for y in lo.y.floor() as i32..hi.y.ceil() as i32 {
for z in lo.z.floor() as i32..=hi.z.floor() as i32 {
match facts.get(world.block(x, y, z)).fluid {
Fluid::Water => water = true,
Fluid::Lava => lava = true,
_ => {}
}
}
}
}
if water {
self.fire_ticks = 0;
}
if self.fire_ticks > 0 {
if self.fire_ticks % 20 == 0
&& !lava
&& !self.invisible
&& !self.marker
&& self.health > 0.5
{
self.health -= 4.0;
}
self.fire_ticks -= 1;
}
if lava {
self.fire_ticks = self.fire_ticks.max(300);
}
let fire = crate::motion::environment::fire_contact(world, registry, self.bounds()) > 0.0;
if fire && !self.invisible && !self.marker {
if self.fire_ticks > 0 {
self.health -= 0.15;
} else {
self.fire_ticks = 100;
}
}
self.health > 0.5
}
/// EntityType.ARMOR_STAND dimensions (0.5 x 1.975, half for small).
pub fn bounds(&self) -> Aabb {
let s = if self.small { 0.5 } else { 1.0 };
@@ -423,3 +539,115 @@ impl ArmorStand {
self.velocity = v;
}
}
#[cfg(test)]
mod fire_environment_tests {
use super::*;
#[test]
fn ordinary_items_burn_but_native_netherite_resists_lava() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("items.json").exists() {
return;
}
let assets = crate::assets::Assets::load(&root).unwrap();
let facts = BlockFacts::load(&root, assets.registry).unwrap();
let items = crate::items::Items::load(&root, assets.registry, &facts).unwrap();
let mut world = World::test_scene(&assets, 3).unwrap();
let at = Vec3::new(20.5, 4.0, 20.5);
world
.set(
20,
4,
20,
assets.registry.default_state("minecraft:lava").unwrap(),
)
.unwrap();
let make = |id: &str| ItemEntity {
id: 1,
stack: ItemStack {
item: std::sync::Arc::from(id),
count: 1,
damage: 0,
extra: None,
},
health: 5,
fire_ticks: 0,
position: at,
previous: at,
velocity: Vec3::ZERO,
on_ground: false,
age: 0,
pickup_delay: 0,
bob_offset: 0.0,
};
let mut wood = make("minecraft:oak_planks");
let mut metal = make("minecraft:netherite_ingot");
let first = wood.environment_tick(&world, &facts, assets.registry, &items);
assert!(first.alive && first.lava_hurt);
assert!(
!first.should_play_lava_hurt_sound(1),
"ordinary entry damage must not repeat the burn sound"
);
assert!(first.should_play_lava_hurt_sound(10));
assert!(
wood.fire_ticks > 0,
"lava contact must ignite dropped items"
);
let last = wood.environment_tick(&world, &facts, assets.registry, &items);
assert!(
!last.alive && last.lava_hurt,
"lethal lava damage still emits burn sound"
);
assert!(
last.should_play_lava_hurt_sound(2),
"the lethal hit must always play the sound"
);
for _ in 0..40 {
let result = metal.environment_tick(&world, &facts, assets.registry, &items);
assert!(result.alive && !result.lava_hurt);
assert!(!result.should_play_lava_hurt_sound(10));
}
assert_eq!(metal.health, 5);
assert_eq!(metal.fire_ticks, 0, "fire-resistant items must not ignite");
world
.set(
20,
4,
20,
assets.registry.default_state("minecraft:fire").unwrap(),
)
.unwrap();
let mut burning = make("minecraft:oak_planks");
let result = burning.environment_tick(&world, &facts, assets.registry, &items);
assert!(result.alive && !result.lava_hurt);
assert!(burning.fire_ticks > 0);
world
.set(
20,
4,
20,
assets
.registry
.default_state("minecraft:soul_fire")
.unwrap(),
)
.unwrap();
let mut soul = make("minecraft:oak_planks");
soul.environment_tick(&world, &facts, assets.registry, &items);
assert_eq!(soul.health, 3);
let mut stand = ArmorStand::new(2, at, 0.0);
world
.set(
20,
4,
20,
assets.registry.default_state("minecraft:lava").unwrap(),
)
.unwrap();
for _ in 0..150 {
assert!(stand.environment_tick(&world, &facts, assets.registry));
}
assert_eq!(stand.health, 20.0, "lava does not hurt armor stands");
}
}
+354 -10
View File
@@ -100,6 +100,11 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
};
let mut tag = base.tag(raw);
for (key, value) in [
(
"Fire",
Tag::Short(m.fire_ticks.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16),
),
("Air", Tag::Short(m.air as i16)),
("Health", Tag::Float(m.health.max(0.0).to_bits())),
(
"HurtTime",
@@ -131,6 +136,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (key, on) in [
("NoAI", m.no_ai),
("Silent", m.silent),
("NoGravity", m.no_gravity),
("Glowing", m.glowing),
("Invulnerable", m.invulnerable_flag),
] {
if on {
@@ -139,6 +146,11 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.remove(&horizon_world::nbt::JavaString::from(key));
}
}
if m.ticks_frozen > 0 {
map.insert("TicksFrozen".into(), Tag::Int(m.ticks_frozen));
} else {
map.remove(&horizon_world::nbt::JavaString::from("TicksFrozen"));
}
for (key, value) in [
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
@@ -324,6 +336,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
crate::mobs::villager::write_nbt(m, map);
}
"minecraft:wandering_trader" => put_offers(map, m),
"minecraft:axolotl" => write_axolotl_memories(m, map),
"minecraft:allay" => {
// InventoryCarrier: the fetched stack; the liked player memory.
let mut inv = Vec::new();
@@ -584,7 +597,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.main_hand = None;
}
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
m.persistent = flag(tag, "PersistenceRequired");
m.persistent |= flag(tag, "PersistenceRequired");
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
m.custom_name = custom_name(tag);
if m.kind.category == "creature" {
@@ -594,9 +607,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
}
m.name_visible = flag(tag, "CustomNameVisible");
m.no_ai = flag(tag, "NoAI");
m.no_gravity = flag(tag, "NoGravity");
m.glowing = flag(tag, "Glowing");
m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32;
m.silent = flag(tag, "Silent");
m.invulnerable_flag = flag(tag, "Invulnerable");
m.no_gravity = m.no_gravity || flag(tag, "NoGravity");
if m.species() == crate::mobs::Species::Creeper {
m.extra.charged = flag(tag, "powered");
// Creeper.readAdditionalSaveData: `ignited` lights the fuse.
@@ -713,6 +728,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
}
crate::mobs::zombie_villager::read_nbt(&mut m, tag);
}
if m.species() == crate::mobs::Species::Axolotl {
restore_axolotl_memories(&mut m, tag);
}
m.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32;
m.air = number(tag.get("Air")).unwrap_or(300) as i32;
if m.species() == crate::mobs::Species::Allay {
if let Some(Tag::List(inv)) = tag.get("Inventory")
&& let Some(first) = inv.first()
@@ -839,6 +859,8 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) ->
let mut tag = base.tag(raw);
for (key, value) in [
("Item", item_to_nbt(&e.stack)),
("Health", Tag::Short(e.health as i16)),
("Fire", Tag::Short(e.fire_ticks as i16)),
("Age", Tag::Short(e.age.min(i16::MAX as u32) as i16)),
(
"PickupDelay",
@@ -847,15 +869,14 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) ->
] {
put(&mut tag, key, value);
}
if let Tag::Compound(map) = &mut tag {
map.entry("Health".into()).or_insert(Tag::Short(5));
}
tag
}
pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option<ItemEntity> {
let stack = item_from_nbt(tag.get("Item")?)?;
let position = position(tag)?;
Some(ItemEntity {
health: number(tag.get("Health")).unwrap_or(5) as i32,
fire_ticks: number(tag.get("Fire")).unwrap_or(0) as i32,
id,
stack,
position,
@@ -1178,11 +1199,8 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) ->
} else if let Tag::Compound(map) = &mut tag {
map.remove(&"Marker".into());
}
if let Tag::Compound(map) = &tag
&& !map.contains_key(&horizon_world::nbt::JavaString::from("Health"))
{
put(&mut tag, "Health", Tag::Float(20f32.to_bits()));
}
put(&mut tag, "Health", Tag::Float(a.health.to_bits()));
put(&mut tag, "Fire", Tag::Short(a.fire_ticks as i16));
// LivingEntity.addAdditionalSaveData and ArmorStand's own fields.
if let Tag::Compound(map) = &mut tag {
for (key, value) in [
@@ -1207,6 +1225,8 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) ->
pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option<ArmorStand> {
let mut a = ArmorStand::new(id, position(tag)?, rotation(tag)[0]);
a.velocity = motion(tag);
a.health = float(tag.get("Health")).unwrap_or(20.0) as f32;
a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32;
if let Some(eq) = tag.get("equipment") {
for (i, slot) in ArmorStand::SLOTS.iter().enumerate() {
a.equipment[i] = eq.get(slot).and_then(item_from_nbt);
@@ -1458,6 +1478,8 @@ mod tests {
#[test]
fn item_entities_round_trip() {
let e = ItemEntity {
health: 2,
fire_ticks: 73,
id: 7,
stack: ItemStack {
item: Arc::from("minecraft:diamond_pickaxe"),
@@ -1478,6 +1500,7 @@ mod tests {
assert_eq!(uuid(&tag), Some([1, 2, 3, 4]));
let back = item_entity_from_nbt(&tag, 9, 0.0).unwrap();
assert_eq!(back.stack.damage, 5);
assert_eq!((back.health, back.fire_ticks), (2, 73));
assert_eq!(
(back.age, back.pickup_delay, back.on_ground),
(120, 10, true)
@@ -1517,3 +1540,324 @@ mod tests {
assert_eq!(back[0].value, 7);
}
}
fn write_axolotl_memories(m: &Mob, map: &mut Compound) {
let brain = map
.entry("Brain".into())
.or_insert_with(|| Tag::Compound(Compound::new()));
if !matches!(brain, Tag::Compound(_)) {
*brain = Tag::Compound(Compound::new());
}
let Tag::Compound(brain) = brain else { return };
let memories = brain
.entry("memories".into())
.or_insert_with(|| Tag::Compound(Compound::new()));
if !matches!(memories, Tag::Compound(_)) {
*memories = Tag::Compound(Compound::new());
}
let Tag::Compound(memories) = memories else {
return;
};
let mm = m.extra.animal_brain.as_deref().map(|b| &b.mem);
let hunting = crate::mobs::animal_brain::hunting_cooldown(m)
.map(|ttl| Tag::compound([("value", Tag::Byte(1)), ("ttl", Tag::Long(ttl))]));
let play_dead = mm
.and_then(|m| m.play_dead_ticks.value())
.map(|v| Tag::compound([("value", Tag::Int(v))]));
let temptation = mm
.and_then(|m| m.temptation_cooldown_ticks.value())
.map(|v| Tag::compound([("value", Tag::Int(v))]));
for (key, value) in [
("minecraft:has_hunting_cooldown", hunting),
("minecraft:play_dead_ticks", play_dead),
("minecraft:temptation_cooldown_ticks", temptation),
] {
if let Some(value) = value {
memories.insert(key.into(), value);
} else {
memories.remove(&key.into());
}
}
}
fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) {
let memories = tag.get("Brain").and_then(|b| b.get("memories"));
let ttl = memories
.and_then(|b| b.get("minecraft:has_hunting_cooldown"))
.and_then(|v| number(v.get("ttl")))
.unwrap_or(0);
crate::mobs::animal_brain::set_hunting_cooldown(m, ttl);
if let Some(b) = m.extra.animal_brain.as_mut() {
if let Some(v) = memories
.and_then(|b| b.get("minecraft:play_dead_ticks"))
.and_then(|v| number(v.get("value")))
{
b.mem.play_dead_ticks.set(v as i32);
}
if let Some(v) = memories
.and_then(|b| b.get("minecraft:temptation_cooldown_ticks"))
.and_then(|v| number(v.get("value")))
{
b.mem.temptation_cooldown_ticks.set(v as i32);
}
}
}
const AXOLOTL_VARIANTS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"];
pub fn bucket_data(m: &Mob) -> Tag {
let mut data = Tag::compound([
("Age", Tag::Int(m.extra.age)),
("AgeLocked", Tag::Byte(i8::from(m.extra.age_locked))),
("Health", Tag::Float(m.health.to_bits())),
]);
for (key, on) in [
("NoAI", m.no_ai),
("Silent", m.silent),
("NoGravity", m.no_gravity),
("Glowing", m.glowing),
("Invulnerable", m.invulnerable_flag),
("PersistenceRequired", m.persistent),
] {
if on {
put(&mut data, key, Tag::Byte(1));
}
}
if let Some(ttl) = crate::mobs::animal_brain::hunting_cooldown(m) {
put(&mut data, "HuntingCooldown", Tag::Long(ttl));
}
data
}
pub fn bucket_components(m: &Mob) -> crate::item_data::StackData {
let mut data = crate::item_data::StackData {
custom_name: m.custom_name.clone(),
..Default::default()
};
data.set_other("minecraft:bucket_entity_data", Some(bucket_data(m)));
if m.species() == crate::mobs::Species::Axolotl {
let variant = AXOLOTL_VARIANTS
.get(usize::from(m.extra.variant))
.unwrap_or(&"lucy");
data.set_other("minecraft:axolotl/variant", Some(string(variant)));
}
data
}
pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
let Some(components) = stack.data() else {
return;
};
if let Some(name) = &components.custom_name {
m.custom_name = Some(name.clone());
}
if let Some(data) = components.other("minecraft:bucket_entity_data") {
if let Some(v) = number(data.get("Age")) {
m.extra.age = v as i32;
}
if let Some(v) = number(data.get("AgeLocked")) {
m.extra.age_locked = v != 0;
}
// Keep old Horizon buckets readable; the modern component below takes precedence.
if let Some(v) = number(data.get("Variant")) {
m.extra.variant = v as u8;
}
if let Some(v) = float(data.get("Health")) {
m.health = v as f32;
}
for (key, flag) in [
("NoAI", &mut m.no_ai),
("Silent", &mut m.silent),
("NoGravity", &mut m.no_gravity),
("Glowing", &mut m.glowing),
("Invulnerable", &mut m.invulnerable_flag),
] {
if let Some(v) = number(data.get(key)) {
*flag = v != 0;
}
}
m.persistent |= flag(data, "PersistenceRequired");
if m.species() == crate::mobs::Species::Axolotl {
crate::mobs::animal_brain::set_hunting_cooldown(
m,
number(data.get("HuntingCooldown")).unwrap_or(0),
);
}
}
if m.species() == crate::mobs::Species::Axolotl
&& let Some(name) = text(components.other("minecraft:axolotl/variant"))
&& let Some(id) = AXOLOTL_VARIANTS
.iter()
.position(|&v| v == name.trim_start_matches("minecraft:"))
{
m.extra.variant = id as u8;
}
}
#[cfg(test)]
mod axolotl_nbt_tests {
use super::*;
#[test]
fn bucket_cooldown_and_brain_memories_survive_and_expired_cooldown_is_removed() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("items.json").exists() {
return;
}
let data = crate::mobs::MobTypes::load(&root).unwrap();
let kind = Arc::new(data.types.get("minecraft:axolotl").unwrap().clone());
let mut m = Mob::new(1, kind.clone(), Vec3::new(0.0, 4.0, 0.0), 0.0);
crate::mobs::animal_brain::set_hunting_cooldown(&mut m, 123);
m.extra.variant = 4;
m.extra.age = -24000;
m.extra.age_locked = true;
m.no_ai = true;
m.silent = true;
m.no_gravity = true;
m.glowing = true;
m.invulnerable_flag = true;
m.persistent = true;
m.custom_name = Some("Bucket friend".into());
m.health = 5.0;
{
let mm = &mut m.extra.animal_brain.as_mut().unwrap().mem;
mm.play_dead_ticks.set(78);
mm.temptation_cooldown_ticks.set(42);
}
let raw = Tag::compound([(
"Brain",
Tag::compound([(
"memories",
Tag::compound([("test:unrelated", Tag::compound([("value", Tag::Int(9))]))]),
)]),
)]);
let tag = mob_to_nbt(&m, [1, 2, 3, 4], Some(&raw));
let memories = tag.get("Brain").unwrap().get("memories").unwrap();
assert!(memories.get("test:unrelated").is_some());
assert_eq!(
number(
memories
.get("minecraft:play_dead_ticks")
.unwrap()
.get("value")
),
Some(78)
);
assert_eq!(
number(
memories
.get("minecraft:temptation_cooldown_ticks")
.unwrap()
.get("value")
),
Some(42)
);
let mut stack = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1);
stack.extra = Some(Box::new(bucket_components(&m)));
assert_eq!(
text(stack.data().unwrap().other("minecraft:axolotl/variant")),
Some("blue".into())
);
assert!(bucket_data(&m).get("Variant").is_none());
let stack = item_from_nbt(&item_to_nbt(&stack)).unwrap();
let mut restored = Mob::new(2, kind, Vec3::new(0.0, 4.0, 0.0), 0.0);
load_bucket_data(&mut restored, &stack);
assert_eq!(
crate::mobs::animal_brain::hunting_cooldown(&restored),
Some(123)
);
assert_eq!(
(
restored.extra.variant,
restored.extra.age,
restored.extra.age_locked
),
(4, -24000, true)
);
assert!(
restored.no_ai
&& restored.silent
&& restored.no_gravity
&& restored.glowing
&& restored.invulnerable_flag
&& restored.persistent
);
assert_eq!(restored.custom_name.as_deref(), Some("Bucket friend"));
assert_eq!(restored.health, 5.0);
m.glowing = false;
m.add_effect("glowing", 200, 0);
assert!(m.has_effect("glowing"));
assert!(bucket_data(&m).get("Glowing").is_none());
m.glowing = true;
assert_eq!(number(bucket_data(&m).get("Glowing")), Some(1));
for (persistent, expected) in [(None, false), (Some(0), false), (Some(1), true)] {
let mut data = Tag::Compound(Compound::new());
if let Some(value) = persistent {
put(&mut data, "PersistenceRequired", Tag::Byte(value));
}
let mut bucket = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1);
bucket
.data_mut()
.set_other("minecraft:bucket_entity_data", Some(data));
restored.persistent = false;
load_bucket_data(&mut restored, &bucket);
assert_eq!(restored.persistent, expected);
restored.persistent = true;
load_bucket_data(&mut restored, &bucket);
assert!(restored.persistent, "bucket data cannot clear persistence");
}
restored.ticks_frozen = 140;
restored.ignite_for_ticks(160);
assert_eq!(restored.ticks_frozen, 0);
restored.ticks_frozen = 140;
restored.ignite_for_ticks(1);
assert_eq!(
restored.ticks_frozen, 0,
"even an ignition that does not extend burning clears freeze"
);
for (id, name) in AXOLOTL_VARIANTS.iter().enumerate() {
let mut vanilla = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1);
vanilla.extra = Some(Box::new(crate::item_data::StackData {
other: vec![("minecraft:axolotl/variant".into(), string(name))],
..Default::default()
}));
load_bucket_data(&mut restored, &vanilla);
assert_eq!(
usize::from(restored.extra.variant),
id,
"component-only vanilla buckets work"
);
}
let mut legacy = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1);
legacy.extra = Some(Box::new(crate::item_data::StackData {
other: vec![(
"minecraft:bucket_entity_data".into(),
Tag::compound([("Variant", Tag::Int(3))]),
)],
..Default::default()
}));
load_bucket_data(&mut restored, &legacy);
assert_eq!(restored.extra.variant, 3);
legacy
.data_mut()
.set_other("minecraft:axolotl/variant", Some(string("gold")));
load_bucket_data(&mut restored, &legacy);
assert_eq!(
restored.extra.variant, 2,
"component wins over old Horizon data"
);
crate::mobs::animal_brain::set_hunting_cooldown(&mut m, 0);
assert!(bucket_data(&m).get("HuntingCooldown").is_none());
let saved = mob_to_nbt(&m, [1, 2, 3, 4], Some(&tag));
assert!(
saved
.get("Brain")
.unwrap()
.get("memories")
.unwrap()
.get("minecraft:has_hunting_cooldown")
.is_none()
);
restore_axolotl_memories(&mut restored, &saved);
let mm = &restored.extra.animal_brain.as_ref().unwrap().mem;
assert_eq!(mm.play_dead_ticks.value(), Some(78));
assert_eq!(mm.temptation_cooldown_ticks.value(), Some(42));
}
}
+106
View File
@@ -0,0 +1,106 @@
//! Animated burning-entity flames; the first-person overlay uses screen_effects.
use crate::{hud::Rect, mesher::Vertex};
use std::collections::HashMap;
#[allow(clippy::too_many_arguments)]
pub fn flames(
position: [f64; 3],
width: f32,
height: f32,
camera: glam::DVec3,
yaw: f32,
sprites: &HashMap<String, Rect>,
scene_light: u8,
out: &mut Vec<Vertex>,
) {
let (Some(a), Some(b)) = (sprites.get("block/fire_0"), sprites.get("block/fire_1")) else {
return;
};
let scale = width * 1.4;
if scale <= 0.0 {
return;
}
let origin = glam::DVec3::from(position) - camera;
let rotation = glam::Mat3::from_rotation_y(std::f32::consts::PI - yaw.to_radians());
let mut remaining = height / scale;
let mut half = 0.5f32;
let mut y = 0.0f32;
let mut z = 0.3 - (remaining as i32) as f32 * 0.02;
let mut index = 0;
while remaining > 0.0 {
let r = if index % 2 == 0 { a } else { b };
let (u0, u1) = if (index / 2) % 2 == 0 {
(r.u0, r.u1)
} else {
(r.u1, r.u0)
};
for (p, uv) in [
([-half, y, z], [u0, r.v1]),
([half, y, z], [u1, r.v1]),
([half, y + 1.4, z], [u1, r.v0]),
([-half, y + 1.4, z], [u0, r.v0]),
] {
let p = origin.as_vec3() + rotation * (glam::Vec3::from(p) * scale);
out.push(Vertex {
pos: p.to_array(),
uv,
layer: 0,
color: 0xffff_ffff,
light: 0xf000 | (u32::from(scene_light >> 4) * 16),
normal: [0; 4],
});
}
remaining -= 0.45;
y += 0.45;
half *= 0.9;
z -= 0.03;
index += 1;
}
}
#[cfg(test)]
mod tests {
#[test]
fn flames_cover_entity_height_and_alternate_animated_sprites() {
let rect = |u0| super::Rect {
u0,
v0: 0.0,
u1: u0 + 0.1,
v1: 0.1,
w: 16,
h: 16,
};
let sprites = super::HashMap::from([
("block/fire_0".into(), rect(0.0)),
("block/fire_1".into(), rect(0.5)),
]);
let mut out = Vec::new();
super::flames(
[0.0; 3],
0.6,
1.8,
glam::DVec3::ZERO,
0.0,
&sprites,
0,
&mut out,
);
assert_eq!(out.len() % 4, 0);
assert!(
out[0].pos[2] < 0.0,
"billboard depth bias must face the camera"
);
assert!(
out.iter().all(|v| v.light == 0xf000),
"fire forces block light to 15 but preserves scene sky light"
);
assert!(out.len() >= 20);
assert!(out.iter().any(|v| v.pos[1] >= 1.8));
assert!(
out.iter().all(|v| v.layer == 0),
"flames must not use the breaking-cracks UV-remap material"
);
assert!(out[..4].iter().all(|v| v.uv[0] <= 0.1));
assert!(out[4..8].iter().all(|v| v.uv[0] >= 0.5));
}
}
+289
View File
@@ -8,6 +8,125 @@
//!
//! What those read and do in the world is behind [`HandWorld`].
/// The ranged item state read by the first-person hand renderer.
#[derive(Clone, Copy, Debug)]
pub enum ItemPose {
Swing,
Using,
Eat {
remaining: f32,
duration: f32,
partial: f32,
},
Trident {
ticks_used: f32,
},
Bow {
ticks_used: f32,
},
Crossbow {
ticks_used: Option<f32>,
charge_duration: f32,
charged: bool,
},
}
/// `submitArmWithItem`: the main-hand item pose, before the model transform.
pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -> glam::Mat4 {
use glam::{Mat4, Vec3};
use horizon_core::geometry::trig::Mth;
let invert = if left { -1.0 } else { 1.0 };
let pi = std::f32::consts::PI;
let mut m = Mat4::from_translation(Vec3::new(
invert * 0.56,
-0.52 - inverse_height * 0.6,
-0.72,
));
if let ItemPose::Eat {
remaining,
duration,
partial,
} = pose
{
let time = remaining - partial + 1.0;
let fraction = time / duration;
let mut eat = Mat4::IDENTITY;
if fraction < 0.8 {
eat *=
Mat4::from_translation(Vec3::new(0.0, ((time / 4.0 * pi).mcos() * 0.1).abs(), 0.0));
}
let jiggle = 1.0 - horizon_core::jmath::pow(f64::from(fraction), 27.0) as f32;
eat *= Mat4::from_translation(Vec3::new(jiggle * 0.6 * invert, jiggle * -0.5, 0.0));
eat *= Mat4::from_rotation_y((invert * jiggle * 90.0).to_radians());
eat *= Mat4::from_rotation_x((jiggle * 10.0).to_radians());
eat *= Mat4::from_rotation_z((invert * jiggle * 30.0).to_radians());
return eat * m;
}
if matches!(pose, ItemPose::Using) {
return m;
}
let charging = match pose {
ItemPose::Bow { ticks_used } => {
let power = ticks_used / 20.0;
Some((
ticks_used,
((power * power + power * 2.0) / 3.0).min(1.0),
false,
))
}
ItemPose::Crossbow {
ticks_used: Some(ticks),
charge_duration,
charged: false,
} => Some((ticks, (ticks / charge_duration).min(1.0), true)),
ItemPose::Trident { ticks_used } => Some((ticks_used, (ticks_used / 10.0).min(1.0), false)),
_ => None,
};
if let Some((ticks, power, crossbow)) = charging {
let trident = matches!(pose, ItemPose::Trident { .. });
let (x, y, z, pitch, yaw) = if trident {
(-0.5, 0.7, 0.1, -55.0f32, 35.3f32)
} else if crossbow {
(-0.4785682, -0.094387, 0.05731531, -11.935f32, 65.3f32)
} else {
(-0.2785682, 0.18344387, 0.15731531, -13.935f32, 35.3f32)
};
m *= Mat4::from_translation(Vec3::new(invert * x, y, z));
m *= Mat4::from_rotation_x(pitch.to_radians());
m *= Mat4::from_rotation_y((invert * yaw).to_radians());
m *= Mat4::from_rotation_z((invert * -9.785f32).to_radians());
if power > 0.1 {
let shake = ((ticks - 0.1) * 1.3).msin() * (power - 0.1);
m *= Mat4::from_translation(Vec3::new(0.0, shake * 0.004, 0.0));
}
m *= Mat4::from_translation(Vec3::new(
0.0,
0.0,
power * if trident { 0.2 } else { 0.04 },
));
m *= Mat4::from_scale(Vec3::new(1.0, 1.0, 1.0 + power * 0.2));
m *= Mat4::from_rotation_y((invert * -45.0f32).to_radians());
} else {
let root = attack.sqrt();
m *= Mat4::from_translation(Vec3::new(
invert * -0.4 * (root * pi).msin(),
0.2 * (root * std::f32::consts::TAU).msin(),
-0.2 * (attack * pi).msin(),
));
m *= Mat4::from_rotation_y(
(invert * (45.0 - (attack * attack * pi).msin() * 20.0)).to_radians(),
);
m *= Mat4::from_rotation_z((invert * (root * pi).msin() * -20.0).to_radians());
m *= Mat4::from_rotation_x(((root * pi).msin() * -80.0).to_radians());
m *= Mat4::from_rotation_y((invert * -45.0f32).to_radians());
if matches!(pose, ItemPose::Crossbow { charged: true, .. }) && attack < 0.001 {
m *= Mat4::from_translation(Vec3::new(invert * -0.641864, 0.0, 0.0));
m *= Mat4::from_rotation_y((invert * 10.0f32).to_radians());
}
}
m
}
/// `InteractionHand`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Hand {
@@ -240,6 +359,23 @@ pub enum UseResult {
Fail,
}
impl UseResult {
pub fn should_swing(self, before: u32, after: u32) -> bool {
matches!(self, Self::Success { swing: true }) && before == after
}
}
pub fn consumable_animation(v: &serde_json::Value) -> horizon_world::consumable::UseAnimation {
use horizon_world::consumable::UseAnimation;
match v
.get("animation")
.and_then(serde_json::Value::as_str)
.unwrap_or("eat")
{
"eat" => UseAnimation::Eat,
"drink" => UseAnimation::Drink,
_ => UseAnimation::None,
}
}
/// What the click handling reads and does in the world.
pub trait HandWorld {
fn hit(&mut self) -> Hit;
@@ -628,3 +764,156 @@ mod tests {
assert_eq!(swing_duration(d, None, Some(2)), 12);
}
}
#[cfg(test)]
mod item_pose_tests {
use super::*;
#[test]
fn ranged_draw_uses_native_charge_curves_and_caps() {
for (ticks, stretch) in [
(0.0, 1.0),
(10.0, 1.0 + 0.2 * 1.25 / 3.0),
(20.0, 1.2),
(40.0, 1.2),
] {
let m = item_pose(false, 0.0, 0.0, ItemPose::Bow { ticks_used: ticks });
assert!((m.determinant() - stretch).abs() < 0.000001);
}
for duration in [25.0, 20.0, 15.0, 10.0] {
let m = item_pose(
false,
0.0,
0.0,
ItemPose::Crossbow {
ticks_used: Some(duration),
charge_duration: duration,
charged: false,
},
);
assert!((m.determinant() - 1.2).abs() < 0.000001);
}
}
#[test]
fn left_handed_ranged_poses_mirror_the_right_hand() {
let reflect = glam::Mat4::from_scale(glam::Vec3::new(-1.0, 1.0, 1.0));
for pose in [
ItemPose::Swing,
ItemPose::Bow { ticks_used: 10.0 },
ItemPose::Crossbow {
ticks_used: Some(10.0),
charge_duration: 25.0,
charged: false,
},
ItemPose::Crossbow {
ticks_used: None,
charge_duration: 25.0,
charged: true,
},
] {
let left = item_pose(true, 0.2, 0.0, pose).to_cols_array();
let right = (reflect * item_pose(false, 0.2, 0.0, pose) * reflect).to_cols_array();
for (a, b) in left.into_iter().zip(right) {
assert!((a - b).abs() < 0.000001);
}
}
}
#[test]
fn drawing_bow_has_its_own_pose() {
assert_ne!(
item_pose(false, 0.0, 0.0, ItemPose::Bow { ticks_used: 10.0 }),
item_pose(false, 0.0, 0.0, ItemPose::Swing)
);
}
#[test]
fn charging_crossbow_has_its_own_pose() {
assert_ne!(
item_pose(
false,
0.0,
0.0,
ItemPose::Crossbow {
ticks_used: Some(10.0),
charge_duration: 25.0,
charged: false
}
),
item_pose(false, 0.0, 0.0, ItemPose::Swing)
);
}
#[test]
fn charged_crossbow_is_aimed_while_idle() {
assert_ne!(
item_pose(
false,
0.0,
0.0,
ItemPose::Crossbow {
ticks_used: None,
charge_duration: 25.0,
charged: true
}
),
item_pose(false, 0.0, 0.0, ItemPose::Swing)
);
}
}
#[cfg(test)]
mod continuous_use_tests {
use super::*;
#[test]
fn eating_and_throwing_have_use_poses_not_attack_poses() {
let swing = item_pose(false, 0.0, 0.3, ItemPose::Swing);
assert_ne!(
swing,
item_pose(
false,
0.0,
0.3,
ItemPose::Eat {
remaining: 10.0,
duration: 32.0,
partial: 0.5
}
)
);
assert_ne!(
swing,
item_pose(false, 0.0, 0.3, ItemPose::Trident { ticks_used: 5.0 })
);
assert_ne!(swing, item_pose(false, 0.0, 0.3, ItemPose::Using));
}
}
#[cfg(test)]
mod action_result_tests {
use super::*;
#[test]
fn only_successful_actions_swing_once() {
assert!(UseResult::Success { swing: true }.should_swing(2, 2));
for result in [
UseResult::Fail,
UseResult::Pass,
UseResult::Success { swing: false },
] {
assert!(!result.should_swing(2, 2));
}
assert!(!UseResult::Success { swing: true }.should_swing(2, 3));
}
#[test]
fn consumption_pose_requires_eat_or_drink_animation() {
use horizon_world::consumable::UseAnimation::*;
assert_eq!(consumable_animation(&serde_json::json!({})), Eat);
assert_eq!(
consumable_animation(&serde_json::json!({"animation":"drink"})),
Drink
);
for animation in ["none", "block", "bow", "brush"] {
assert_eq!(
consumable_animation(&serde_json::json!({"animation":animation})),
None
);
}
}
}
+247 -36
View File
@@ -24,6 +24,8 @@ const BACK: u64 = id("front.back", 0);
const PLAY_WORLD: u64 = id("worlds.play", 0);
const CREATE: u64 = id("worlds.create", 0);
const WORLD: u64 = id("worlds.row", 0);
const DELETE_WORLD: u64 = id("worlds.delete", 0);
const CONFIRM_DELETE: u64 = id("delete.confirm", 0);
const NAME: u64 = id("create.name", 0);
const SEED: u64 = id("create.seed", 0);
const MODE: u64 = id("create.mode", 0);
@@ -91,15 +93,21 @@ fn page(mode: &Mode) -> usize {
}
}
const PAGES: [&str; 4] = ["Home", "Singleplayer", "Multiplayer", "Options"];
/// World editing and backups still use the classic screens, and so do their
/// errors; the rest of the singleplayer flow has Horizon pages.
fn classic(mode: &Mode) -> bool {
match mode {
Mode::Edit { .. } | Mode::Backup { .. } => true,
Mode::Error { return_to, .. } => classic(return_to),
_ => false,
}
}
impl Title {
/// Horizon's layout for every title mode. `backdrop` is how much of the
/// live backdrop is visible (0 shows the plain cold background).
pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) {
if matches!(
self.mode,
Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. }
) {
if classic(&self.mode) {
self.draw(ui.atlas, ui.batch, ui.cursor);
return;
}
@@ -149,11 +157,15 @@ impl Title {
let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
create_page(ui, x, w, name, seed, *creative, *focus, caret);
}
Mode::Delete { world } => delete_page(ui, x, w, world),
Mode::Error { message, .. } => error_page(ui, x, w, message),
Mode::Multiplayer(screen) => {
let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
multiplayer_page(ui, x, w, screen, caret);
}
_ => unreachable!("World-management screens use the classic layout"),
Mode::Edit { .. } | Mode::Backup { .. } => {
unreachable!("World editing uses the classic layout")
}
}
}
ui.opacity = 1.0;
@@ -307,10 +319,7 @@ impl Title {
if self.skip_opening() {
return Action::None;
}
if matches!(
self.mode,
Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. }
) {
if classic(&self.mode) {
return self.click(x, y, (batch.width, batch.height)).0;
}
let hit = {
@@ -377,6 +386,11 @@ impl Title {
focus: 0,
}
}
DELETE_WORLD => {
if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() {
self.mode = Mode::Delete { world };
}
}
h if (WORLD..WORLD + 10_000).contains(&h) => {
let i = (h - WORLD) as usize;
if *selected == Some(i) {
@@ -398,7 +412,25 @@ impl Title {
MAKE => return self.create_action(),
_ => {}
},
Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } => {}
Mode::Delete { .. } => match hit {
// The selection stays in place: on the world that moved up
// into the deleted one's row, or the new last one.
CONFIRM_DELETE => {
if let Some(row) = self.confirm_delete()
&& let Mode::Select { worlds, selected } = &mut self.mode
{
*selected = worlds.len().checked_sub(1).map(|last| row.min(last));
}
}
BACK => self.escape(),
_ => {}
},
Mode::Error { return_to, .. } => {
if hit == BACK {
self.mode = *return_to.clone();
}
}
Mode::Edit { .. } | Mode::Backup { .. } => {}
Mode::Multiplayer(screen) => {
let id = match hit {
JOIN => Some(40),
@@ -564,15 +596,14 @@ fn worlds_page(
n => format!("{n} worlds in the saves folder."),
};
let mut y = header(ui, x, "Singleplayer", &count);
actions_right(
ui,
x + w,
y - 24.0 - 58.0,
&[
(PLAY_WORLD, "Play", Kind::Primary, selected.is_some()),
(CREATE, "Create world", Kind::Secondary, true),
],
);
let mut items = vec![
(PLAY_WORLD, "Play", Kind::Primary, selected.is_some()),
(CREATE, "Create world", Kind::Secondary, true),
];
if selected.is_some() {
items.push((DELETE_WORLD, "Delete", Kind::Danger, true));
}
actions_right(ui, x + w, y - 24.0 - 58.0, &items);
ui.divider(x, y, w);
if worlds.is_empty() {
empty(ui, x, y, "A blank map.", "Create a world to begin.");
@@ -608,6 +639,100 @@ fn worlds_page(
}
}
/// The launcher's notice: a plate led by a danger dot, the first line in
/// medium type, wrapped lines under it. Returns its height.
fn notice(ui: &mut Ui, x: f32, y: f32, w: f32, title: Option<&str>, text: &str) -> f32 {
let lines = wrap(ui, text, w - 48.0);
let title_h = if title.is_some() { 26.0 } else { 0.0 };
let h = 32.0 + title_h + lines.len() as f32 * 19.0;
ui.rounded(x, y, w, h, t::RADIUS_PLATE, color::RAISED);
ui.rounded(x + 16.0, y + 22.0, 6.0, 6.0, 3.0, color::DANGER);
let mut ty = y + 16.0;
if let Some(title) = title {
let title = ui.fit(Face::Medium, t::LARGE + 2.0, title, w - 48.0);
ui.text_line(
Face::Medium,
t::LARGE + 2.0,
19.0,
x + 32.0,
ty,
color::TEXT,
&title,
);
ty += title_h;
}
for (i, line) in lines.iter().enumerate() {
let tint = if title.is_some() {
color::MUTED
} else {
color::TEXT
};
ui.text_line(
Face::Regular,
BODY,
19.0,
x + 32.0,
ty + i as f32 * 19.0,
tint,
line,
);
}
h
}
/// `ConfirmScreen` for a world: what goes, that it can't come back, then
/// Delete (danger) and Cancel under it.
fn delete_page(ui: &mut Ui, x: f32, w: f32, world: &crate::title::WorldEntry) {
let mut y = header(
ui,
x,
"Delete this world?",
"It will be lost forever. This can't be undone.",
);
ui.divider(x, y, w);
y += 16.0;
let secs = world
.modified
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let text = format!(
"Last played {}. The folder saves/{} and everything built in it will be removed.",
crate::title::date_label(secs),
world.folder
);
y += notice(ui, x, y, w, Some(&world.name), &text) + 16.0;
let dw = ui.button_width("Delete world", false);
ui.button(
CONFIRM_DELETE,
[x, y, dw, CONTROL],
"Delete world",
Kind::Danger,
true,
);
let cw = ui.button_width("Cancel", false);
ui.button(
BACK,
[x + dw + 8.0, y, cw, CONTROL],
"Cancel",
Kind::Ghost,
true,
);
}
fn error_page(ui: &mut Ui, x: f32, w: f32, message: &str) {
let mut y = header(
ui,
x,
"Something went wrong",
"Horizon couldn't finish that.",
);
ui.divider(x, y, w);
y += 16.0;
y += notice(ui, x, y, w, None, message) + 16.0;
let bw = ui.button_width("Back", false);
ui.button(BACK, [x, y, bw, CONTROL], "Back", Kind::Secondary, true);
}
#[allow(clippy::too_many_arguments)]
fn create_page(
ui: &mut Ui,
@@ -839,23 +964,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
);
ui.divider(x, y, w);
y += 16.0;
// The launcher's error note: a danger dot beside the message.
let lines = wrap(ui, reason, w - 40.0);
let box_h = 24.0 + lines.len() as f32 * 19.0;
ui.rounded(x, y, w, box_h, t::RADIUS_PLATE, color::RAISED);
ui.rounded(x + 12.0, y + 18.0, 6.0, 6.0, 3.0, color::DANGER);
for (i, line) in lines.iter().enumerate() {
ui.text_line(
Face::Regular,
BODY,
19.0,
x + 28.0,
y + 12.0 + i as f32 * 19.0,
color::TEXT,
line,
);
}
y += box_h + 16.0;
y += notice(ui, x, y, w, None, reason) + 16.0;
if let Some(r) = retry {
// Auto-reconnect's countdown, with a way out.
let text = r.text(std::time::Instant::now());
@@ -1006,3 +1115,105 @@ pub mod pause {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_world::nbt::Tag;
fn world(saves: &std::path::Path, folder: &str, last_played: i64) {
crate::save::write_dat(
&saves.join(folder).join("level.dat"),
Tag::compound([(
"Data",
Tag::compound([
("LevelName", Tag::String(folder.into())),
("GameType", Tag::Int(0)),
("LastPlayed", Tag::Long(last_played)),
("WorldGenSettings", Tag::compound([("seed", Tag::Long(1))])),
]),
)]),
)
.unwrap();
}
/// Clicks the middle of button `bid` as the game would; panics if the
/// page does not show it.
fn press(title: &mut Title, atlas: &HudAtlas, bid: u64) -> Action {
let mut batch = HudBatch::new([1280, 720]);
let (rect, density) = {
let mut ui = Ui::dry(atlas, &mut batch, (0.0, 0.0));
title.draw_horizon(&mut ui, 1.0);
let hit = ui.hits.iter().rev().find(|h| h.id == bid);
(hit.expect("button on the page").rect, ui.density)
};
let k = density / batch.scale;
let (x, y) = ((rect[0] + rect[2]) / 2.0 * k, (rect[1] + rect[3]) / 2.0 * k);
title.click_horizon(atlas, &mut batch, x, y)
}
fn shows(title: &Title, atlas: &HudAtlas, bid: u64) -> bool {
let mut batch = HudBatch::new([1280, 720]);
let mut ui = Ui::dry(atlas, &mut batch, (0.0, 0.0));
title.draw_horizon(&mut ui, 1.0);
ui.hits.iter().any(|h| h.id == bid)
}
fn selected(title: &Title) -> Option<String> {
match &title.mode {
Mode::Select { worlds, selected } => selected.map(|i| worlds[i].folder.clone()),
_ => panic!("not on the world list"),
}
}
#[test]
fn horizon_world_delete_confirms_and_keeps_the_selection_in_place() {
let atlas =
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
let root =
std::env::temp_dir().join(format!("horizon-front-delete-{}", std::process::id()));
let saves = root.join("saves");
for (i, folder) in ["C", "B", "A"].iter().enumerate() {
world(&saves, folder, 1000 * (i as i64 + 1));
}
let mut title = Title::new(saves.clone());
title.mode = Mode::Select {
worlds: list_worlds(&saves),
selected: None,
};
assert!(!shows(&title, &atlas, DELETE_WORLD));
press(&mut title, &atlas, WORLD + 1);
assert_eq!(selected(&title).as_deref(), Some("B"));
// Cancel leaves the world and its selection.
press(&mut title, &atlas, DELETE_WORLD);
assert!(matches!(&title.mode, Mode::Delete { world } if world.folder == "B"));
press(&mut title, &atlas, BACK);
assert_eq!(selected(&title).as_deref(), Some("B"));
assert!(saves.join("B/level.dat").is_file());
// Deleting selects the world that moved up into the row.
press(&mut title, &atlas, DELETE_WORLD);
press(&mut title, &atlas, CONFIRM_DELETE);
assert!(!saves.join("B").exists());
assert_eq!(selected(&title).as_deref(), Some("C"));
// A world open elsewhere is refused on a Horizon page; Back returns
// to the question.
let open = crate::save::SessionLock::acquire(&saves.join("C")).unwrap();
press(&mut title, &atlas, DELETE_WORLD);
press(&mut title, &atlas, CONFIRM_DELETE);
assert!(matches!(title.mode, Mode::Error { .. }));
assert!(!classic(&title.mode));
press(&mut title, &atlas, BACK);
assert!(matches!(title.mode, Mode::Delete { .. }));
drop(open);
// The last row: the selection moves to the new last world.
press(&mut title, &atlas, CONFIRM_DELETE);
assert_eq!(selected(&title).as_deref(), Some("A"));
press(&mut title, &atlas, DELETE_WORLD);
press(&mut title, &atlas, CONFIRM_DELETE);
assert!(
matches!(&title.mode, Mode::Select { worlds, selected: None } if worlds.is_empty())
);
let _ = std::fs::remove_dir_all(root);
}
}
File diff suppressed because it is too large Load Diff
@@ -45,7 +45,7 @@ impl Toast {
pub(super) struct AdvState {
pub(super) tree: Arc<Tree>,
pub(super) progress: Progress,
loaded: bool,
pub(super) loaded: bool,
pub(super) toasts: VecDeque<Toast>,
/// Awards skip the toast (`/advancement grant ... everything`).
pub(super) quiet: bool,
+5
View File
@@ -506,6 +506,11 @@ impl Game<'_> {
Mode::Error { message, .. } => {
json!({ "mode": "world-operation-error", "message": message })
}
Mode::Multiplayer(horizon_client::multiplayer::Screen::Disconnected {
reason, ..
}) => {
json!({ "mode": "multiplayer", "disconnected": reason })
}
Mode::Multiplayer(_) => json!({ "mode": "multiplayer" }),
}
}
+5
View File
@@ -54,6 +54,11 @@ impl Game<'_> {
.inflate(horizon_core::geometry::Vec3::new(1.0, 1.0, 1.0));
if b.contains(e.position) {
let take = (max - carried).min(e.stack.count as i32);
let (item, id) = (e.clone(), self.mobs[i].id);
self.add_pickup(
super::pickups::Taken::Item(Box::new(item)),
super::pickups::Collector::Mob(id),
);
self.mobs[i].extra.ints[1] += take;
let e = &mut self.dropped[j];
e.stack.count -= take as u32;
+54 -2
View File
@@ -41,6 +41,9 @@ impl ArmorStandAssets {
}
}
}
if let Some(part) = load("minecraft:elytra#main") {
player.insert("elytra", part);
}
let mut equipment = HashMap::new();
if let Ok(entries) = std::fs::read_dir(root.join("assets/minecraft/equipment")) {
for e in entries.flatten() {
@@ -55,7 +58,7 @@ impl ArmorStandAssets {
};
let Ok(v) = v else { continue };
let mut kinds = HashMap::new();
for kind in ["humanoid", "humanoid_leggings"] {
for kind in ["humanoid", "humanoid_leggings", "wings"] {
if let Some(layer) = v["layers"][kind].get(0) {
let tex = layer["texture"]
.as_str()
@@ -365,8 +368,23 @@ impl Game<'_> {
binding: self.collision,
subject: None,
};
for a in &mut self.armor_stands {
let mut dead = Vec::new();
for (i, a) in self.armor_stands.iter_mut().enumerate() {
a.tick(&mut scene);
if !a.environment_tick(&self.world, &self.res.facts, self.res.assets.registry) {
dead.push(i);
}
}
for i in dead.into_iter().rev() {
let a = self.armor_stands.remove(i);
let at = [a.position.x, a.position.y, a.position.z];
let (pos, drops) = burnt_armor_stand_equipment(a);
for stack in drops {
self.pop_resource(pos, stack);
}
self.audio
.play("minecraft:entity.armor_stand.break", Some(at), 1.0, 1.0);
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
}
}
/// ArmorStandRenderer: the stand with its default pose, then armor layers.
@@ -684,3 +702,37 @@ fn skull_kind(item: &str) -> Option<&'static str> {
_ => return None,
})
}
fn burnt_armor_stand_equipment(a: ArmorStand) -> ([i32; 3], Vec<ItemStack>) {
let pos = [
a.position.x.floor() as i32,
a.position.y.floor() as i32 + 1,
a.position.z.floor() as i32,
];
let drops = a
.equipment
.into_iter()
.flatten()
.filter(|stack| stack.enchantment_level("minecraft:vanishing_curse") == 0)
.collect();
(pos, drops)
}
#[cfg(test)]
mod burn_drop_tests {
use super::*;
#[test]
fn burnt_equipment_drops_above_the_block_and_vanishing_items_do_not_drop() {
let mut stand = ArmorStand::new(1, Vec3::new(-0.1, 4.8, 0.0), 0.0);
let kept = ItemStack::new("minecraft:diamond_boots", 1);
let mut vanished = ItemStack::new("minecraft:diamond_helmet", 1);
vanished
.data_mut()
.enchantments
.push(("minecraft:vanishing_curse".into(), 1));
stand.equipment[0] = Some(kept.clone());
stand.equipment[1] = Some(vanished);
let (pos, drops) = burnt_armor_stand_equipment(stand);
assert_eq!(pos, [-1, 5, 0]);
assert_eq!(drops, vec![kept]);
}
}
+1
View File
@@ -79,6 +79,7 @@ impl Game<'_> {
_ => return false,
};
self.open_book(screen);
self.swing_arm();
true
}
fn open_book(&mut self, screen: BookScreen) {
+6
View File
@@ -54,6 +54,12 @@ impl Game<'_> {
.push((damage_type.to_owned(), (mob, name)));
}
}
/// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the
/// source's `DamageEffects` (`Player.getHurtSound`).
pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) {
let pitch = self.audio.hurt_pitch();
self.audio.play(sound, Some(at), 1.0, pitch);
}
/// `CombatTracker.recordDamage` for the motion events of this tick.
pub(super) fn record_combat(&mut self, events: &[MotionEvent]) {
self.recheck_combat();
+1 -1
View File
@@ -484,7 +484,7 @@ impl Game<'_> {
}
let name = words
.get(2)
.map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned());
.map_or_else(|| self.options.player_name(), |n| (*n).to_owned());
self.connect_server(arg(1)?, &name)?;
ok()
}
+107 -74
View File
@@ -40,7 +40,6 @@ fn arrow_impact_sound(
pub(super) struct Creatures {
pub projectiles: Vec<Projectile>,
/// Player status effects applied by mobs: (effect, ticks left, amplifier).
pub player_fire: i32,
pub pearl_cooldown: u32,
/// The wind charge's use cooldown (ticks).
pub wind_cooldown: u32,
@@ -821,8 +820,10 @@ impl Game<'_> {
source,
} => {
let mut killed = false;
let mut hurt = false;
if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) {
let hit = t.damage(amount, source);
hurt = hit;
if hit {
killed = !t.alive();
// The hurt or death sound the mob raised.
@@ -839,6 +840,20 @@ impl Game<'_> {
}
}
}
if hurt
&& let Some(Who::Mob(attacker)) = source.attacker
&& let Some(m) = self
.mobs
.iter()
.find(|m| m.id == attacker && m.species() == Species::Axolotl)
{
self.audio.play(
"minecraft:entity.axolotl.attack",
Some([m.position.x, m.position.y, m.position.z]),
1.0,
1.0,
);
}
if killed && let Some(Who::Mob(killer)) = source.attacker {
self.zombie_killed(killer, target);
}
@@ -993,6 +1008,26 @@ impl Game<'_> {
}
}
MobEvent::Experience { at, amount } => self.spawn_orbs(at, amount),
MobEvent::AxolotlSupportPlayer => {
let previous = self
.potions
.effects
.get("regeneration")
.map_or(0, |e| e.duration);
if (0..=2399).contains(&previous) {
self.potions
.effects
.add(horizon_client::effects::EffectInstance::new(
"regeneration",
(previous + 100).min(2400),
0,
));
}
self.potions
.effects
.list
.retain(|e| e.id != "mining_fatigue");
}
MobEvent::EffectPlayer {
effect,
ticks,
@@ -1002,14 +1037,15 @@ impl Game<'_> {
}
MobEvent::Ignite { target, seconds } => match target {
Who::Player => {
if !self.creative {
self.creatures.player_fire =
self.creatures.player_fire.max(seconds * 20);
if !self.creative
&& let Some(p) = self.player.as_mut()
{
p.ignite_for_ticks(seconds * 20)?;
}
}
Who::Mob(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.fire_ticks = m.fire_ticks.max(seconds * 20);
m.ignite_for_ticks(seconds * 20);
}
}
},
@@ -1352,9 +1388,6 @@ impl Game<'_> {
(player.velocity.y / 2.0 + 0.4).min(0.4),
player.velocity.z / 2.0 + dz / l * 0.4,
);
let at = [player.position.x, player.position.y, player.position.z];
self.audio
.play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0);
self.hurt_armor(amount);
self.thorns(from);
}
@@ -1377,24 +1410,6 @@ impl Game<'_> {
}
/// Burning applied to the player by mobs.
fn tick_player_effects(&mut self) {
let in_water = self.player.as_ref().is_some_and(|p| {
let (x, y, z) = (
p.position.x.floor() as i32,
p.position.y.floor() as i32,
p.position.z.floor() as i32,
);
self.res.facts.get(self.world.block(x, y, z)).fluid == Fluid::Water
});
if self.creatures.player_fire > 0 {
if in_water {
self.creatures.player_fire = 0;
} else {
if self.creatures.player_fire % 20 == 0 {
self.hurt_player_by("minecraft:on_fire", 1.0);
}
self.creatures.player_fire -= 1;
}
}
self.creatures.wind_cooldown = self.creatures.wind_cooldown.saturating_sub(1);
if self.creatures.pearl_cooldown > 0 {
self.creatures.pearl_cooldown -= 1;
@@ -1434,6 +1449,7 @@ impl Game<'_> {
// Player.hasInfiniteMaterials.
let creative = self.creative;
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
let mut picked = Vec::new();
projectiles.retain(|shot| {
let Some(a) = shot.arrow.as_ref().filter(|a| !a.removed) else {
return true;
@@ -1461,10 +1477,17 @@ impl Game<'_> {
0.2,
pitch,
);
picked.push(shot.clone());
}
!taken
});
self.creatures.projectiles = projectiles;
for shot in picked {
self.add_pickup(
super::pickups::Taken::Arrow(Box::new(shot)),
super::pickups::Collector::Player,
);
}
}
fn tick_projectiles(&mut self) -> Result<()> {
@@ -1841,7 +1864,9 @@ impl Game<'_> {
Hit::Entity { who, .. } => match who {
Who::Player => {
if !self.creative {
self.creatures.player_fire = self.creatures.player_fire.max(100);
if let Some(p) = self.player.as_mut() {
p.ignite_for_ticks(100)?;
}
self.mob_hits_player(
5.0,
[p.previous.x, p.previous.y, p.previous.z],
@@ -1852,7 +1877,7 @@ impl Game<'_> {
Who::Mob(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
if !m.kind.flags.fire_immune {
m.fire_ticks = m.fire_ticks.max(100);
m.ignite_for_ticks(100);
}
m.damage(5.0, source);
}
@@ -2070,6 +2095,32 @@ impl Game<'_> {
.as_ref()
.map(|h| h.item.to_string())
.unwrap_or_default();
if item == "minecraft:water_bucket"
&& self.mobs[index].species() == Species::Axolotl
&& self.mobs[index].alive()
{
let mut filled = ItemStack::new("minecraft:axolotl_bucket", 1);
filled.extra = Some(Box::new(horizon_client::entity_nbt::bucket_components(
&self.mobs[index],
)));
self.audio.play(
"minecraft:item.bucket.fill_axolotl",
Some(self.mobs[index].center()),
1.0,
1.0,
);
self.trigger_item("minecraft:filled_bucket", &filled);
self.mobs[index].removed = true;
if self.creative {
if let Some(rest) = self.give(filled) {
self.spawn_item(rest, self.eye_position().unwrap_or([0.0; 3]), [0.0; 3], 40);
}
} else {
self.inventory[self.selected] = Some(filled);
}
self.swing_arm();
return Ok(true);
}
let creative = self.creative;
let selected = self.selected;
if self.interact_zombie_villager(index, &item) {
@@ -2663,7 +2714,7 @@ impl Game<'_> {
}
self.elder_apparition_geometry(alpha, out);
self.spawner_geometry(camera, alpha, out);
// Projectiles: arrows as crossed quads, the rest as item billboards.
// Projectiles: the baked vanilla arrow model, the rest as item billboards.
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
let forward = glam::Vec3::new(
-yaw.sin() * pitch.cos(),
@@ -2672,12 +2723,21 @@ impl Game<'_> {
);
let right = forward.cross(glam::Vec3::Y).normalize_or_zero();
let up = right.cross(forward).normalize_or_zero();
for a in &self.creatures.projectiles {
let p = glam::DVec3::new(
let live = self.creatures.projectiles.iter().map(|a| {
let at = [
a.previous.x + (a.position.x - a.previous.x) * alpha,
a.previous.y + (a.position.y - a.previous.y) * alpha,
a.previous.z + (a.position.z - a.previous.z) * alpha,
) - camera;
];
(a, at)
});
// ItemPickupParticle: a picked-up arrow flying to its collector.
let taken = self.pickups.live.iter().filter_map(|p| match &p.taken {
super::pickups::Taken::Arrow(a) => Some((&**a, super::pickups::position(p, alpha))),
_ => None,
});
for (a, at) in live.chain(taken) {
let p = glam::DVec3::from_array(at) - camera;
let c = p.as_vec3();
let light = self.world.light(
a.position.x.floor() as i32,
@@ -2689,52 +2749,24 @@ impl Game<'_> {
packed = (15 * 16) | ((15 * 16) << 8);
}
if a.is_arrow() {
let Some(model) = self.arrow_model.as_ref() else {
continue;
};
let Some(r) = atlas.sprites.get("entity/projectiles/arrow").copied() else {
continue;
};
let dir = glam::Vec3::new(
a.velocity.x as f32,
a.velocity.y as f32,
a.velocity.z as f32,
)
.normalize_or(glam::Vec3::X);
let dir = if a.stuck {
glam::Vec3::new(
-a.yaw.to_radians().sin() * a.pitch.to_radians().cos(),
a.pitch.to_radians().sin(),
a.yaw.to_radians().cos() * a.pitch.to_radians().cos(),
)
.normalize_or(dir)
} else {
dir
};
let side = dir.cross(glam::Vec3::Y).normalize_or(glam::Vec3::Z) * 0.08;
let upv = dir.cross(side).normalize_or(glam::Vec3::Y) * 0.08;
let (u1, v1) = (
r.u0 + (r.u1 - r.u0) * 0.5,
r.v0 + (r.v1 - r.v0) * (5.0 / 32.0),
let m = glam::Mat4::from_translation(c)
* glam::Mat4::from_rotation_y((a.yaw - 90.0).to_radians())
* glam::Mat4::from_rotation_z(a.pitch.to_radians());
horizon_client::mobs::render_model(
model,
m,
&|part| part.pose,
[r.u0, r.v0, r.u1, r.v1],
packed,
0,
out,
);
for off in [side, upv] {
let q = [
c - dir * 0.25 - off,
c + dir * 0.25 - off,
c + dir * 0.25 + off,
c - dir * 0.25 + off,
];
for (v, uv) in q
.iter()
.zip([[r.u0, v1], [u1, v1], [u1, r.v0], [r.u0, r.v0]])
{
out.push(Vertex {
normal: [0; 4],
pos: v.to_array(),
uv,
layer: 0,
color: 0xFFFF_FFFF,
light: packed,
});
}
}
if a.arrow.as_ref().is_some_and(|s| s.on_fire()) {
flame_geometry(atlas, c, 0.5, 0.5, self.yaw, light, out);
}
@@ -2847,6 +2879,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack {
.collect(),
potion: None,
map: false,
exploration: None,
ominous_amplifier: None,
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ use horizon_core::{geometry::Vec3, random::RandomSource};
const CROSSBOW: &str = "minecraft:crossbow";
impl Game<'_> {
fn charge_ticks(stack: &ItemStack) -> u32 {
pub(super) fn charge_ticks(stack: &ItemStack) -> u32 {
// crossbow_charge_time: 1.25 s, minus 0.25 s per Quick Charge level.
let seconds = 1.25 - 0.25 * stack.enchantment_level("minecraft:quick_charge") as f32;
(seconds.max(0.0) * 20.0).floor() as u32
@@ -42,7 +42,7 @@ impl Game<'_> {
],
}
}
fn arrow_slot(&self) -> Option<usize> {
pub(super) fn arrow_slot(&self) -> Option<usize> {
self.inventory
.iter()
.position(|s| s.as_ref().is_some_and(|s| &*s.item == "minecraft:arrow"))
+8 -45
View File
@@ -742,7 +742,7 @@ impl Game<'_> {
1.0 + amount
}
/// `EntityType.spawn(.., pos, reason, tryMoveDown, false)` for a mob.
fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option<u32> {
pub(super) fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option<u32> {
let name = if kind.contains(':') {
kind.to_owned()
} else {
@@ -869,7 +869,7 @@ impl Game<'_> {
self.handle_mob_events(events)
}
/// A mob a bucket emptied: `setFromBucket` keeps it, then it calls out.
fn mob_placed(&mut self, id: u32) -> Result<()> {
pub(super) fn mob_placed(&mut self, id: u32) -> Result<()> {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.persistent = true;
}
@@ -1137,48 +1137,8 @@ impl Game<'_> {
) -> Result<Dispensed> {
let item = stack.item.to_string();
let target = offset(pos, facing);
let (content, sound, mob) = match item.as_str() {
"minecraft:lava_bucket" => (
BucketContent::Fluid(FluidKind::Lava),
"minecraft:item.bucket.empty_lava",
None,
),
"minecraft:water_bucket" => (
BucketContent::Fluid(FluidKind::Water),
"minecraft:item.bucket.empty",
None,
),
"minecraft:powder_snow_bucket" => (
BucketContent::Powder,
"minecraft:item.bucket.empty_powder_snow",
None,
),
"minecraft:axolotl_bucket" => (
BucketContent::MobWater,
"minecraft:item.bucket.empty_axolotl",
Some("axolotl"),
),
"minecraft:tadpole_bucket" => (
BucketContent::MobWater,
"minecraft:item.bucket.empty_tadpole",
Some("tadpole"),
),
"minecraft:sulfur_cube_bucket" => (
BucketContent::Nothing,
"minecraft:item.bucket.empty_sulfur_cube",
Some("sulfur_cube"),
),
other => (
BucketContent::MobWater,
"minecraft:item.bucket.empty_fish",
Some(match other {
"minecraft:salmon_bucket" => "salmon",
"minecraft:cod_bucket" => "cod",
"minecraft:pufferfish_bucket" => "pufferfish",
_ => "tropical_fish",
}),
),
};
let (content, sound, mob) =
horizon_client::items::bucket_contents(&item).expect("filled bucket dispatcher");
let target_pos = Self::pos_of(target);
let emptied = self
.with_level(|b, level, ticks| b.bucket_empty(level, ticks, target_pos, content, sound));
@@ -1213,6 +1173,9 @@ impl Game<'_> {
// MobBucketItem.checkExtraContent: the mob (from the bucket, so
// persistent) calls out, then ENTITY_PLACE.
if let Some(id) = self.spawn_mob_at(kind, target, true) {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
horizon_client::entity_nbt::load_bucket_data(m, &stack);
}
self.mob_placed(id)?;
}
self.post_block_game_event(
@@ -1333,7 +1296,7 @@ impl Game<'_> {
Ok((Some(stack), event))
}
/// `CampfireBlock.canLight || CandleBlock.canLight || CandleCakeBlock.canLight`.
fn can_light(&self, state: BlockStateId, name: &str) -> bool {
pub(super) fn can_light(&self, state: BlockStateId, name: &str) -> bool {
let lit = self.prop(state, "lit");
let waterlogged = self.prop(state, "waterlogged");
let dry_unlit = lit.as_deref() == Some("false") && waterlogged.as_deref() == Some("false");
@@ -159,11 +159,11 @@ impl Game<'_> {
}
}
}
if ignite > 0.0 {
// Entity.igniteForSeconds; mobs burn for 1 damage per second.
let id = self.mobs[mob].id;
self.potions.burning.retain(|(m, _)| *m != id);
self.potions.burning.push((id, (ignite * 20.0) as i32));
if ignite > 0.0
&& let Some(m) = self.mobs.get_mut(mob)
&& !m.kind.flags.fire_immune
{
m.ignite_for_ticks((ignite * 20.0) as i32);
}
self.post_attack_bursts(&held, &kind);
}
@@ -229,25 +229,6 @@ impl Game<'_> {
let _ = self.wind_burst(feet, radius, knockback, false, false);
}
}
/// Burning mobs (fire aspect): one damage every 20 ticks, flame particles.
pub(super) fn tick_burning(&mut self) {
let mut burning = std::mem::take(&mut self.potions.burning);
burning.retain_mut(|(id, ticks)| {
*ticks -= 1;
let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id && m.alive()) else {
return false;
};
if *ticks % 20 == 0 {
let at = [m.position.x, m.position.y, m.position.z];
if m.hurt(1.0, None, &mut self.world.random) {
self.last_hurt_by_player.insert(*id);
let _ = at;
}
}
*ticks > 0
});
self.potions.burning = burning;
}
/// Thorns on worn armor when a mob at `from` hits the player.
pub(super) fn thorns(&mut self, from: [f64; 3]) {
let attacker = self
@@ -102,6 +102,7 @@ impl Game<'_> {
if !self.creative {
self.consume_held();
}
self.swing_arm();
true
}
pub(super) fn tick_rockets(&mut self) {
+64 -2
View File
@@ -14,6 +14,21 @@ use horizon_client::{
/// The off hand's place in `visible_hands` (the main hand uses its hotbar slot).
const OFFHAND: usize = usize::MAX;
/// `AttackRange.isInRange`: float bounds, then inclusive double comparison.
fn attack_range_contains(range: &serde_json::Value, distance: f64, creative: bool) -> bool {
let value = |key: &str, default: f32| range[key].as_f64().map_or(default, |v| v as f32);
let (min, max) = if creative {
(
value("min_creative_reach", 0.0),
value("max_creative_reach", 5.0),
)
} else {
(value("min_reach", 0.0), value("max_reach", 3.0))
};
let margin = value("hitbox_margin", 0.3);
distance >= f64::from(min - margin) && distance <= f64::from(max + margin)
}
impl Game<'_> {
/// `LivingEntity.swing` with `getModifiedSwingDuration`.
pub(super) fn swing_hand(&mut self, hand: Hand, animation: SwingAnimation) {
@@ -219,16 +234,35 @@ impl Game<'_> {
let living = nearest(&[
self.mob_hit().map(|h| h.1),
self.armor_stand_hit().map(|h| h.1),
self.dragon_hit().map(|h| h.1),
])?;
let other = nearest(&[
self.painting_hit().map(|h| h.1),
self.frame_hit().map(|h| h.1),
self.boat_hit().map(|h| h.1),
self.cart_hit().map(|h| h.1),
self.dragon_hit().map(|h| h.1),
]);
if !self.before_block(living) || other.is_some_and(|o| o <= living) {
return None;
}
let active = self
.using
.and_then(|(slot, _)| self.inventory.get(slot).and_then(Option::as_ref))
.or_else(|| self.held());
if let Some(stack) = active {
let components = self
.res
.item_renderer
.models
.components(&horizon_client::item_render::stack_view(stack));
if let Some(range) = components.get("minecraft:attack_range")
&& !attack_range_contains(range, living, self.creative)
{
return None;
}
}
// Only alive mobs are hit, so a picked living entity is alive.
(self.before_block(living) && other.is_none_or(|o| living <= o)).then_some(true)
Some(true)
}
/// `Attributes.ATTACK_SPEED` with the main-hand item's modifier.
pub(super) fn main_hand_attack_speed(&self) -> f64 {
@@ -392,3 +426,31 @@ impl HandWorld for GameHands<'_, '_> {
}
fn release_using(&mut self) {}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn attack_range_uses_inclusive_float_bounds() {
let range = serde_json::json!({
"min_reach": 2.0, "max_reach": 4.5,
"min_creative_reach": 2.0, "max_creative_reach": 6.5,
"hitbox_margin": 0.125,
});
for (creative, min, max) in [(false, 1.875, 4.625), (true, 1.875, 6.625)] {
for distance in [min, max] {
assert!(attack_range_contains(&range, distance, creative));
}
for distance in [min - 0.0001, max + 0.0001] {
assert!(!attack_range_contains(&range, distance, creative));
}
}
let defaults = serde_json::json!({});
for (creative, reach) in [(false, 3.0f32), (true, 5.0f32)] {
let max = f64::from(reach + 0.3f32);
assert!(attack_range_contains(&defaults, max, creative));
assert!(!attack_range_contains(&defaults, max + 1e-8, creative));
}
}
}
+17 -5
View File
@@ -220,7 +220,7 @@ impl Game<'_> {
owner.using_this_item = true;
owner.use_duration = duration;
owner.use_item_remaining_ticks = duration - ticks as i32;
owner.crossbow_charge_duration = 25;
owner.crossbow_charge_duration = Self::charge_ticks(stack).max(1) as i32;
}
owner.is_selected =
stack.is_some() && self.inventory.get(self.selected).and_then(Option::as_ref) == stack;
@@ -310,13 +310,25 @@ impl Game<'_> {
alpha: f64,
out: &mut Vec<Vertex>,
) {
for item in &self.dropped {
let live = self.dropped.iter().map(|item| {
let (p, q) = (item.previous, item.position);
let pos = glam::DVec3::new(
let at = [
p.x + (q.x - p.x) * alpha,
p.y + (q.y - p.y) * alpha,
p.z + (q.z - p.z) * alpha,
) - camera;
];
(item, at, alpha as f32)
});
// ItemPickupParticle: the render state extracted at partial tick 1.
let taken = self.pickups.live.iter().filter_map(|p| match &p.taken {
super::pickups::Taken::Item(item) => {
Some((&**item, super::pickups::position(p, alpha), 1.0))
}
_ => None,
});
for (item, at, partial) in live.chain(taken) {
let q = item.position;
let pos = glam::DVec3::from_array(at) - camera;
if pos.length_squared() > 64.0 * 64.0 {
continue;
}
@@ -331,7 +343,7 @@ impl Game<'_> {
if state.is_empty() {
continue;
}
let age = item.age as f32 + alpha as f32;
let age = item.age as f32 + partial;
let (lo, _) = state.bounding_box();
let min_offset_y = -lo.y + 0.0625;
let bob = (age / 10.0 + item.bob_offset).sin() * 0.1 + 0.1;
+20 -1
View File
@@ -748,10 +748,12 @@ impl Game<'_> {
let rest = self.as_guest(host, conn, |g| g.give(stack)).flatten();
match rest {
None => {
self.dropped.remove(i);
let item = self.dropped.remove(i);
self.guest_pickup(host, id, item);
taken.push((item_id, before));
}
Some(rest) if rest.count < before => {
self.guest_pickup(host, id, self.dropped[i].clone());
self.dropped[i].stack = rest;
taken.push((item_id, before - self.dropped[i].stack.count));
}
@@ -765,6 +767,23 @@ impl Game<'_> {
}
}
/// The host's own `ItemPickupParticle` toward the guest's model.
fn guest_pickup(
&mut self,
host: &LanHost,
id: i32,
item: horizon_client::entities::ItemEntity,
) {
use super::pickups::{Collector, Taken, guest_target};
if let Some(target) = guest_target(host, id as u32) {
self.add_pickup_toward(
Taken::Item(Box::new(item)),
Collector::Guest(id as u32),
target,
);
}
}
/// Positional sounds and level events of the tick, for the guests.
pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) {
let sounds = self.audio.capture.take().unwrap_or_default();
+13 -7
View File
@@ -316,11 +316,11 @@ impl Game<'_> {
_ => {}
}
// Entity.thunderHit: burning (8 seconds) and 5 lightning damage.
m.fire_ticks = if m.fire_ticks + 1 == 0 {
160
} else {
m.fire_ticks + 1
};
m.fire_ticks += 1;
if m.fire_ticks == 0 {
m.ignite_for_ticks(160);
}
m.damage(5.0, damage);
}
if !events.is_empty() {
@@ -329,8 +329,14 @@ impl Game<'_> {
if let Some(p) = self.player.as_ref().map(|p| p.position)
&& inside([p.x, p.y, p.z])
{
let fire = &mut self.creatures.player_fire;
*fire = if *fire + 1 == 0 { 160 } else { *fire + 1 };
if let Some(p) = self.player.as_mut() {
p.fire_ticks += 1;
if p.fire_ticks == 0
&& let Err(error) = p.ignite_for_ticks(160)
{
self.error = Some(error);
}
}
self.hurt_player_by("minecraft:lightning_bolt", 5.0);
}
// Dropped items burn up (ItemEntity health 5), save fire-resistant ones.
+351 -6
View File
@@ -138,12 +138,116 @@ fn packed_rgba(packed: u8) -> [u8; 4] {
let ch = |s: u32| ((col >> s & 255) * modifier / 255) as u8;
[ch(16), ch(8), ch(0), 255]
}
/// `has(DataComponents.MAP_ID)`: filled maps and the explorer map items
/// (`buried_treasure_map`, `woodland_mansion_map`, ..., all `MapItem`s).
pub(super) fn map_id(stack: &ItemStack) -> Option<i32> {
if &*stack.item != "minecraft:filled_map" {
return None;
}
stack.data().and_then(|d| d.map_id)
}
/// `MapDecorationTypes`: the sprite of a decoration type that a
/// `minecraft:map_decorations` entry can name.
fn decoration_sprite(id: &str) -> Option<&'static str> {
Some(match id.strip_prefix("minecraft:").unwrap_or(id) {
"player" => "map/decorations/player",
"frame" => "map/decorations/frame",
"red_marker" => "map/decorations/red_marker",
"blue_marker" => "map/decorations/blue_marker",
"target_x" => "map/decorations/target_x",
"target_point" => "map/decorations/target_point",
"player_off_map" => "map/decorations/player_off_map",
"player_off_limits" => "map/decorations/player_off_limits",
"mansion" => "map/decorations/woodland_mansion",
"monument" => "map/decorations/ocean_monument",
"red_x" => "map/decorations/red_x",
"village_desert" => "map/decorations/desert_village",
"village_plains" => "map/decorations/plains_village",
"village_savanna" => "map/decorations/savanna_village",
"village_snowy" => "map/decorations/snowy_village",
"village_taiga" => "map/decorations/taiga_village",
"jungle_temple" => "map/decorations/jungle_temple",
"swamp_hut" => "map/decorations/swamp_hut",
"trial_chambers" => "map/decorations/trial_chambers",
"abandoned_camp" => "map/decorations/abandoned_camp",
"ancient_city" => "map/decorations/ancient_city",
"desert_pyramid" => "map/decorations/desert_pyramid",
"mineshaft" => "map/decorations/mineshaft",
"ocean_ruin_warm" => "map/decorations/warm_ocean_ruins",
_ => return None,
})
}
/// `minecraft:map_decorations` of a map item: (sprite, x, z, rotation), in
/// the component's order.
fn static_decorations(stack: &ItemStack) -> Vec<(&'static str, f64, f64, f32)> {
let Some(Tag::Compound(entries)) = stack.data().and_then(|d| {
d.other
.iter()
.find(|(k, _)| k == "minecraft:map_decorations")
.map(|(_, t)| t)
}) else {
return Vec::new();
};
let number = |t: Option<&Tag>| match t {
Some(Tag::Double(b)) => Some(f64::from_bits(*b)),
Some(Tag::Float(b)) => Some(f64::from(f32::from_bits(*b))),
Some(Tag::Int(v)) => Some(f64::from(*v)),
_ => None,
};
entries
.values()
.filter_map(|e| {
let sprite = match e.get("type") {
Some(Tag::String(s)) => decoration_sprite(&s.to_string_lossy())?,
_ => return None,
};
Some((
sprite,
number(e.get("x"))?,
number(e.get("z"))?,
number(e.get("rotation")).unwrap_or(0.0) as f32,
))
})
.collect()
}
/// `MapItemSavedData.addTargetDecoration`: the `"+"` entry of
/// `minecraft:map_decorations`, rotation 180.
fn target_decoration(decoration: &str, at: [i32; 3]) -> Tag {
Tag::compound([(
"+",
Tag::compound([
("type", Tag::String(decoration.into())),
("x", Tag::Double(f64::from(at[0]).to_bits())),
("z", Tag::Double(f64::from(at[2]).to_bits())),
("rotation", Tag::Float(180.0f32.to_bits())),
]),
)])
}
/// `MapItemSavedData.clampMapCoordinate`.
fn clamp_map_coordinate(d: f32) -> i8 {
if d <= -63.0 {
-128
} else if d >= 63.0 {
127
} else {
(d * 2.0 + 0.5) as i8
}
}
/// `MapItemSavedData.calculateRotation`: spinning in the Nether.
fn decoration_rotation(nether: bool, game_time: i64, y_rot: f64) -> u8 {
if nether {
let s = (game_time / 10) as i32;
(s.wrapping_mul(s)
.wrapping_mul(34_187_121)
.wrapping_add(s.wrapping_mul(121))
>> 15
& 15) as u8
} else {
let adjusted = if y_rot < 0.0 {
y_rot - 8.0
} else {
y_rot + 8.0
};
((adjusted * 16.0 / 360.0) as i32 & 15) as u8
}
}
impl Game<'_> {
fn dimension_id(&self) -> &'static str {
match self.dim {
@@ -199,6 +303,161 @@ impl Game<'_> {
self.maps.data.insert(id, data);
let last = self.maps.last_id.unwrap_or(-1).max(id);
self.maps.last_id = Some(last);
self.render_biome_preview(id);
}
}
/// `ExplorationMapFunction.run` for an item a generated chest still holds
/// unsearched (`structure_blocks::take_pending_map`): the nearest
/// structure of the tag around `origin`, a new map centred on it with its
/// biome preview and target decoration. False when nothing is found: the
/// loot table's `filtered` map_id check would have discarded the item.
pub(super) fn resolve_pending_map(&mut self, item: &mut ItemStack, origin: [f64; 3]) -> bool {
let Some(map) = horizon_client::structure_blocks::take_pending_map(item) else {
return true;
};
let names = self.structure_tag(&map.destination);
let from = origin.map(|v| v.floor() as i32);
let found = self
.end
.locator()
.filter(|_| !names.is_empty())
.and_then(|t| t.locate(&names, from, map.search_radius));
let Some((_, at)) = found else {
return false;
};
let mut data = MapData::fresh(
f64::from(at[0]),
f64::from(at[2]),
map.zoom,
self.dimension_id(),
);
data.unlimited = true;
let id = self.new_map_id(data);
self.render_biome_preview(id);
let d = item.data_mut();
d.map_id = Some(id);
d.other.retain(|(k, _)| k != "minecraft:map_decorations");
d.other.push((
"minecraft:map_decorations".into(),
target_decoration(&map.decoration, at),
));
true
}
/// The unsearched exploration maps of a container being opened
/// (`RandomizableContainer.unpackLootTable` runs the function then).
pub(super) fn resolve_container_maps(&mut self, key: (i32, i32, i32), origin: [f64; 3]) {
use horizon_client::containers::BlockEntity;
let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get(&key) else {
return;
};
let pending: Vec<usize> = slots
.iter()
.enumerate()
.filter(|(_, s)| {
s.as_ref()
.is_some_and(horizon_client::structure_blocks::has_pending_map)
})
.map(|(i, _)| i)
.collect();
for i in pending {
let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get_mut(&key) else {
return;
};
let Some(mut item) = slots[i].take() else {
continue;
};
let keep = self.resolve_pending_map(&mut item, origin);
if let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get_mut(&key) {
slots[i] = keep.then_some(item);
}
}
}
/// `MapItem.renderBiomePreviewMap`: the map's biomes at sea level, water
/// outlines (`#water_on_map_outlines`) drawn in orange and brown.
pub(super) fn render_biome_preview(&mut self, id: i32) {
let Some(terrain) = self.end.locator() else {
return;
};
let dim = self.dimension_id();
let zoom = self.streaming.biome_zoom;
let watery_biomes: std::collections::HashSet<String> = self
.tag_entries("worldgen/biome", "minecraft:water_on_map_outlines")
.into_iter()
.collect();
let Some(m) = self.maps.data.get(&id) else {
return;
};
if m.dimension != dim {
return;
}
let scale = 1i32 << m.scale;
let start_x = m.center[0] / scale - 64;
let start_z = m.center[1] / scale - 64;
let sea_level = 63;
let quarts: Vec<[i32; 3]> = (0..128)
.flat_map(|row| {
(0..128).map(move |column| {
zoom.quart_at_block(horizon_core::position::BlockPos::new(
(start_x + column) * scale,
sea_level,
(start_z + row) * scale,
))
})
})
.collect();
let watery: Vec<bool> = terrain
.noise_biomes(&quarts)
.into_iter()
.map(|b| b.is_some_and(|b| watery_biomes.contains(&b)))
.collect();
let is_watery = |x: i32, z: i32| watery[(z * 128 + x) as usize];
// MapColor ids and MapColor.Brightness ids.
const ORANGE: u8 = 15;
const BROWN: u8 = 26;
const LOW: u8 = 0;
const NORMAL: u8 = 1;
const HIGH: u8 = 2;
const LOWEST: u8 = 3;
let Some(m) = self.maps.data.get_mut(&id) else {
return;
};
for mx in 1..127 {
for mz in 1..127 {
let mut water_count = 0;
for dx in -1..2 {
for dz in -1..2 {
if (dx != 0 || dz != 0) && is_watery(mx + dx, mz + dz) {
water_count += 1;
}
}
}
let mut brightness = LOWEST;
let mut color = 0;
if is_watery(mx, mz) {
color = ORANGE;
if water_count > 7 && mz % 2 == 0 {
let sin = horizon_core::geometry::trig::sin(f64::from(mz as f32 + 0.0));
match (mx + (sin * 7.0) as i32) / 8 % 5 {
0 | 4 => brightness = LOW,
1 | 3 => brightness = NORMAL,
2 => brightness = HIGH,
_ => {}
}
} else if water_count > 7 {
color = 0;
} else if water_count > 5 {
brightness = NORMAL;
} else if water_count > 1 {
brightness = LOW;
}
} else if water_count > 0 {
color = BROWN;
brightness = if water_count > 3 { NORMAL } else { LOWEST };
}
if color != 0 {
m.update_color(mx, mz, color << 2 | brightness);
}
}
}
}
/// Registers `data` under a free map id.
@@ -250,20 +509,33 @@ impl Game<'_> {
let Some(p) = self.player.as_ref().map(|p| p.position) else {
return;
};
// A generated exploration map that reached the inventory unsearched
// (moved out of its chest by a hopper): searched from here.
for i in 0..self.inventory.len() {
if self.inventory[i]
.as_ref()
.is_some_and(horizon_client::structure_blocks::has_pending_map)
&& let Some(mut item) = self.inventory[i].take()
{
let keep = self.resolve_pending_map(&mut item, [p.x, p.y, p.z]);
self.inventory[i] = keep.then_some(item);
}
}
let held: Vec<i32> = [Some(self.selected), Some(super::shield::OFFHAND_SLOT)]
.into_iter()
.flatten()
.filter_map(|i| self.stack_in(i).and_then(map_id))
.collect();
let carried: Vec<i32> = self
let carried: Vec<(i32, Vec<(&'static str, f64, f64, f32)>)> = self
.inventory
.iter()
.chain(std::iter::once(&self.offhand))
.flatten()
.filter_map(map_id)
.filter_map(|s| Some((map_id(s)?, static_decorations(s))))
.collect();
let (yaw, dim) = (self.yaw, self.dimension_id());
for id in carried {
let (nether, game_time) = (self.dim == super::Dim::Nether, self.world.game_time);
for (id, targets) in carried {
let Some(m) = self.map(id) else { continue };
// tickCarriedBy: the player marker while tracking in this dimension.
m.decorations.clear();
@@ -302,6 +574,26 @@ impl Game<'_> {
});
}
}
// The item's MAP_DECORATIONS (an explorer map's target), added
// after the players as addDecoration would.
let s = (1 << m.scale) as f32;
for (sprite, x, z, rotation) in targets {
let dx = (x - f64::from(m.center[0])) as f32 / s;
let dz = (z - f64::from(m.center[1])) as f32 / s;
let inside = (-63.0..=63.0).contains(&dx) && (-63.0..=63.0).contains(&dz);
if !inside && !m.unlimited {
continue;
}
let d = Decoration {
sprite,
x: clamp_map_coordinate(dx),
y: clamp_map_coordinate(dz),
rot: decoration_rotation(nether, game_time, f64::from(rotation)),
};
if !m.decorations.contains(&d) {
m.decorations.push(d);
}
}
}
for id in held {
self.update_map(id);
@@ -663,3 +955,56 @@ impl Game<'_> {
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_target_decoration_type_has_its_sprite() {
// MapDecorationTypes: (name, asset).
for (name, asset) in [
("mansion", "woodland_mansion"),
("monument", "ocean_monument"),
("red_x", "red_x"),
("village_desert", "desert_village"),
("village_plains", "plains_village"),
("village_savanna", "savanna_village"),
("village_snowy", "snowy_village"),
("village_taiga", "taiga_village"),
("jungle_temple", "jungle_temple"),
("swamp_hut", "swamp_hut"),
("trial_chambers", "trial_chambers"),
("abandoned_camp", "abandoned_camp"),
("ancient_city", "ancient_city"),
("desert_pyramid", "desert_pyramid"),
("mineshaft", "mineshaft"),
("ocean_ruin_warm", "warm_ocean_ruins"),
] {
assert_eq!(
decoration_sprite(&format!("minecraft:{name}")),
Some(format!("map/decorations/{asset}").as_str()),
"{name}"
);
}
assert_eq!(decoration_sprite("minecraft:nothing"), None);
}
#[test]
fn target_decorations_read_back_with_vanilla_rotation() {
let mut stack = ItemStack::new("minecraft:buried_treasure_map", 1);
stack.data_mut().map_id = Some(3);
stack.data_mut().other.push((
"minecraft:map_decorations".into(),
target_decoration("minecraft:red_x", [120, 40, -300]),
));
assert_eq!(map_id(&stack), Some(3));
let found = static_decorations(&stack);
assert_eq!(found, vec![("map/decorations/red_x", 120.0, -300.0, 180.0)]);
// calculateRotation(180): (byte) (188 * 16 / 360) = 8.
assert_eq!(decoration_rotation(false, 0, 180.0), 8);
assert_eq!(decoration_rotation(false, 0, -90.0), 12);
assert_eq!(clamp_map_coordinate(-70.0), -128);
assert_eq!(clamp_map_coordinate(10.25), 21);
}
}
+2
View File
@@ -112,6 +112,7 @@ impl Game<'_> {
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
let assets = std::sync::Arc::new(self.res.assets.reload(root)?);
let mut atlas = HudAtlas::build(root)?;
let panorama = horizon_client::gfx::panorama::Faces::load(root);
atlas.font.uniform = self.settings.force_unicode;
atlas.font.japanese = self.settings.japanese_glyphs;
let item_renderer = horizon_client::item_render::ItemRenderer::load(root)?;
@@ -137,6 +138,7 @@ impl Game<'_> {
self.res.assets = assets;
self.res.context = context.clone();
self.res.atlas = atlas;
self.res.panorama = panorama;
self.res.item_renderer = std::sync::Arc::new(item_renderer);
self.res.clouds = super::load_clouds(root);
self.res.forcefield = super::load_forcefield(root);
+161 -25
View File
@@ -298,6 +298,14 @@ impl Game<'_> {
}
let crouching = p.pose == Pose::Crouching;
let (position, flying) = (p.position, p.flying || p.fall_flying);
let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity);
let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0);
let charged = self.inventory[self.selected]
.as_ref()
.is_some_and(|s| s.data().is_some_and(|d| !d.charged.is_empty()));
let charge_duration = self.inventory[self.selected]
.as_ref()
.map_or(25, |s| Self::charge_ticks(s).max(1)) as i32;
let attack = (self.swing.old_animation, self.swing.animation);
let swinging = self.swing.swinging();
let (yaw, pitch) = (self.yaw, self.pitch);
@@ -357,6 +365,14 @@ impl Game<'_> {
m.extra.off_hand = off;
m.extra.crouching = crouching;
m.extra.passenger = riding;
m.velocity = velocity;
m.extra.fall_flying = fall_flying;
m.extra.fall_fly_ticks = fly_ticks;
m.extra.main_hand_left = self.settings.main_hand_left;
m.extra.using_item = using;
m.extra.charged = charged;
m.extra.ints[5] = charge_duration;
m.extra.elytra.tick(fall_flying, crouching, velocity);
m.hurt_time = hurt;
}
/// Whether the player's own model shows in the world view.
@@ -401,6 +417,7 @@ impl Game<'_> {
&self.player_armor_layers(),
out,
);
self.player_elytra_geometry(m, camera, alpha as f32, packed, out);
self.held_item_geometry(m, camera, alpha, packed, true, out);
}
/// `extractEntityInInventoryFollowsMouse`: the player in the box
@@ -455,6 +472,7 @@ impl Game<'_> {
&self.player_armor_layers(),
&mut verts,
);
self.player_elytra_geometry(&m, camera, 1.0, 240 | 240 << 8, &mut verts);
self.held_item_geometry(&m, camera, 1.0, 240 | 240 << 8, false, &mut verts);
let height = if m.extra.crouching { 1.5 } else { 1.8 };
// PictureInPictureRenderer: the box centre, (size, size, -size);
@@ -464,31 +482,12 @@ impl Game<'_> {
* glam::Mat4::from_translation(glam::Vec3::new(0.0, height / 2.0 + offset_y, 0.0))
* glam::Mat4::from_rotation_z(std::f32::consts::PI)
* glam::Mat4::from_rotation_x((y_angle * 20.0).to_radians());
let mut quads: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
for q in verts.as_chunks::<4>().0 {
let p: [glam::Vec3; 4] =
std::array::from_fn(|i| gui.transform_point3(glam::Vec3::from_array(q[i].pos)));
let n = (p[1] - p[0]).cross(p[2] - p[0]);
// The winding gives inward normals: faces with n.z >= 0 point away.
if n.z >= 0.0 {
continue;
}
let n = n.normalize_or_zero();
// Lighting.Entry.ENTITY_IN_UI, roughly: lit from the front and above.
let shade = (0.55 + 0.45 * -n.z - 0.15 * n.y).clamp(0.4, 1.0);
let c = q[0].color;
let ch = |s: u32| ((((c >> s) & 255) as f32 * shade) as u32) << s;
let color = (c & 0xFF00_0000) | ch(0) | ch(8) | ch(16);
let depth = p.iter().map(|v| v.z).sum::<f32>() / 4.0;
quads.push((
depth,
p.map(|v| [v.x, v.y]),
std::array::from_fn(|i| q[i].uv),
color,
));
}
// Far (low z) first: the viewer is on the +z side.
quads.sort_by(|a, b| a.0.total_cmp(&b.0));
let fire = self
.player
.as_ref()
.filter(|p| p.fire_ticks > 0 && !p.spectator)
.map(|p| (p.dimensions.width, p.dimensions.height));
let quads = player_preview_quads(verts, gui, fire, &atlas.sprites);
let start = batch.vertices.len();
for (_, p, uv, color) in quads {
batch.quad(p, uv, color);
@@ -510,3 +509,140 @@ impl Game<'_> {
}
}
}
impl Game<'_> {
fn player_elytra_geometry(
&self,
m: &Mob,
camera: glam::DVec3,
partial: f32,
light: u32,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
let Some(asset) = self.armor[1]
.as_ref()
.and_then(|s| self.res.items.get(&s.item))
.and_then(|i| i.equip_asset.as_ref())
else {
return;
};
let assets = &self.armor_stand_assets;
let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else {
return;
};
let (Some(model), Some(rect)) = (
assets.player.get("elytra"),
self.res.atlas.sprites.get(texture),
) else {
return;
};
let base = horizon_client::mobs::render::base_transform(m, partial, camera)
* glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.0, 0.125));
let angles = m.extra.elytra.angles(partial);
horizon_client::mobs::render_model(
model,
base,
&|part| {
let mut p = part.pose;
if part.name == "left_wing" || part.name == "right_wing" {
let invert = if part.name == "left_wing" { 1.0 } else { -1.0 };
p[1] = if m.extra.crouching { 3.0 } else { 0.0 };
p[3] = angles[0];
p[4] = invert * angles[1];
p[5] = invert * angles[2];
}
p
},
[rect.u0, rect.v0, rect.u1, rect.v1],
light,
0,
out,
);
}
}
fn player_preview_quads(
mut verts: Vec<horizon_client::mesher::Vertex>,
gui: glam::Mat4,
fire: Option<(f32, f32)>,
sprites: &std::collections::HashMap<String, horizon_client::hud::Rect>,
) -> Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> {
let flame_start = verts.len();
if let Some((width, height)) = fire {
horizon_client::fire_render::flames(
[0.0; 3],
width,
height,
glam::DVec3::ZERO,
0.0,
sprites,
0xff,
&mut verts,
);
}
let mut quads: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
for (index, q) in verts.as_chunks::<4>().0.iter().enumerate() {
let p: [glam::Vec3; 4] =
std::array::from_fn(|i| gui.transform_point3(glam::Vec3::from_array(q[i].pos)));
let n = (p[1] - p[0]).cross(p[2] - p[0]);
// The winding gives inward normals: faces with n.z >= 0 point away.
if n.z >= 0.0 {
continue;
}
let n = n.normalize_or_zero();
// Lighting.Entry.ENTITY_IN_UI, roughly: lit from the front and above.
let shade = if index * 4 >= flame_start {
1.0
} else {
(0.55 + 0.45 * -n.z - 0.15 * n.y).clamp(0.4, 1.0)
};
let c = q[0].color;
let ch = |s: u32| ((((c >> s) & 255) as f32 * shade) as u32) << s;
let color = (c & 0xFF00_0000) | ch(0) | ch(8) | ch(16);
let depth = p.iter().map(|v| v.z).sum::<f32>() / 4.0;
quads.push((
depth,
p.map(|v| [v.x, v.y]),
std::array::from_fn(|i| q[i].uv),
color,
));
}
// Far (low z) first: the viewer is on the +z side.
quads.sort_by(|a, b| a.0.total_cmp(&b.0));
quads
}
#[cfg(test)]
mod preview_tests {
use super::*;
#[test]
fn burning_inventory_preview_keeps_visible_fullbright_flames() {
let rect = |u0| horizon_client::hud::Rect {
u0,
v0: 0.0,
u1: u0 + 0.1,
v1: 0.1,
w: 16,
h: 16,
};
let sprites = std::collections::HashMap::from([
("block/fire_0".into(), rect(0.0)),
("block/fire_1".into(), rect(0.5)),
]);
for pitch in [-30.0f32, 0.0, 30.0] {
let gui = glam::Mat4::from_scale(glam::Vec3::new(30.0, 30.0, -30.0))
* glam::Mat4::from_rotation_z(std::f32::consts::PI)
* glam::Mat4::from_rotation_x(pitch.to_radians());
assert!(player_preview_quads(Vec::new(), gui, None, &sprites).is_empty());
let quads = player_preview_quads(Vec::new(), gui, Some((0.6, 1.8)), &sprites);
assert!(
!quads.is_empty(),
"inventory projection must not cull all flames"
);
assert!(quads.iter().all(|q| q.3 == 0xffff_ffff));
assert!(quads.iter().any(|q| q.2[0][0] <= 0.1));
assert!(quads.iter().any(|q| q.2[0][0] >= 0.5));
assert!(quads.windows(2).all(|q| q[0].0 <= q[1].0));
}
}
}
+185
View File
@@ -0,0 +1,185 @@
//! `ItemPickupParticle`: a taken item entity, experience orb or arrow flies
//! into whoever took it over three ticks (`ClientPacketListener.handleTakeItemEntity`
//! adds one for every `ClientboundTakeItemEntityPacket`), drawn with the render
//! state it had when it was taken (`extractEntity(from, 1.0F)`).
use super::Game;
use horizon_client::{
entities::{ExperienceOrb, ItemEntity},
projectiles::Projectile,
};
/// `ItemPickupParticle.LIFE_TIME`.
const LIFE_TIME: u32 = 3;
/// The taken entity, as it was when taken.
pub(super) enum Taken {
Item(Box<ItemEntity>),
Orb(Box<ExperienceOrb>),
Arrow(Box<Projectile>),
}
impl Taken {
/// The render state's position: the entity's at partial tick 1.
fn position(&self) -> [f64; 3] {
let p = match self {
Taken::Item(i) => i.position,
Taken::Orb(o) => o.position,
Taken::Arrow(a) => a.position,
};
[p.x, p.y, p.z]
}
}
/// Whoever took it: the particle's `target`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Collector {
Player,
/// A mob, or another player on a server (both kept as mobs here).
Mob(u32),
/// A LAN guest, by entity id (the host draws it as a model).
Guest(u32),
}
pub(super) struct Pickup {
pub taken: Taken,
collector: Collector,
life: u32,
target: [f64; 3],
target_old: [f64; 3],
}
/// `ParticleEngine`'s ITEM_PICKUP group and the particles waiting to join it.
#[derive(Default)]
pub(super) struct Pickups {
pub live: Vec<Pickup>,
added: Vec<Pickup>,
}
impl Pickups {
pub fn clear(&mut self) {
self.live.clear();
self.added.clear();
}
}
/// `ItemPickupParticleGroup.ParticleInstance.fromParticle`: the position at
/// `partial`, from the taken entity's to the collector's (lerped between ticks)
/// along the square of the particle's age.
pub(super) fn position(p: &Pickup, partial: f64) -> [f64; 3] {
let time = (p.life as f32 + partial as f32) / LIFE_TIME as f32;
let time = f64::from(time * time);
let from = p.taken.position();
std::array::from_fn(|i| {
let target = p.target_old[i] + partial * (p.target[i] - p.target_old[i]);
from[i] + time * (target - from[i])
})
}
/// A LAN guest's target, from the model the host draws for it.
pub(super) fn guest_target(host: &super::lan::LanHost, id: u32) -> Option<[f64; 3]> {
let m = host.models.values().find(|m| m.id == id)?;
let (p, eye) = (m.position, m.eye_height());
Some([p.x, (p.y + (p.y + eye)) / 2.0, p.z])
}
impl Game<'_> {
/// `ItemPickupParticle.updatePosition`: the collector's x and z, halfway up to its eyes.
fn collector_target(&self, collector: Collector) -> Option<[f64; 3]> {
let (p, eye) = match collector {
Collector::Player => {
let p = self.player.as_ref()?;
(p.position, f64::from(p.dimensions.eye_height))
}
Collector::Mob(id) => {
let m = self.mobs.iter().find(|m| m.id == id)?;
(m.position, m.eye_height())
}
Collector::Guest(id) => {
return guest_target(self.lan.as_ref()?, id);
}
};
Some([p.x, (p.y + (p.y + eye)) / 2.0, p.z])
}
/// `handleTakeItemEntity`: `particleEngine.add(new ItemPickupParticle(...))` when the
/// collector is known; it joins the group at the end of the next particle tick.
pub(super) fn add_pickup(&mut self, taken: Taken, collector: Collector) {
if let Some(target) = self.collector_target(collector) {
self.add_pickup_toward(taken, collector, target);
}
}
/// [`Self::add_pickup`] with the collector's first target given (a LAN
/// guest's model while the host is taken out for its tick).
pub(super) fn add_pickup_toward(
&mut self,
taken: Taken,
collector: Collector,
target: [f64; 3],
) {
self.pickups.added.push(Pickup {
taken,
collector,
life: 0,
target,
target_old: target,
});
}
/// `ParticleEngine.tick` for the ITEM_PICKUP group: age (removed at
/// `LIFE_TIME`), follow the collector, then let the new particles in.
pub(super) fn tick_pickups(&mut self) {
let mut live = std::mem::take(&mut self.pickups.live);
live.retain_mut(|p| {
p.life += 1;
if p.life == LIFE_TIME {
return false;
}
p.target_old = p.target;
if let Some(t) = self.collector_target(p.collector) {
p.target = t;
}
true
});
live.append(&mut self.pickups.added);
self.pickups.live = live;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn orb_at(x: f64, y: f64, z: f64) -> Taken {
let at = horizon_core::geometry::Vec3::new(x, y, z);
Taken::Orb(Box::new(ExperienceOrb {
position: at,
previous: at,
velocity: horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0),
value: 1,
age: 0,
on_ground: false,
}))
}
#[test]
fn flies_along_the_square_of_its_age_to_the_moving_target() {
let mut p = Pickup {
taken: orb_at(0.0, 64.0, 0.0),
collector: Collector::Player,
life: 0,
target: [3.0, 65.0, 0.0],
target_old: [3.0, 65.0, 0.0],
};
// Added this tick: still at the orb.
assert_eq!(position(&p, 0.0), [0.0, 64.0, 0.0]);
// Halfway through the first tick: (0.5 / 3)^2 of the way.
let t = (0.5f32 / 3.0) * (0.5 / 3.0);
let mid = position(&p, 0.5);
assert!((mid[0] - 3.0 * f64::from(t)).abs() < 1e-9, "{mid:?}");
// Last tick before removal, the target moved: lerped between its ticks.
p.life = 2;
p.target_old = [3.0, 65.0, 0.0];
p.target = [4.0, 65.0, 0.0];
let end = position(&p, 1.0);
assert!(
(end[0] - 4.0).abs() < 1e-9 && (end[1] - 65.0).abs() < 1e-9,
"{end:?}"
);
}
}
@@ -64,6 +64,11 @@ impl Game<'_> {
}
// Nuggets come whole, anything else one at a time.
let item = e.stack.item.clone();
let (taken_item, id) = (e.clone(), self.mobs[i].id);
self.add_pickup(
super::pickups::Taken::Item(Box::new(taken_item)),
super::pickups::Collector::Mob(id),
);
let taken = if &*item == "minecraft:gold_nugget" {
self.dropped.remove(j).stack.count
} else {
+1 -2
View File
@@ -57,8 +57,7 @@ pub(super) struct PotionState {
applied: Vec<(&'static str, &'static str, f64, &'static str)>,
/// Armor the protection table was computed for.
protection_for: Option<Vec<Option<ItemStack>>>,
/// Mobs set on fire by fire aspect: (mob id, ticks left).
pub(super) burning: Vec<(u32, i32)>,
/// Enchantment attribute modifiers on the player: (attribute, id, amount, operation).
pub(super) enchant_modifiers: Vec<(String, String, f64, String)>,
}
@@ -42,7 +42,7 @@ impl Game<'_> {
};
let entered = std::mem::take(&mut player.powder_snow_entered);
let at = [player.position.x, player.position.y, player.position.z];
if entered.is_empty() || self.creatures.player_fire <= 0 {
if entered.is_empty() || player.fire_ticks <= 0 {
return Ok(());
}
for pos in entered {
@@ -50,7 +50,9 @@ impl Game<'_> {
self.world.modified.insert((pos.x >> 4, pos.z >> 4));
}
self.process_level_events()?;
self.creatures.player_fire = 0;
if let Some(player) = self.player.as_mut() {
player.fire_ticks = 0;
}
// Entity.playEntityOnFireExtinguishedSound
let r = self.particles.random();
let pitch = 1.6 + (r.next_float() - r.next_float()) * 0.4;
+9
View File
@@ -770,6 +770,7 @@ impl Game<'_> {
.map(|(i, e)| (i, e.position))
.collect();
let mut taken: Vec<usize> = Vec::new();
let mut collectors: Vec<(usize, u32)> = Vec::new();
let mut recruit: Vec<(i32, Vec3)> = Vec::new();
let mut joins: Vec<(u32, i32, f32)> = Vec::new();
let mut new_leaders: Vec<(i32, i32, u32)> = Vec::new();
@@ -868,6 +869,7 @@ impl Game<'_> {
if p.distance_squared(position) < 1.414 * 1.414 {
// pickUpItem: the banner becomes the wave's leader.
taken.push(*i);
collectors.push((*i, m.id));
leaders.insert((id, s.wave));
new_leaders.push((id, s.wave, m.id));
s.banner_at = None;
@@ -878,6 +880,13 @@ impl Game<'_> {
}
}
}
for (i, mob) in collectors {
let item = self.dropped[i].clone();
self.add_pickup(
super::pickups::Taken::Item(Box::new(item)),
super::pickups::Collector::Mob(mob),
);
}
taken.sort_unstable();
for i in taken.into_iter().rev() {
self.dropped.remove(i);
+18
View File
@@ -186,6 +186,7 @@ impl Game<'_> {
self.creatures.projectiles.clear();
self.dropped.clear();
self.particles.clear();
self.pickups.clear();
self.orbs.clear();
self.falling.clear();
self.travelling = None;
@@ -278,6 +279,7 @@ impl Game<'_> {
self.mobs.clear();
self.dropped.clear();
self.particles.clear();
self.pickups.clear();
self.score.board = Default::default();
self.tab_list = Default::default();
self.border = Default::default();
@@ -469,6 +471,7 @@ impl Game<'_> {
self.mobs.clear();
self.dropped.clear();
self.particles.clear();
self.pickups.clear();
if let Some(r) = self.remote.as_mut() {
r.entities.clear();
r.lerps.clear();
@@ -982,6 +985,19 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch);
}
// ItemPickupParticle toward the collector (this player, another one or a mob).
if let Some(item) = self.dropped.iter().find(|d| d.id == p.item as u32).cloned() {
let collector = if self
.remote
.as_ref()
.is_some_and(|r| r.entity_id == p.player)
{
super::pickups::Collector::Player
} else {
super::pickups::Collector::Mob(p.player as u32)
};
self.add_pickup(super::pickups::Taken::Item(Box::new(item)), collector);
}
self.remove_entity(p.item);
}
C::HurtAnimation(p) => {
@@ -1555,6 +1571,8 @@ impl Game<'_> {
let at = Vec3::new(p[0], p[1], p[2]);
let bob_offset = self.world.random.next_float() * std::f32::consts::PI * 2.0;
self.dropped.push(ItemEntity {
health: 5,
fire_ticks: 0,
id: id as u32,
stack,
position: at,
@@ -179,7 +179,9 @@ impl Game<'_> {
partial,
block_overlay,
water,
on_fire: false,
on_fire: self.camera_type.first_person()
&& !self.spectator()
&& self.player.as_ref().is_some_and(|p| p.fire_ticks > 0),
gui_overlays: &gui_overlays,
})
}
@@ -331,6 +333,7 @@ impl Game<'_> {
.map(|p| ([p.position.x, p.position.y, p.position.z], p.velocity.y)),
};
self.particles.tick(&level);
self.tick_pickups();
for (name, at, volume, pitch) in std::mem::take(&mut self.particles.sounds) {
self.audio.play(name, Some(at), volume, pitch);
}
+1 -1
View File
@@ -10,7 +10,7 @@ use std::collections::BTreeMap;
#[derive(Default)]
pub(super) struct Stats {
pub(super) values: BTreeMap<String, BTreeMap<String, i32>>,
loaded: bool,
pub(super) loaded: bool,
/// Ticks until the phantom spawner runs again.
phantom_tick: i32,
/// Statistic changes (type, key, amount; `None` = reset) for the
@@ -126,6 +126,11 @@ impl Game<'_> {
continue;
}
let item = e.stack.item.clone();
let (taken_item, id) = (e.clone(), self.mobs[i].id);
self.add_pickup(
super::pickups::Taken::Item(Box::new(taken_item)),
super::pickups::Collector::Mob(id),
);
let e = &mut self.dropped[j];
e.stack.count -= 1;
if e.stack.count == 0 {
+305 -35
View File
@@ -31,6 +31,78 @@ impl PrimedTnt {
),
)
}
fn tick(
&mut self,
world: &horizon_client::world::World,
collision: &horizon_world::block_collision::BlockCollisionRegistry<'_>,
assets: &horizon_client::assets::Assets,
facts: &horizon_client::blocks::BlockFacts,
) -> Result<()> {
self.previous = self.position;
self.velocity.y -= 0.04;
let mut scene = SceneCollisions {
world,
binding: collision,
subject: None,
};
let wanted = self.velocity;
let moved = scene
.resolve(self.bounds(), wanted, 0.0, self.on_ground)
.unwrap_or(Vec3::ZERO);
self.position = Vec3::new(
self.position.x + moved.x,
self.position.y + moved.y,
self.position.z + moved.z,
);
self.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
if moved.x != wanted.x {
self.velocity.x = 0.0;
}
if moved.z != wanted.z {
self.velocity.z = 0.0;
}
if moved.y != wanted.y {
self.velocity.y = 0.0;
}
self.velocity = Vec3::new(
self.velocity.x * 0.98,
self.velocity.y * 0.98,
self.velocity.z * 0.98,
);
if self.on_ground {
self.velocity = Vec3::new(
self.velocity.x * 0.7,
self.velocity.y * -0.5,
self.velocity.z * 0.7,
);
}
self.fuse -= 1;
if self.fuse > 0 {
// PrimedTnt updates immersion after moving and decrementing its fuse.
let mut fluids =
horizon_world::entity_fluid::EntityFluidInteraction::new([WATER, LAVA]);
let mut fluid_world = TntFluidWorld {
tnt: self,
world,
assets,
facts,
};
fluids
.update(&mut fluid_world, false, 4096)
.map_err(|e| std::io::Error::other(e.to_string()))?;
fluids.apply_current(&mut fluid_world, WATER, 0.014)?;
fluids.apply_current(
&mut fluid_world,
LAVA,
if world.fast_lava {
0.007
} else {
0.0023333333333333335
},
)?;
}
Ok(())
}
}
impl Game<'_> {
@@ -83,41 +155,12 @@ impl Game<'_> {
let mut i = 0;
while i < count {
let t = &mut self.tnts[i];
t.previous = t.position;
t.velocity.y -= 0.04;
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
let wanted = t.velocity;
let moved = scene
.resolve(t.bounds(), wanted, 0.0, t.on_ground)
.unwrap_or(Vec3::ZERO);
t.position = Vec3::new(
t.position.x + moved.x,
t.position.y + moved.y,
t.position.z + moved.z,
);
t.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
if moved.x != wanted.x {
t.velocity.x = 0.0;
}
if moved.z != wanted.z {
t.velocity.z = 0.0;
}
if moved.y != wanted.y {
t.velocity.y = 0.0;
}
t.velocity = Vec3::new(
t.velocity.x * 0.98,
t.velocity.y * 0.98,
t.velocity.z * 0.98,
);
if t.on_ground {
t.velocity = Vec3::new(t.velocity.x * 0.7, t.velocity.y * -0.5, t.velocity.z * 0.7);
}
t.fuse -= 1;
t.tick(
&self.world,
self.collision,
&self.res.assets,
&self.res.facts,
)?;
if t.fuse <= 0 {
let center = [
t.position.x,
@@ -269,3 +312,230 @@ impl Game<'_> {
}
}
}
use horizon_world::{
entity_fluid::{
CurrentTarget, FluidInteractionWorld, FluidMembership, FluidSections, FluidTagId,
},
fluid::{FluidHeightWorld, FluidKind, FluidState},
fluid_flow::{FluidFlowWorld, flow_at},
};
const WATER: FluidTagId = FluidTagId(0);
const LAVA: FluidTagId = FluidTagId(1);
struct TntFluidWorld<'a> {
tnt: &'a mut PrimedTnt,
world: &'a horizon_client::world::World,
assets: &'a horizon_client::assets::Assets,
facts: &'a horizon_client::blocks::BlockFacts,
}
impl TntFluidWorld<'_> {
fn state(&self, p: BlockPos) -> horizon_world::registry::BlockStateId {
self.world.block(p.x, p.y, p.z)
}
fn fluid_at(&self, p: BlockPos) -> std::io::Result<FluidState> {
FluidState::from_block(
self.assets
.registry
.state(self.state(p))
.ok_or_else(|| std::io::Error::other("missing TNT fluid state"))?,
)
}
}
impl FluidMembership for TntFluidWorld<'_> {
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
match tag {
WATER => matches!(kind, FluidKind::Water | FluidKind::FlowingWater),
LAVA => matches!(kind, FluidKind::Lava | FluidKind::FlowingLava),
_ => false,
}
}
}
impl CurrentTarget for TntFluidWorld<'_> {
type Error = std::io::Error;
fn is_player_class(&self) -> bool {
false
}
fn velocity(&mut self) -> std::io::Result<Vec3> {
Ok(self.tnt.velocity)
}
fn add_delta_movement(&mut self, v: Vec3) -> std::io::Result<()> {
self.tnt.velocity = Vec3::new(
self.tnt.velocity.x + v.x,
self.tnt.velocity.y + v.y,
self.tnt.velocity.z + v.z,
);
Ok(())
}
}
impl FluidInteractionWorld for TntFluidWorld<'_> {
type Error = std::io::Error;
type Chunk = (i32, i32);
fn interaction_box(&mut self) -> std::io::Result<Option<Aabb>> {
Ok(Some(
self.tnt.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)),
))
}
fn loaded_chunk(&mut self, x: i32, z: i32) -> std::io::Result<Option<Self::Chunk>> {
Ok(self.world.chunks.contains_key(&(x, z)).then_some((x, z)))
}
fn chunk_sections(&mut self, _: Self::Chunk) -> std::io::Result<FluidSections<'_>> {
static SECTIONS: [bool; horizon_client::chunk::SECTIONS] =
[true; horizon_client::chunk::SECTIONS];
Ok(FluidSections {
minimum_section_y: horizon_client::chunk::MIN_Y / 16,
has_fluid: &SECTIONS,
})
}
fn bounding_box_min_y(&self) -> f64 {
self.tnt.position.y
}
fn block_x(&self) -> i32 {
self.tnt.position.x.floor() as i32
}
fn block_z(&self) -> i32 {
self.tnt.position.z.floor() as i32
}
fn eye_y(&mut self) -> std::io::Result<f64> {
Ok(self.tnt.position.y + f64::from(0.98f32 * 0.85f32))
}
fn fluid_state(&mut self, p: BlockPos) -> std::io::Result<FluidState> {
self.fluid_at(p)
}
fn fluid_height(&mut self, s: FluidState, p: BlockPos) -> std::io::Result<f32> {
s.height_at(self, [p.x, p.y, p.z])
}
fn camera_height(&mut self, s: FluidState, p: BlockPos) -> std::io::Result<f32> {
s.camera_height_at(self, [p.x, p.y, p.z])
}
fn flow(&mut self, s: FluidState, p: BlockPos) -> std::io::Result<Vec3> {
flow_at(self, s, p)
}
}
impl FluidHeightWorld for TntFluidWorld<'_> {
type Error = std::io::Error;
fn fluid(&mut self, p: [i32; 3]) -> std::io::Result<FluidState> {
self.fluid_at(BlockPos::new(p[0], p[1], p[2]))
}
fn sturdy_down(&mut self, p: [i32; 3]) -> std::io::Result<bool> {
Ok(self
.facts
.get(self.state(BlockPos::new(p[0], p[1], p[2])))
.sturdy_full
& 1
!= 0)
}
}
impl FluidFlowWorld for TntFluidWorld<'_> {
type Error = std::io::Error;
type Block = horizon_world::registry::BlockStateId;
fn fluid(&mut self, p: BlockPos) -> std::io::Result<FluidState> {
self.fluid_at(p)
}
fn block(&mut self, p: BlockPos) -> std::io::Result<Self::Block> {
Ok(self.state(p))
}
fn blocks_fluid_flow(&self, s: Self::Block) -> bool {
self.assets
.blocks_fluid_flow
.contains(&self.assets.registry.state(s).unwrap().name)
}
fn is_ice_class(&self, s: Self::Block) -> bool {
self.facts
.get(s)
.classes
.iter()
.any(|c| c.as_ref() == "IceBlock")
}
fn is_face_sturdy(
&mut self,
s: Self::Block,
_: BlockPos,
d: horizon_core::geometry::Direction,
) -> std::io::Result<bool> {
Ok(self.facts.get(s).sturdy_full & (1 << d as u8) != 0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn primed_tnt_follows_water_currents_after_moving() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = horizon_client::assets::Assets::load(&root).unwrap();
let facts = horizon_client::blocks::BlockFacts::load(&root, assets.registry).unwrap();
let collision = horizon_client::collisions::load(&root, assets.registry).unwrap();
let mut world = horizon_client::world::World::test_scene(&assets, 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..=22 {
for z in 19..=21 {
world.set(x, 3, z, stone).unwrap();
}
}
world.set(20, 4, 20, water).unwrap();
world.set(21, 4, 20, flowing).unwrap();
let at = Vec3::new(20.5, 4.0, 20.5);
let mut tnt = PrimedTnt {
position: at,
previous: at,
velocity: Vec3::ZERO,
fuse: 80,
on_ground: false,
};
tnt.tick(&world, &collision, &assets, &facts).unwrap();
assert_eq!(
tnt.position.x, at.x,
"current is applied after motion, not before"
);
assert!(
(tnt.velocity.x - 0.014).abs() < 1e-12,
"water must push primed TNT east: {:?}",
tnt.velocity
);
assert_eq!(tnt.fuse, 79);
tnt.tick(&world, &collision, &assets, &facts).unwrap();
assert!((tnt.position.x - at.x - 0.014).abs() < 1e-12);
assert!(tnt.on_ground);
tnt.position = at;
tnt.velocity = Vec3::ZERO;
tnt.fuse = 1;
tnt.tick(&world, &collision, &assets, &facts).unwrap();
assert_eq!(tnt.fuse, 0);
assert_eq!(
tnt.velocity.x, 0.0,
"expired TNT must not receive a current"
);
world.set(21, 4, 20, water).unwrap();
tnt.position = at;
tnt.velocity = Vec3::ZERO;
tnt.fuse = 80;
tnt.tick(&world, &collision, &assets, &facts).unwrap();
assert_eq!(
tnt.velocity.x, 0.0,
"still water must not add horizontal motion"
);
world
.set(
20,
3,
20,
assets.registry.default_state("minecraft:air").unwrap(),
)
.unwrap();
tnt.on_ground = false;
tnt.velocity = Vec3::ZERO;
tnt.tick(&world, &collision, &assets, &facts).unwrap();
assert!(
tnt.position.y < at.y && tnt.velocity.y < 0.0,
"TNT sinks; water does not add buoyancy"
);
}
}
+1 -1
View File
@@ -89,8 +89,8 @@ impl merchant::MapMaker for GameMaps<'_> {
self.made
.borrow_mut()
.push((id, at, map.zoom, map.decoration.clone()));
// The trade's own map item (woodland_mansion_map, ...) keeps its id.
let mut out = stack;
out.item = std::sync::Arc::from("minecraft:filled_map");
let d = out.data_mut();
d.map_id = Some(id);
d.other.push((
@@ -293,7 +293,15 @@ impl Game<'_> {
j += 1;
continue;
}
let before = self.dropped[j].clone();
let rest = villager::ext_mut(&mut self.mobs[i]).add_item(stack, max);
if rest.as_ref().is_none_or(|r| r.count < before.stack.count) {
let id = self.mobs[i].id;
self.add_pickup(
super::pickups::Taken::Item(Box::new(before)),
super::pickups::Collector::Mob(id),
);
}
match rest {
None => {
self.dropped.remove(j);
+110 -26
View File
@@ -83,6 +83,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6]
mod arena;
mod occlusion;
pub mod panorama;
mod timing;
mod world_post;
@@ -137,7 +138,7 @@ pub struct Frame<'a> {
/// Skip sections the camera cannot see through open faces (vanilla's
/// occlusion graph; off in spectator-like views inside blocks).
pub cave_culling: bool,
/// Title screen: only the panorama (in `celestial`) and the HUD.
/// Title screen: only the dedicated panorama cube map and the HUD.
pub title: bool,
/// Dimensions without a skybox (the Nether) clear to the fog colour.
pub skybox: bool,
@@ -246,6 +247,7 @@ pub struct Renderer {
additive_pipeline: wgpu::RenderPipeline,
celestial_pipeline: wgpu::RenderPipeline,
celestial_buffer: wgpu::Buffer,
panorama: panorama::Panorama,
/// `RenderPipelines.WORLD_BORDER` and its buffers.
border_pipeline: wgpu::RenderPipeline,
border_group: wgpu::BindGroup,
@@ -277,6 +279,7 @@ pub struct Renderer {
sprite_mips: Vec<crate::mipmap::Settings>,
/// Edge length of the block sprite array's layers.
sprite_size: u32,
sprite_minimum_size: u32,
indices: wgpu::Buffer,
index_quads: u32,
instances: wgpu::Buffer,
@@ -396,11 +399,13 @@ impl Renderer {
offscreen: bool,
sprite_pixels: &[u8],
sprite_size: u32,
sprite_minimum_size: u32,
layers: u32,
sprite_mips: &[crate::mipmap::Settings],
animations: &[SpriteAnimation],
hud_atlas: (&[u8], u32, u32),
forcefield: (&[u8], u32),
panorama_faces: &panorama::Faces,
) -> Result<Self> {
let instance =
wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
@@ -1361,6 +1366,12 @@ impl Renderer {
.features()
.contains(wgpu::Features::INDIRECT_FIRST_INSTANCE);
let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix());
let panorama = panorama::Panorama::new(
&device,
&queue,
config.format.remove_srgb_suffix(),
panorama_faces,
);
Ok(Self {
instance,
surface,
@@ -1389,6 +1400,7 @@ impl Renderer {
additive_pipeline,
celestial_pipeline,
celestial_buffer,
panorama,
border_pipeline,
border_group,
border_uniform,
@@ -1414,6 +1426,7 @@ impl Renderer {
animations: animations.iter().map(|a| (a.clone(), usize::MAX)).collect(),
sprite_mips: sprite_mips.to_vec(),
sprite_size,
sprite_minimum_size,
indices,
index_quads,
instances,
@@ -1658,7 +1671,12 @@ impl Renderer {
/// The Mipmap Levels option: block textures sample at most `levels`
/// reduced copies (0: none).
pub fn set_mipmap_levels(&mut self, levels: u32) {
let levels = levels.min(self.mip_levels - 1);
let levels = sprite_mipmap_limit(
levels,
self.sprite_texture.width(),
self.sprite_minimum_size,
self.mip_levels,
);
if levels == self.mipmaps {
return;
}
@@ -1785,23 +1803,13 @@ impl Renderer {
);
}
fn animate(&mut self, tick: u64) {
for (animation, previous) in &mut self.animations {
let frame = animation.frame(tick);
if frame == *previous {
continue;
}
*previous = frame;
let (mips, levels) = mip_chain(
animation.pixels(frame),
self.sprite_size,
&self.sprite_mips,
animation.layer,
1,
);
let mut offset = 0;
for level in 0..levels.min(self.mip_levels) {
let size = self.sprite_size >> level;
let bytes = (size * size * 4) as usize;
animate_sprites(
&mut self.animations,
tick,
self.sprite_size,
self.mip_levels,
&self.sprite_mips,
|layer, level, size, pixels| {
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.sprite_texture,
@@ -1809,11 +1817,11 @@ impl Renderer {
origin: wgpu::Origin3d {
x: 0,
y: 0,
z: animation.layer,
z: layer,
},
aspect: wgpu::TextureAspect::All,
},
&mips[offset..offset + bytes],
pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(size * 4),
@@ -1825,9 +1833,8 @@ impl Renderer {
depth_or_array_layers: 1,
},
);
offset += bytes;
}
}
},
);
}
pub fn render(&mut self, frame: &Frame) -> Result<bool> {
if self.suspended {
@@ -1866,6 +1873,7 @@ impl Renderer {
};
if self.animated_textures {
self.animate(frame.ticks);
self.hud.animate_fire(&self.queue, frame.ticks);
}
self.update_lightmap(
&frame.sky,
@@ -1875,6 +1883,15 @@ impl Renderer {
frame.block_flicker,
);
let view_proj = self.view_projection(frame);
if frame.title {
self.panorama.prepare(
&self.queue,
self.config.width,
self.config.height,
frame.yaw,
frame.pitch,
);
}
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
let view = crate::camera::view_matrix(frame.yaw, frame.pitch);
let sun_angle = frame.sky.sun_angle.to_radians();
@@ -2221,12 +2238,15 @@ impl Renderer {
Some(f) => f.sky_end > 2.0,
None => !frame.underwater,
};
if sky_visible && (frame.skybox || frame.end_sky) {
if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) {
if !frame.title && frame.skybox {
pass.set_pipeline(&self.sky);
pass.draw(0..3, 0..1);
}
if celestial_vertices > 0 {
if frame.title {
self.panorama.draw(&mut pass);
pass.set_bind_group(0, &self.group, &[]);
} else if celestial_vertices > 0 {
pass.set_pipeline(&self.celestial_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
@@ -2691,3 +2711,67 @@ mod tests {
assert!(super::outline_vertices(&[], glam::DVec3::ZERO).is_empty());
}
}
pub(crate) fn sprite_mipmap_limit(requested: u32, size: u32, minimum: u32, available: u32) -> u32 {
// Only the atlas native minimum determines how many resampling-only mips to skip.
let upscale = (size / minimum.max(1)).max(1).ilog2();
requested.saturating_add(upscale).min(available - 1)
}
fn animate_sprites(
animations: &mut [(crate::sprites::SpriteAnimation, usize)],
tick: u64,
size: u32,
max_levels: u32,
settings: &[crate::mipmap::Settings],
mut write: impl FnMut(u32, u32, u32, &[u8]),
) {
for (animation, previous) in animations {
let frame = animation.frame(tick);
if frame == *previous {
continue;
}
*previous = frame;
let (mips, levels) = mip_chain(animation.pixels(frame), size, settings, animation.layer, 1);
let mut offset = 0;
for level in 0..levels.min(max_levels) {
let edge = size >> level;
let bytes = (edge * edge * 4) as usize;
write(animation.layer, level, edge, &mips[offset..offset + bytes]);
offset += bytes;
}
}
}
#[cfg(test)]
mod sprite_upload_tests {
use super::*;
#[test]
fn mipmap_option_keeps_real_16px_reductions() {
for levels in 0..=4 {
assert_eq!(sprite_mipmap_limit(levels, 32, 16, 6), levels + 1);
assert_eq!(sprite_mipmap_limit(levels, 16, 16, 5), levels);
}
}
#[test]
fn animation_updates_entire_layer_every_mip_once() {
for size in [16, 32] {
let animation = crate::sprites::test_animation(size, 7);
let pixels = animation.pixels(animation.frame(1)).to_vec();
let settings = [];
let (expected, levels) = mip_chain(&pixels, size, &settings, 7, 1);
let mut animations = vec![(animation, 0)];
let mut writes = Vec::new();
let mut record = |layer, level, edge, data: &[u8]| {
assert_eq!(layer, 7);
assert_eq!(edge, size >> level);
assert_eq!(data.len(), (edge * edge * 4) as usize);
writes.push(data.to_vec());
};
animate_sprites(&mut animations, 0, size, levels, &settings, &mut record);
animate_sprites(&mut animations, 1, size, levels, &settings, &mut record);
animate_sprites(&mut animations, 1, size, levels, &settings, &mut record);
assert_eq!(writes.len(), levels as usize);
assert_eq!(writes[0], pixels);
assert_eq!(writes.concat(), expected);
}
}
}
+346
View File
@@ -0,0 +1,346 @@
//! Vanilla 26.3's CubeMapTexture and CubeMap, separate from the pixel-filtered GUI atlas.
use crate::{Result, hud::decode};
use glam::Mat4;
use std::path::Path;
use wgpu::util::DeviceExt;
/// Native cube order: +X, -X, +Y, -Y, +Z, -Z (CubeMapTexture.SUFFIXES).
const FACE_ORDER: [u8; 6] = [1, 3, 5, 4, 0, 2];
#[derive(Debug)]
pub struct Faces {
pub size: u32,
pub pixels: Vec<u8>,
}
impl Faces {
pub fn load(root: &Path) -> Self {
Self::try_load(root).unwrap_or_else(|error| {
log::warn!("Horizon: title panorama unavailable ({error})");
Self {
size: 1,
pixels: [96, 110, 111, 255].repeat(6),
}
})
}
fn try_load(root: &Path) -> Result<Self> {
let background = root.join("assets/minecraft/textures/gui/title/background");
let mut size = 0;
let mut pixels = Vec::new();
for face in FACE_ORDER {
let path = background.join(format!("panorama_{face}.png"));
let (w, h, data) = decode(&path)?;
if w != h || (size != 0 && w != size) {
return Err(format!(
"{}: panorama faces must be equally sized squares",
path.display()
)
.into());
}
size = w;
// CubeMapTexture copies each original image with flipY=true. Keep every texel.
for row in data.chunks_exact((w * 4) as usize).rev() {
pixels.extend_from_slice(row);
}
}
Ok(Self { size, pixels })
}
}
fn projection(width: u32, height: u32, yaw: f32, pitch: f32) -> Mat4 {
// CubeMap.render: 85-degree FOV, near/far 0.05/10, rotationX(PI), rotateX, rotateY.
Mat4::perspective_rh(
85.0f32.to_radians(),
width as f32 / height.max(1) as f32,
0.05,
10.0,
) * Mat4::from_rotation_x(std::f32::consts::PI)
* Mat4::from_rotation_x(pitch.to_radians())
* Mat4::from_rotation_y(yaw.to_radians())
}
pub(super) struct Panorama {
pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
}
impl Panorama {
pub(super) fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
faces: &Faces,
) -> Self {
let texture = device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
label: Some("Title panorama cube"),
size: wgpu::Extent3d {
width: faces.size,
height: faces.size,
depth_or_array_layers: 6,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&faces.pixels,
);
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::Cube),
..Default::default()
});
// CubeMapTexture's blur=true metadata: linear minification and magnification, no mips.
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Title panorama linear filtering"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Title panorama projection"),
size: 64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Title panorama bindings"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::Cube,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Title panorama resources"),
layout: &layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Title panorama shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("panorama.wgsl").into()),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Title panorama layout"),
bind_group_layouts: &[Some(&layout)],
..Default::default()
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Title panorama"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_panorama"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(false),
depth_compare: Some(wgpu::CompareFunction::Always),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_panorama"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
Self {
pipeline,
group,
uniform,
}
}
pub(super) fn prepare(
&self,
queue: &wgpu::Queue,
width: u32,
height: u32,
yaw: f32,
pitch: f32,
) {
queue.write_buffer(
&self.uniform,
0,
bytemuck::cast_slice(&projection(width, height, yaw, pitch).to_cols_array()),
);
}
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.group, &[]);
pass.draw(0..36, 0..1);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{
fs,
sync::atomic::{AtomicU32, Ordering},
};
struct Fixture(std::path::PathBuf);
impl Fixture {
fn new(size: u32) -> Self {
static NEXT: AtomicU32 = AtomicU32::new(0);
let root = std::env::temp_dir().join(format!(
"horizon-panorama-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed),
));
let fixture = Self(root);
fs::create_dir_all(fixture.background()).unwrap();
for face in 0..6 {
fixture.write(face, size, size);
}
fixture
}
fn background(&self) -> std::path::PathBuf {
self.0
.join("assets/minecraft/textures/gui/title/background")
}
fn write(&self, face: u8, w: u32, h: u32) {
let file =
fs::File::create(self.background().join(format!("panorama_{face}.png"))).unwrap();
let mut encoder = png::Encoder::new(file, w, h);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let pixels: Vec<u8> = (0..h)
.flat_map(|y| {
(0..w).flat_map(move |x| [face, (x % 251) as u8, (y % 253) as u8, 255])
})
.collect();
encoder
.write_header()
.unwrap()
.write_image_data(&pixels)
.unwrap();
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn original_resolution_texels_and_vanilla_cube_orientation_are_preserved() {
let f = Fixture::new(1024);
let faces = Faces::try_load(&f.0).unwrap();
assert_eq!(faces.size, 1024);
assert_eq!(faces.pixels.len(), 6 * 1024 * 1024 * 4);
// CubeMapTexture's actual layer suffixes, with each source row flipped vertically.
for (layer, source_face) in [1, 3, 5, 4, 0, 2].into_iter().enumerate() {
for y in 0..1024 {
for x in 0..1024 {
let at = ((layer * 1024 + y) * 1024 + x) * 4;
assert_eq!(
faces.pixels[at..at + 4],
[source_face, (x % 251) as u8, ((1023 - y) % 253) as u8, 255]
);
}
}
}
}
#[test]
fn placeholders_load_and_incomplete_or_mismatched_cubes_fall_back() {
let f = Fixture::new(1);
assert_eq!(Faces::try_load(&f.0).unwrap().size, 1);
f.write(5, 2, 1);
assert!(
Faces::try_load(&f.0)
.unwrap_err()
.to_string()
.contains("equally sized squares")
);
let fallback = Faces::load(&f.0);
assert_eq!(fallback.pixels.len(), 24);
f.write(5, 2, 2);
assert!(Faces::try_load(&f.0).is_err());
fs::remove_file(f.background().join("panorama_5.png")).unwrap();
assert!(Faces::try_load(&f.0).is_err());
assert_eq!(Faces::load(&f.0).size, 1);
}
#[test]
fn cube_shader_validates() {
let module = naga::front::wgsl::parse_str(include_str!("panorama.wgsl")).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
}
#[test]
fn vanilla_camera_centres_the_positive_z_face_and_pitches_ten_degrees() {
let straight = projection(1920, 1080, 0.0, 0.0) * glam::Vec4::new(0.0, 0.0, 1.0, 1.0);
assert!((straight.x / straight.w).abs() < 1e-6);
assert!((straight.y / straight.w).abs() < 1e-6);
assert!(straight.w > 0.0);
let pitched = projection(1920, 1080, 0.0, 10.0) * glam::Vec4::new(0.0, 0.0, 1.0, 1.0);
let expected_y = 10.0f32.to_radians().tan() / 42.5f32.to_radians().tan();
assert!((pitched.y / pitched.w - expected_y).abs() < 1e-6);
}
}
@@ -0,0 +1,30 @@
// CubeMap's position-only cube and panorama.vsh/fsh: sample its untransformed direction.
struct Projection { view_proj: mat4x4<f32> }
@group(0) @binding(0) var<uniform> projection: Projection;
@group(0) @binding(1) var panorama: texture_cube<f32>;
@group(0) @binding(2) var panorama_sampler: sampler;
struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) direction: vec3<f32>,
}
@vertex fn vs_panorama(@builtin(vertex_index) index: u32) -> Out {
let corners = array<vec3<f32>, 8>(
vec3(-1.0, -1.0, -1.0), vec3(1.0, -1.0, -1.0),
vec3(1.0, 1.0, -1.0), vec3(-1.0, 1.0, -1.0),
vec3(-1.0, -1.0, 1.0), vec3(1.0, -1.0, 1.0),
vec3(1.0, 1.0, 1.0), vec3(-1.0, 1.0, 1.0),
);
let indices = array<u32, 36>(
4, 7, 6, 4, 6, 5, 5, 6, 2, 5, 2, 1,
1, 2, 3, 1, 3, 0, 0, 3, 7, 0, 7, 4,
7, 3, 2, 7, 2, 6, 0, 4, 5, 0, 5, 1,
);
let position = corners[indices[index]];
var out: Out;
out.clip = projection.view_proj * vec4(position, 1.0);
out.direction = position;
return out;
}
@fragment fn fs_panorama(in: Out) -> @location(0) vec4<f32> {
return textureSample(panorama, panorama_sampler, in.direction);
}
+44 -2
View File
@@ -76,6 +76,18 @@ impl HealthResources {
.expect("validated landing source")
}
}
/// `DamageEffects.sound()` by its serialized id: what `Player.getHurtSound`
/// plays for a damage type's `effects` (unknown ids fall back to `hurt`, the codec default).
pub fn hurt_sound(effects: &str) -> &'static str {
match effects {
"drowning" => "minecraft:entity.player.hurt_drown",
"burning" => "minecraft:entity.player.hurt_on_fire",
"poking" => "minecraft:entity.player.hurt_sweet_berry_bush",
"freezing" => "minecraft:entity.player.hurt_freeze",
// HURT and THORNS (both SoundEvents.PLAYER_HURT).
_ => "minecraft:entity.player.hurt",
}
}
#[derive(Clone, Copy, Debug)]
pub enum HealthEvent {
StarvationDamage(f32),
@@ -97,6 +109,11 @@ pub enum HealthEvent {
amount: f32,
},
Phase(&'static str),
/// `ServerLevel.broadcastDamageEvent`: the client's
/// `LivingEntity.handleDamageEvent` plays the source's hurt sound.
DamageBroadcast {
source: DamageTypeId,
},
Criterion {
original: f32,
amount: f32,
@@ -119,6 +136,7 @@ impl HealthEvent {
format!("record-damage {:08x}", amount.to_bits())
}
Self::Phase(name) => name.into(),
Self::DamageBroadcast { .. } => "broadcast-damage".into(),
Self::Criterion { .. } => "hurt-criterion".into(),
}
}
@@ -559,7 +577,10 @@ impl HurtWorld for Environment<'_> {
Ok(())
}
fn broadcast_damage(&mut self, _: &mut State) -> io::Result<()> {
self.phase("broadcast-damage")
self.event(HealthEvent::DamageBroadcast {
source: self.source.type_id(),
});
Ok(())
}
fn mark_hurt(&mut self, _: &mut State) -> io::Result<()> {
*self.sync_velocity = true;
@@ -596,7 +617,10 @@ impl HurtWorld for Environment<'_> {
self.phase("death-request")
}
fn hurt_sound(&mut self, _: &mut State) -> io::Result<()> {
self.phase("hurt-sound")
self.phase("hurt-sound")?;
let sound = hurt_sound(&self.source.definition().effects);
self.events.push(MotionEvent::HurtSound(sound));
Ok(())
}
fn game_time(&mut self, _: &mut State) -> io::Result<i64> {
Ok(self.game_time)
@@ -655,3 +679,21 @@ impl ServerPlayerHurtWorld for Environment<'_> {
Ok(true)
}
}
#[cfg(test)]
mod tests {
#[test]
fn hurt_sounds_follow_damage_effects() {
// DamageEffects: HURT, THORNS, DROWNING, BURNING, POKING, FREEZING.
for (effects, sound) in [
("hurt", "minecraft:entity.player.hurt"),
("thorns", "minecraft:entity.player.hurt"),
("drowning", "minecraft:entity.player.hurt_drown"),
("burning", "minecraft:entity.player.hurt_on_fire"),
("poking", "minecraft:entity.player.hurt_sweet_berry_bush"),
("freezing", "minecraft:entity.player.hurt_freeze"),
] {
assert_eq!(super::hurt_sound(effects), sound, "{effects}");
}
}
}
+94 -18
View File
@@ -23,6 +23,7 @@ pub struct HudAtlas {
pub width: u32,
pub height: u32,
pub sprites: HashMap<String, Rect>,
pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>,
/// The default font (bitmap sheets in this atlas, unifont rasterized on demand).
pub font: crate::font::Font,
white: Rect,
@@ -151,9 +152,7 @@ impl HudAtlas {
walk(&textures.join("map"), &mut files);
files.retain(|p| {
let s = p.to_string_lossy();
(!s.contains("title/background") || s.contains("panorama_"))
&& !s.contains("realms")
&& !s.contains("presets")
!s.contains("title/background") && !s.contains("realms") && !s.contains("presets")
});
let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec<u8>)> {
let name = path
@@ -170,18 +169,6 @@ impl HudAtlas {
} else {
pixels
};
// Title panorama faces are downsampled to 256 for the shared atlas.
if name.contains("panorama_") && w >= 512 && w == h {
let step = (w / 256) as usize;
let mut small = Vec::with_capacity(256 * 256 * 4);
for y in 0..256usize {
for x in 0..256usize {
let i = ((y * step) * w as usize + x * step) * 4;
small.extend_from_slice(&pixels[i..i + 4]);
}
}
return Some((name, 256, 256, small));
}
(w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels))
};
let threads = std::thread::available_parallelism().map_or(2, |n| n.get());
@@ -199,6 +186,15 @@ impl HudAtlas {
.collect()
});
images.extend(atlas_sprites(root, &images));
// The title screen's "JAVA EDITION" banner reads "RUST EDITION".
if let Some(edition) = images
.iter_mut()
.find(|i| i.0 == crate::title_edition::SPRITE)
&& let Some(pixels) =
crate::title_edition::rust_edition(edition.1, edition.2, &edition.3)
{
edition.3 = pixels;
}
images.push(("horizon/white".into(), 4, 4, vec![255; 64]));
// Map textures (game/maps.rs) are written into these slots at run time.
for i in 0..MAP_SLOTS {
@@ -266,6 +262,35 @@ impl HudAtlas {
},
);
}
let mut fire_sprites = crate::sprites::Sprites::default();
let mut fire_animations = Vec::new();
for name in [
"block/fire_0",
"block/fire_1",
"block/soul_fire_0",
"block/soul_fire_1",
] {
if let Some(rect) = sprites.get(name).copied() {
let layer = fire_sprites.insert(root, &format!("minecraft:{name}"))?;
if let Some(animation) = fire_sprites
.animations
.iter()
.find(|a| a.layer == layer)
.cloned()
{
let image = animation.resized_pixels(animation.frame(0), rect.w, rect.h);
let x = (rect.u0 * width as f32).round() as usize;
let y = (rect.v0 * height as f32).round() as usize;
for row in 0..rect.h as usize {
let dst = ((y + row) * width as usize + x) * 4;
let src = row * rect.w as usize * 4;
pixels[dst..dst + rect.w as usize * 4]
.copy_from_slice(&image[src..src + rect.w as usize * 4]);
}
fire_animations.push((rect, animation));
}
}
}
let white = sprites["horizon/white"];
let font = crate::font::Font::load(
root,
@@ -280,6 +305,7 @@ impl HudAtlas {
width,
height,
sprites,
fire_animations,
font,
white,
})
@@ -643,6 +669,7 @@ struct HudUniform {
size: [f32; 4],
}
pub struct HudRenderer {
pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation, usize)>,
/// The shared atlas texture, for run-time glyph uploads.
pub atlas_texture: Option<wgpu::Texture>,
pipeline: wgpu::RenderPipeline,
@@ -728,7 +755,7 @@ impl HudRenderer {
..Default::default()
});
let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4];
let create = |label, blend| {
let create = |label, blend, fragment_entry| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
@@ -747,7 +774,7 @@ impl HudRenderer {
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
entry_point: Some(fragment_entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
@@ -759,7 +786,7 @@ impl HudRenderer {
cache: None,
})
};
let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING);
let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING, "fs_main");
// BlendFunction.INVERT: ONE_MINUS_DST_COLOR, ONE_MINUS_SRC_COLOR,
// ONE, ZERO.
let invert_pipeline = create(
@@ -776,6 +803,7 @@ impl HudRenderer {
operation: wgpu::BlendOperation::Add,
},
},
"fs_crosshair",
);
let capacity = 1 << 16;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
@@ -786,6 +814,7 @@ impl HudRenderer {
});
Ok(Self {
atlas_texture: None,
fire_animations: Vec::new(),
pipeline,
invert_pipeline,
group,
@@ -794,6 +823,42 @@ impl HudRenderer {
capacity,
})
}
pub fn animate_fire(&mut self, queue: &wgpu::Queue, tick: u64) {
let Some(texture) = &self.atlas_texture else {
return;
};
for (rect, animation, previous) in &mut self.fire_animations {
let frame = animation.frame(tick);
if frame == *previous {
continue;
}
let pixels = animation.resized_pixels(frame, rect.w, rect.h);
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: (rect.u0 * texture.width() as f32).round() as u32,
y: (rect.v0 * texture.height() as f32).round() as u32,
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
&pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(rect.w * 4),
rows_per_image: Some(rect.h),
},
wgpu::Extent3d {
width: rect.w,
height: rect.h,
depth_or_array_layers: 1,
},
);
*previous = frame;
}
}
pub fn draw(
&mut self,
device: &wgpu::Device,
@@ -951,6 +1016,17 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn hud_shader_validates_both_fragment_entries() {
let module = naga::front::wgsl::parse_str(include_str!("hud.wgsl")).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
}
#[test]
fn inverted_ranges_split_the_draws_in_order() {
let mut batch = HudBatch::new([854, 480]);
+5
View File
@@ -26,3 +26,8 @@ struct Out {
if c.a < 0.004 { discard; }
return c;
}
@fragment fn fs_crosshair(in: Out) -> @location(0) vec4<f32> {
let c = textureSample(atlas, atlas_sampler, in.uv) * in.color;
if c.a == 0.0 { discard; }
return c;
}
+143
View File
@@ -41,6 +41,7 @@ pub struct ToolRule {
}
#[derive(Clone, Debug)]
pub struct ItemInfo {
pub fire_resistant: bool,
pub id: Arc<str>,
pub max_stack: u32,
pub max_damage: u32,
@@ -48,6 +49,7 @@ pub struct ItemInfo {
pub tool: Vec<ToolRule>,
pub tool_default_speed: f32,
pub food: Option<(u32, f32)>,
pub consumable: bool,
pub model: String,
/// Main-hand `attack_damage` / `attack_speed` modifier amounts.
pub attack_damage: f32,
@@ -331,6 +333,26 @@ fn entity_spec(tags: &HashMap<String, HashSet<String>>, spec: &str) -> HashSet<S
}
}
impl Items {
pub fn resists_fire(&self, stack: &ItemStack, source: &str) -> bool {
if let Some(data) = stack.data()
&& let Some((_, v)) = data
.other
.iter()
.find(|(key, _)| key == "minecraft:damage_resistant")
{
return match v.get("types") {
Some(horizon_world::nbt::Tag::String(tag)) => {
tag.to_string().is_ok_and(|id|id=="#minecraft:is_fire" || id==source)
}
Some(horizon_world::nbt::Tag::List(tags)) => tags.iter().any(
|t| matches!(t,horizon_world::nbt::Tag::String(id) if id.to_string().is_ok_and(|id|id==source)),
),
_ => false,
};
}
self.get(&stack.item).is_some_and(|i| i.fire_resistant)
}
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new();
for (i, s) in facts.states.iter().enumerate() {
@@ -394,6 +416,8 @@ impl Items {
items.insert(
id.clone(),
ItemInfo {
fire_resistant: c["minecraft:damage_resistant"]["types"].as_str()
== Some("#minecraft:is_fire"),
id: id.clone(),
max_stack: c["minecraft:max_stack_size"].as_u64().unwrap_or(64) as u32,
max_damage: c["minecraft:max_damage"].as_u64().unwrap_or(0) as u32,
@@ -403,6 +427,7 @@ impl Items {
.as_f64()
.unwrap_or(1.0) as f32,
food,
consumable: c.get("minecraft:consumable").is_some(),
model: c["minecraft:item_model"]
.as_str()
.unwrap_or(name)
@@ -1264,6 +1289,94 @@ impl LootContext<'_> {
}
}
/// `DispensibleContainerItem`: shared contents for hand use and dispensers.
pub fn bucket_contents(
item: &str,
) -> Option<(horizon_world::level::BucketContent, &str, Option<&str>)> {
use horizon_world::{fluid::FluidKind, level::BucketContent as C};
Some(match item {
"minecraft:water_bucket" => (
C::Fluid(FluidKind::Water),
"minecraft:item.bucket.empty",
None,
),
"minecraft:lava_bucket" => (
C::Fluid(FluidKind::Lava),
"minecraft:item.bucket.empty_lava",
None,
),
"minecraft:powder_snow_bucket" => {
(C::Powder, "minecraft:item.bucket.empty_powder_snow", None)
}
"minecraft:cod_bucket" => (C::MobWater, "minecraft:item.bucket.empty_fish", Some("cod")),
"minecraft:salmon_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_fish",
Some("salmon"),
),
"minecraft:pufferfish_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_fish",
Some("pufferfish"),
),
"minecraft:tropical_fish_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_fish",
Some("tropical_fish"),
),
"minecraft:axolotl_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_axolotl",
Some("axolotl"),
),
"minecraft:tadpole_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_tadpole",
Some("tadpole"),
),
"minecraft:sulfur_cube_bucket" => (
C::Nothing,
"minecraft:item.bucket.empty_sulfur_cube",
Some("sulfur_cube"),
),
_ => return None,
})
}
#[cfg(test)]
mod bucket_use_tests {
use super::*;
#[test]
fn every_filled_bucket_has_the_native_content_and_sound() {
use horizon_world::level::BucketContent as C;
assert_eq!(
bucket_contents("minecraft:powder_snow_bucket"),
Some((C::Powder, "minecraft:item.bucket.empty_powder_snow", None))
);
assert_eq!(
bucket_contents("minecraft:tadpole_bucket"),
Some((
C::MobWater,
"minecraft:item.bucket.empty_tadpole",
Some("tadpole")
))
);
assert_eq!(
bucket_contents("minecraft:sulfur_cube_bucket"),
Some((
C::Nothing,
"minecraft:item.bucket.empty_sulfur_cube",
Some("sulfur_cube")
))
);
for id in ["cod", "salmon", "pufferfish", "tropical_fish", "axolotl"] {
assert!(bucket_contents(&format!("minecraft:{id}_bucket")).is_some());
}
assert!(bucket_contents("minecraft:bucket").is_none());
assert!(bucket_contents("minecraft:milk_bucket").is_none());
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1358,3 +1471,33 @@ mod tests {
);
}
}
pub fn take_held_drop(slot: &mut Option<ItemStack>, all: bool) -> Option<ItemStack> {
let stack = slot.as_mut()?;
if stack.count == 0 {
return None;
}
let count = if all { stack.count } else { 1 };
let thrown = ItemStack {
count,
..stack.clone()
};
stack.count -= count;
if stack.count == 0 {
*slot = None;
}
Some(thrown)
}
#[cfg(test)]
mod held_drop_tests {
use super::*;
#[test]
fn one_all_and_empty_drop() {
let mut slot = Some(ItemStack::new("minecraft:stone", 4));
assert_eq!(take_held_drop(&mut slot, false).unwrap().count, 1);
assert_eq!(slot.as_ref().unwrap().count, 3);
assert_eq!(take_held_drop(&mut slot, true).unwrap().count, 3);
assert!(slot.is_none());
assert!(take_held_drop(&mut slot, false).is_none());
}
}
+3
View File
@@ -53,6 +53,7 @@ pub mod extras;
pub mod extras_hud;
pub mod fast_hash;
pub mod fastutil_order;
pub mod fire_render;
pub mod first_person;
pub mod flatgen;
pub mod fog;
@@ -101,6 +102,7 @@ pub mod music;
pub mod nbt_path;
pub mod net;
pub mod nether_portal;
pub mod offline_name;
pub mod options_file;
pub mod options_fixes;
pub mod options_horizon;
@@ -145,6 +147,7 @@ pub mod tab_list;
pub mod testgen;
pub mod text;
pub mod title;
pub mod title_edition;
pub mod ui;
pub mod ui_theme;
pub mod vanillagen;
+2 -21
View File
@@ -643,13 +643,7 @@ pub trait MapMaker {
) -> ItemStack;
}
/// An `exploration_map` function's settings.
pub struct ExplorationMap {
pub destination: String,
pub decoration: String,
pub zoom: u8,
pub search_radius: i32,
pub skip_existing_chunks: bool,
}
pub use horizon_world::loot::ExplorationMap;
fn int_provider<R: RandomSource>(v: &Value, random: &mut R) -> i32 {
match v {
Value::Number(n) => n.as_i64().unwrap_or(0) as i32,
@@ -953,20 +947,7 @@ impl Trades {
let Some(maps) = ctx.maps else {
return Some((stack, 0));
};
let map = ExplorationMap {
destination: m["destination"]
.as_str()
.unwrap_or("#minecraft:on_treasure_maps")
.trim_start_matches('#')
.to_owned(),
decoration: m["decoration"]
.as_str()
.unwrap_or("minecraft:mansion")
.to_owned(),
zoom: m["zoom"].as_u64().unwrap_or(2) as u8,
search_radius: m["search_radius"].as_i64().unwrap_or(50) as i32,
skip_existing_chunks: m["skip_existing_chunks"].as_bool().unwrap_or(true),
};
let map = ExplorationMap::from_json(m);
Some((maps.exploration_map(stack, &map, ctx.origin), 0))
}
_ => Some((stack, 0)),
+93
View File
@@ -10,6 +10,7 @@ pub mod allay;
pub mod anim;
pub mod animal_brain;
pub mod aquatic;
pub mod axolotl;
pub mod body_anim;
pub mod brain;
pub mod breeze;
@@ -677,6 +678,10 @@ pub struct Extra {
pub legs: Option<Arc<str>>,
pub feet: Option<Arc<str>>,
pub using_item: i32,
pub fall_flying: bool,
pub fall_fly_ticks: i32,
pub main_hand_left: bool,
pub elytra: ElytraAnimation,
pub flag: bool,
pub flag2: bool,
/// Species scratch values (the wither's head targets and clocks).
@@ -714,6 +719,7 @@ pub struct Extra {
pub villager: Option<Box<villager::Ext>>,
/// The sniffer's and the ghastling's brain.
pub animal_brain: Option<Box<animal_brain::Brain>>,
pub axolotl: axolotl::Animation,
/// The mob this one rides, and the mob riding it (`getVehicle`, `getFirstPassenger`).
pub mount: Option<u32>,
pub rider: Option<u32>,
@@ -800,6 +806,8 @@ pub struct Mob {
pub invulnerable_flag: bool,
pub climbing: bool,
pub fire_ticks: i32,
pub ticks_frozen: i32,
pub glowing: bool,
pub air: i32,
pub last_hurt: f32,
pub last_damage: Option<(Damage, i64)>,
@@ -968,6 +976,8 @@ pub enum MobEvent {
at: [f64; 3],
amount: u32,
},
/// Regeneration support after an axolotl-assisted kill.
AxolotlSupportPlayer,
/// Apply an effect to the player (witch potions, bee stings, cave spider poison).
EffectPlayer {
effect: &'static str,
@@ -1125,6 +1135,9 @@ pub struct SpawnSetup {
/// A snapshot of another entity mobs can see this tick.
#[derive(Clone, Debug)]
pub struct Seen {
pub in_water: bool,
pub playing_dead: bool,
pub last_damage: Option<Damage>,
pub id: u32,
pub species: Species,
pub position: Vec3,
@@ -1177,12 +1190,30 @@ pub struct Seen {
pub stats: [f64; 3],
}
impl Mob {
pub fn burning_time(&self) -> f64 {
let base = finalize::value(self, finalize::Attr::BurningTime);
let protection: u32 = gear::ARMOR
.into_iter()
.map(|slot| gear::level(self, slot, "minecraft:fire_protection"))
.sum();
(base - 0.15 * f64::from(protection)).max(0.0)
}
pub fn ignite_for_ticks(&mut self, ticks: i32) {
self.fire_ticks = self
.fire_ticks
.max((f64::from(ticks) * self.burning_time()).ceil() as i32);
self.ticks_frozen = 0;
}
/// What other mobs see of this one this tick (`player`: the player's
/// UUID, which villagers' reputation is keyed by).
pub fn seen(&self, player: Option<[i32; 4]>) -> Seen {
let m = self;
let villager = m.species() == Species::Villager;
Seen {
in_water: self.fluids.in_water,
playing_dead: axolotl::is_playing_dead(self),
last_damage: self.last_damage.map(|(d, _)| d),
id: m.id,
species: m.species(),
position: m.position,
@@ -1435,6 +1466,8 @@ impl Mob {
invulnerable_flag: false,
climbing: false,
fire_ticks: 0,
ticks_frozen: 0,
glowing: false,
air: 300,
last_hurt: 0.0,
last_damage: None,
@@ -1545,6 +1578,7 @@ impl Mob {
source: Damage,
armor_effectiveness: Option<&mut dyn FnMut(f32) -> f32>,
) -> bool {
axolotl::before_damage(self, amount, &source);
raider::note_hurt(self);
if !self.alive() || self.removed || self.invulnerable_flag {
return false;
@@ -1936,3 +1970,62 @@ mod lighting_tests {
);
}
}
/// `LivingEntity.elytraAnimationState`: eased wing angles and render interpolation.
#[derive(Clone, Copy, Debug, Default)]
pub struct ElytraAnimation {
pub old: [f32; 3],
pub angles: [f32; 3],
}
impl ElytraAnimation {
pub fn tick(&mut self, flying: bool, crouching: bool, velocity: horizon_core::geometry::Vec3) {
use std::f32::consts::PI;
self.old = self.angles;
let target = if flying {
let length =
(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z)
.sqrt();
let ratio = if velocity.y < 0.0 && length > 0.0 {
1.0 - horizon_core::jmath::pow(-velocity.y / length, 1.5) as f32
} else {
1.0
};
[
PI / 12.0 + (PI / 9.0 - PI / 12.0) * ratio,
0.0,
-PI / 12.0 + (-PI / 2.0 + PI / 12.0) * ratio,
]
} else if crouching {
[PI * 2.0 / 9.0, 0.08726646, -PI / 4.0]
} else {
[PI / 12.0, 0.0, -PI / 12.0]
};
for (angle, target) in self.angles.iter_mut().zip(target) {
*angle += (target - *angle) * 0.3;
}
}
pub fn angles(&self, partial: f32) -> [f32; 3] {
std::array::from_fn(|i| self.old[i] + (self.angles[i] - self.old[i]) * partial)
}
}
#[cfg(test)]
mod elytra_tests {
use super::*;
#[test]
fn wings_ease_between_ground_flight_and_crouch() {
let mut wings = ElytraAnimation::default();
wings.tick(false, false, Vec3::ZERO);
assert!((wings.angles[0] - std::f32::consts::PI / 12.0 * 0.3).abs() < 0.000001);
assert_eq!(wings.angles(0.0), wings.old);
assert_eq!(wings.angles(1.0), wings.angles);
for _ in 0..40 {
wings.tick(true, false, Vec3::new(1.0, 0.0, 0.0));
}
assert!((wings.angles[2] + std::f32::consts::FRAC_PI_2).abs() < 0.00001);
for _ in 0..40 {
wings.tick(false, true, Vec3::ZERO);
}
assert!((wings.angles[1] - 0.08726646).abs() < 0.00001);
}
}
+37 -6
View File
@@ -126,7 +126,8 @@ pub fn family(s: Species) -> Family {
| S::Salmon
| S::TropicalFish
| S::Pufferfish
| S::Dolphin => Family::Aquatic,
| S::Dolphin
| S::Axolotl => Family::Aquatic,
S::Giant => Family::Inert,
S::Witch => Family::Witch,
S::Wolf | S::Cat => Family::Tame,
@@ -381,6 +382,7 @@ pub fn tick(
}
events.append(&mut m.outbox);
m.update_walk_animation();
super::axolotl::tick_animation(m);
m.anim.end_tick(m.ai.swinging);
tick_swing(m);
if m.species() == Species::CopperGolem {
@@ -409,6 +411,20 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.fluids.in_water {
m.fall_distance = 0.0;
}
let fire = crate::motion::environment::fire_contact(w.world, w.registry, m.bounds());
if fire > 0.0 {
m.ticks_frozen = 0;
}
if fire > 0.0 && !m.kind.flags.fire_immune {
let multiplier = m.burning_time();
m.fire_ticks = crate::motion::environment::ignite_contact(
m.fire_ticks,
false,
&mut m.random,
multiplier,
);
m.damage(fire, Damage::of(DamageKind::InFire));
}
// Fire: water extinguishes, lava ignites, burning hurts every second.
if m.fluids.in_water && m.fire_ticks > 0 {
m.fire_ticks = 0;
@@ -420,12 +436,12 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
));
}
if m.fluids.in_lava && !m.kind.flags.fire_immune {
m.fire_ticks = m.fire_ticks.max(300);
m.ignite_for_ticks(300);
m.damage(4.0, Damage::of(DamageKind::Lava));
}
if m.fire_ticks > 0 {
if m.kind.flags.fire_immune {
m.fire_ticks = (m.fire_ticks - 4).max(0);
m.fire_ticks = 0;
} else {
if m.fire_ticks % 20 == 0 && !m.fluids.in_lava {
m.damage(1.0, Damage::of(DamageKind::OnFire));
@@ -508,6 +524,9 @@ pub fn ambient_sound(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
play_ambient(m, w, events);
}
fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if super::axolotl::is_playing_dead(m) {
return;
}
let sound = match m.species() {
// Warden.getAmbientSound: by anger, silent while roaring or digging.
Species::Warden => match super::warden::ambient_sound(m) {
@@ -686,7 +705,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
}
// Mob.aiStep: undead burn in daylight.
if m.kind.flags.burns_in_day && m.alive() && sun_burn_tick(m, w) && m.extra.head.is_none() {
m.fire_ticks = m.fire_ticks.max(160);
m.ignite_for_ticks(160);
}
species_ai_step(m, w, events);
}
@@ -844,6 +863,7 @@ fn server_ai_step(
if m.species() == Species::Sniffer
|| m.species() == Species::HappyGhast && m.is_baby()
|| m.species() == Species::CopperGolem
|| m.species() == Species::Axolotl
{
super::animal_brain::tick(m, w, level_random, events);
}
@@ -855,8 +875,10 @@ fn server_ai_step(
m.ai.jumping = false;
return;
}
m.move_control_tick(w, events);
m.look_control_tick();
if !super::axolotl::is_playing_dead(m) {
m.move_control_tick(w, events);
m.look_control_tick();
}
m.jump_control_tick();
}
fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
@@ -1474,3 +1496,12 @@ pub fn swim_sound(m: &Mob) -> &'static str {
_ => "entity.generic.swim",
}
}
#[cfg(test)]
mod bucket_axolotl_tests {
use super::*;
#[test]
fn bucket_axolotl_uses_aquatic_not_generic_land_ai() {
assert_eq!(family(Species::Axolotl), Family::Aquatic);
}
}
+83 -2
View File
@@ -266,6 +266,8 @@ pub struct Hum {
pub left: ArmPose,
pub crouching: bool,
pub passenger: bool,
pub fall_flying: bool,
pub fly_speed_scale: f32,
/// `Some(aggressive)` for `ZombieModel`-style `animateZombieArms`.
pub zombie: Option<bool>,
/// The main hand holds something (`getMainHandItemStack() != EMPTY`).
@@ -282,6 +284,8 @@ impl Hum {
left,
crouching: false,
passenger: false,
fall_flying: false,
fly_speed_scale: 1.0,
zombie: None,
holding: false,
charge: (0.0, 0.0),
@@ -353,7 +357,10 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) {
/// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`).
pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
head(p, s);
let (pos, sp) = (s.pos, s.speed);
if h.fall_flying {
p.xrot("head", -std::f32::consts::FRAC_PI_4);
}
let (pos, sp) = (s.pos, s.speed / h.fly_speed_scale);
p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5);
p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5);
p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp);
@@ -539,7 +546,38 @@ pub fn setup(
} else {
ArmPose::Empty
};
let mut h = Hum::new(right, ArmPose::Empty);
let pose = if player {
match m.extra.main_hand.as_deref() {
Some("minecraft:bow") if m.extra.using_item > 0 => ArmPose::Bow,
Some("minecraft:crossbow") if m.extra.using_item > 0 && !m.extra.charged => {
ArmPose::CrossbowCharge
}
Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => {
ArmPose::CrossbowHold
}
Some(_) => ArmPose::Item,
None => ArmPose::Empty,
}
} else {
right
};
let off = if player && m.extra.off_hand.is_some() && !pose.two_handed() {
ArmPose::Item
} else {
ArmPose::Empty
};
let mut h = if m.extra.main_hand_left {
Hum::new(off, pose)
} else {
Hum::new(pose, off)
};
h.charge = (m.extra.ints[5] as f32, m.extra.using_item as f32);
h.fall_flying = m.extra.fall_flying;
if h.fall_flying {
let v = m.velocity;
h.fly_speed_scale =
(((v.x * v.x + v.y * v.y + v.z * v.z) as f32 / 0.2).powi(3)).max(1.0);
}
h.crouching = m.extra.crouching;
h.passenger = m.extra.passenger;
humanoid(p, s, &h);
@@ -630,3 +668,46 @@ pub fn setup(
}
}
}
#[cfg(test)]
mod flight_pose_tests {
use super::*;
#[test]
fn flight_slows_limbs_and_sets_the_head_pose() {
let state = State {
pos: 0.0,
speed: 1.0,
age: 0.0,
y_rot: 0.0,
x_rot: 0.0,
swing: 0.0,
baby: false,
partial: 0.0,
};
let make = || Poses {
map: [
"head",
"right_arm",
"left_arm",
"right_leg",
"left_leg",
"body",
]
.into_iter()
.map(|n| (n.to_string(), [0.0; 9]))
.collect(),
dummy: [0.0; 9],
skipped: Default::default(),
hidden: Default::default(),
};
let mut ground = make();
let mut flight = make();
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
humanoid(&mut ground, &state, &h);
h.fall_flying = true;
h.fly_speed_scale = 8.0;
humanoid(&mut flight, &state, &h);
assert_eq!(flight.get("head")[3], -std::f32::consts::FRAC_PI_4);
assert_eq!(flight.get("right_leg")[3], ground.get("right_leg")[3] / 8.0);
}
}
+696 -26
View File
@@ -194,11 +194,21 @@ pub struct Memories {
pub sniff_cooldown: Slot<()>,
pub gaze_cooldown_ticks: Slot<i32>,
pub transport_items_cooldown_ticks: Slot<i32>,
pub nearest_attackable: Slot<Who>,
pub attack_target: Slot<Who>,
pub attack_cooling_down: Slot<bool>,
pub hunting_cooldown: Slot<bool>,
pub play_dead_ticks: Slot<i32>,
pub visited_block_positions: Slot<Vec<[i32; 3]>>,
pub unreachable_transport_block_positions: Slot<Vec<[i32; 3]>>,
}
impl Memories {
fn tick(&mut self) {
self.nearest_attackable.tick();
self.attack_target.tick();
self.attack_cooling_down.tick();
self.hunting_cooldown.tick();
self.play_dead_ticks.tick();
self.mobs.tick();
self.visible_mobs.tick();
self.nearest_players.tick();
@@ -231,6 +241,8 @@ impl Memories {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Act {
Core,
Fight,
PlayDead,
Idle,
Sniff,
Dig,
@@ -240,6 +252,8 @@ impl Act {
pub fn name(self) -> &'static str {
match self {
Act::Core => "core",
Act::Fight => "fight",
Act::PlayDead => "play_dead",
Act::Idle => "idle",
Act::Sniff => "sniff",
Act::Dig => "dig",
@@ -251,6 +265,7 @@ impl Act {
/// Which brain.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Axolotl,
Sniffer,
/// A happy ghast (the brain ticks while it is a ghastling).
Ghastling,
@@ -261,6 +276,8 @@ pub enum Kind {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Sensor {
Living,
AxolotlAttackables,
AdultSameType,
HurtBy,
Players,
Tempting,
@@ -270,6 +287,13 @@ impl Kind {
/// `BRAIN_PROVIDER`'s sensors, in order (all scan every 20 ticks).
fn sensors(self) -> &'static [Sensor] {
match self {
Kind::Axolotl => &[
Sensor::Living,
Sensor::AdultSameType,
Sensor::HurtBy,
Sensor::AxolotlAttackables,
Sensor::Tempting,
],
Kind::Sniffer => &[
Sensor::Living,
Sensor::HurtBy,
@@ -322,7 +346,11 @@ pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> {
/// The brain kind a mob has, if any.
pub fn kind_of(m: &Mob) -> Option<Kind> {
match m.species() {
kind_for_species(m.species())
}
fn kind_for_species(species: Species) -> Option<Kind> {
match species {
Species::Axolotl => Some(Kind::Axolotl),
Species::Sniffer => Some(Kind::Sniffer),
// Every happy ghast has the brain; only the ghastling's ticks.
Species::HappyGhast => Some(Kind::Ghastling),
@@ -353,6 +381,7 @@ pub fn init(m: &mut Mob, shuffle_seed: i64) {
list: Vec::new(),
};
b.list = match kind {
Kind::Axolotl => axolotl_package(shuffle_seed),
Kind::Sniffer => sniffer_package(shuffle_seed),
Kind::Ghastling => ghastling_package(shuffle_seed),
Kind::CopperGolem => copper_golem_package(shuffle_seed),
@@ -399,7 +428,16 @@ pub fn set_breed_partner(m: &mut Mob, partner: u32) {
}
let who = Who::Mob(partner);
mem(m).breed_target.set(who);
lock_gaze_and_walk(m, who, 1.0, 2);
lock_gaze_and_walk(
m,
who,
if m.species() == Species::Axolotl {
0.2
} else {
1.0
},
2,
);
}
/// `AnimalMakeLove.tick` after the birth: the partner forgets this mob.
@@ -413,7 +451,16 @@ pub fn lock_gaze(m: &mut Mob, partner: u32) {
if m.extra.animal_brain.is_none() {
return;
}
lock_gaze_and_walk(m, Who::Mob(partner), 1.0, 2);
lock_gaze_and_walk(
m,
Who::Mob(partner),
if m.species() == Species::Axolotl {
0.2
} else {
1.0
},
2,
);
}
/// What behaviours read and emit during a brain tick.
@@ -457,6 +504,13 @@ pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec<M
brain_mut(m).list = list;
update_activity(m);
m.ai.panicking = is_panicking(m);
if m.species() == Species::Axolotl {
m.extra.axolotl.playing_dead = mem(m)
.play_dead_ticks
.value()
.is_some_and(|ticks| ticks > 0);
m.ai.target = mem(m).attack_target.value();
}
}
/// `SnifferAi.updateActivity` / `HappyGhastAi.updateActivity`:
@@ -464,10 +518,15 @@ pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec<M
fn update_activity(m: &mut Mob) {
let b = brain_mut(m);
let mm = &b.mem;
if b.kind == Kind::Axolotl {
update_axolotl_activity(b);
return;
}
let order: &[Act] = match b.kind {
Kind::Sniffer => &[Act::Dig, Act::Sniff, Act::Idle],
Kind::Ghastling => &[Act::Panic, Act::Idle],
Kind::CopperGolem => &[Act::Idle],
Kind::Axolotl => unreachable!(),
};
for &a in order {
let ok = match a {
@@ -484,6 +543,7 @@ fn update_activity(m: &mut Mob) {
Act::Idle => b.kind != Kind::Sniffer || !mm.sniffer_digging.present(),
Act::Panic => mm.is_panicking.present(),
Act::Core => true,
Act::Fight | Act::PlayDead => false,
};
if ok {
b.activity = a;
@@ -523,6 +583,16 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) {
}
match sensor {
Sensor::Living => sense_living(m, w),
Sensor::AxolotlAttackables => sense_axolotl_attackables(m, w),
Sensor::AdultSameType => {
let found = find_closest(m, w, |m, who| match who {
Who::Mob(id) => w
.seen(id)
.is_some_and(|s| !s.baby && s.species == m.species()),
_ => false,
});
mem(m).nearest_visible_adult.set_opt(found);
}
Sensor::HurtBy => sense_hurt(m, w),
Sensor::Players => sense_players(m, w),
Sensor::Tempting => sense_tempting(m, w),
@@ -759,6 +829,8 @@ impl Timed {
#[derive(Clone, Debug)]
struct Gate {
running: bool,
shuffle: bool,
try_all: bool,
random: LegacyRandom,
kids: Vec<(B, i32, f64)>,
/// The gate's memory requirements.
@@ -768,6 +840,8 @@ impl Gate {
fn run_one(seed: i64, kids: Vec<(B, i32)>) -> Self {
Self {
running: false,
shuffle: true,
try_all: false,
random: LegacyRandom::new(seed),
kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(),
when: None,
@@ -786,13 +860,15 @@ impl Gate {
self.running = true;
// ShufflingList.shuffle: a fresh weight for each entry in the
// current order, then a stable sort.
for k in &mut self.kids {
let r = self.random.next_float();
k.2 = -horizon_core::jmath::pow(f64::from(r), f64::from(1.0_f32 / k.1 as f32));
if self.shuffle {
for k in &mut self.kids {
let r = self.random.next_float();
k.2 = -horizon_core::jmath::pow(f64::from(r), f64::from(1.0_f32 / k.1 as f32));
}
self.kids.sort_by(|a, b| a.2.total_cmp(&b.2));
}
self.kids.sort_by(|a, b| a.2.total_cmp(&b.2));
for k in &mut self.kids {
if !k.0.running() && k.0.try_start(m, cx) {
if !k.0.running() && k.0.try_start(m, cx) && !self.try_all {
break;
}
}
@@ -820,6 +896,12 @@ impl Gate {
#[derive(Clone, Debug)]
enum B {
AxolotlAction {
action: AxolotlAction,
running: bool,
until: i64,
},
PlayDead(Timed),
Swim(Timed),
/// `AnimalPanic`: flying (`AirAndWaterRandomPos`) or on land, and
/// whether the sniffer's override resets its sniffing first.
@@ -890,7 +972,8 @@ enum B {
impl B {
fn running(&self) -> bool {
match self {
B::Swim(t)
B::PlayDead(t)
| B::Swim(t)
| B::AnimalPanic { t, .. }
| B::MoveToTargetSink { t, .. }
| B::CountDownTemptation(t)
@@ -908,7 +991,8 @@ impl B {
| B::CountDownTransport(t) => t.running,
B::Transport(x) => x.running,
B::LookAtPlayerSometimes(running, _) => *running,
B::WalkToLookTarget { running, .. }
B::AxolotlAction { running, .. }
| B::WalkToLookTarget { running, .. }
| B::LookAtPlayer(running)
| B::Stroll { running, .. }
| B::FollowAdult { running, .. } => *running,
@@ -919,7 +1003,8 @@ impl B {
/// cleared with the rest).
fn reset(&mut self) {
match self {
B::Swim(t)
B::PlayDead(t)
| B::Swim(t)
| B::AnimalPanic { t, .. }
| B::CountDownTemptation(t)
| B::MakeLove { t, .. }
@@ -952,7 +1037,8 @@ impl B {
fn one_shot(&self) -> bool {
matches!(
self,
B::WalkToLookTarget { .. }
B::AxolotlAction { .. }
| B::WalkToLookTarget { .. }
| B::LookAtPlayer(_)
| B::LookAtPlayerSometimes(..)
| B::Stroll { .. }
@@ -961,7 +1047,8 @@ impl B {
}
fn set_one_shot(&mut self, on: bool) {
match self {
B::WalkToLookTarget { running, .. }
B::AxolotlAction { running, .. }
| B::WalkToLookTarget { running, .. }
| B::LookAtPlayer(running)
| B::LookAtPlayerSometimes(running, _)
| B::Stroll { running, .. }
@@ -982,6 +1069,19 @@ impl B {
let now = cx.now;
match self {
B::Gate(g) => g.try_start(m, cx),
B::PlayDead(t) => {
if !m.fluids.in_water
|| !mem(m).play_dead_ticks.present()
|| !mem(m).hurt_by_entity.present()
{
return false;
}
t.begin(cx);
mem(m).walk_target.clear();
mem(m).look_target.clear();
m.add_effect("minecraft:regeneration", 200, 0);
true
}
B::Swim(t) => {
if !swim_condition(m) {
return false;
@@ -1082,7 +1182,12 @@ impl B {
partner: m.id,
});
}
lock_gaze_and_walk(m, partner, 1.0, 2);
let speed = if m.species() == Species::Axolotl {
0.2
} else {
1.0
};
lock_gaze_and_walk(m, partner, speed, 2);
*spawn_at = now + 60 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
true
}
@@ -1196,7 +1301,8 @@ impl B {
t.begin(cx);
true
}
B::WalkToLookTarget { .. }
B::AxolotlAction { .. }
| B::WalkToLookTarget { .. }
| B::LookAtPlayer(_)
| B::LookAtPlayerSometimes(..)
| B::Stroll { .. }
@@ -1207,6 +1313,11 @@ impl B {
/// A one-shot's trigger.
fn trigger(&mut self, m: &mut Mob, cx: &mut Bx) -> bool {
match *self {
B::AxolotlAction {
action,
ref mut until,
..
} => axolotl_action(m, cx, action, until),
B::WalkToLookTarget { speed, close, .. } => {
let mm = mem(m);
if mm.walk_target.present() {
@@ -1252,7 +1363,11 @@ impl B {
let Some(t) = found else { return false };
// Ticker.tickDownAndCheck (UniformInt 40..80 on the level random).
if *ticks == 0 {
*ticks = 40 + cx.lr.next_int_bound(41).unwrap_or(0) - 1;
*ticks = if m.species() == Species::Axolotl {
30 + cx.lr.next_int_bound(31).unwrap_or(0) - 1
} else {
40 + cx.lr.next_int_bound(41).unwrap_or(0) - 1
};
return false;
}
*ticks -= 1;
@@ -1265,6 +1380,9 @@ impl B {
B::Stroll {
fly, speed, range, ..
} => {
if m.species() == Species::Axolotl && m.fluids.in_water {
return false;
}
if mem(m).walk_target.present() {
return false;
}
@@ -1295,23 +1413,39 @@ impl B {
};
// closerThan(adult, 17) && !closerThan(adult, 3)
let d = m.distance_sqr(at.position);
if !(3.0 * 3.0..17.0 * 17.0).contains(&d) {
let min = if m.species() == Species::Axolotl {
5.0
} else {
3.0
};
if !(min * min..17.0 * 17.0).contains(&d) {
return false;
}
let speed = if m.species() == Species::Axolotl {
axolotl_speed(m, true)
} else {
1.1
};
let close = if m.species() == Species::Axolotl {
4
} else {
2
};
let eyes = m.species() != Species::Axolotl;
let mm = mem(m);
mm.walk_target.set(WalkTarget {
target: Tracker::Entity {
who: adult,
eye: true,
block_eye: true,
eye: eyes,
block_eye: eyes,
},
speed: 1.1,
close: 2,
speed,
close,
});
mm.look_target.set(Tracker::Entity {
who: adult,
eye: true,
block_eye: true,
block_eye: eyes,
});
true
}
@@ -1327,6 +1461,12 @@ impl B {
}
let now = cx.now;
match self {
B::AxolotlAction { .. } => {}
B::PlayDead(t) => {
if t.timed_out(now) || !m.fluids.in_water || !mem(m).play_dead_ticks.present() {
self.do_stop(m, cx);
}
}
B::Gate(g) => g.tick_or_stop(m, cx),
B::Swim(t) => {
if t.timed_out(now) || !swim_condition(m) {
@@ -1419,7 +1559,16 @@ impl B {
self.do_stop(m, cx);
return;
}
lock_gaze_and_walk(m, partner, 1.0, 2);
lock_gaze_and_walk(
m,
partner,
if m.species() == Species::Axolotl {
0.2
} else {
1.0
},
2,
);
if let Who::Mob(id) = partner {
cx.events.push(MobEvent::LockGaze {
mob: id,
@@ -1476,7 +1625,11 @@ impl B {
let near =
cx.w.target_info(player)
.is_some_and(|t| m.distance_sqr(t.position) < close * close);
let speed = 1.25;
let speed = if m.species() == Species::Axolotl {
axolotl_speed(m, false)
} else {
1.25
};
let mm = mem(m);
if near {
mm.walk_target.clear();
@@ -1560,6 +1713,8 @@ impl B {
}
let now = cx.now;
match self {
B::AxolotlAction { .. } => {}
B::PlayDead(t) => t.running = false,
B::Gate(g) => g.do_stop(m, cx),
B::Swim(t) | B::DoNothing(t) => t.running = false,
B::AnimalPanic { t, .. } => {
@@ -1788,6 +1943,7 @@ fn follow_temptation_close(m: &mut Mob) -> f64 {
3.5
}
}
Kind::Axolotl => 2.5,
Kind::Ghastling | Kind::CopperGolem => 3.0,
}
}
@@ -1797,8 +1953,8 @@ fn can_mate_with(m: &Mob, w: &MobWorld, partner: Who) -> bool {
s.species == m.species()
&& s.in_love
&& m.extra.in_love > 0
&& sniffer::can_mate_state(sniffer::state(m))
&& sniffer::can_mate_state(s.variant)
&& (m.species() != Species::Sniffer
|| sniffer::can_mate_state(sniffer::state(m)) && sniffer::can_mate_state(s.variant))
}
fn partner_panicking(_w: &MobWorld, _partner: Who) -> bool {
false
@@ -2093,6 +2249,438 @@ fn move_to_target_sink(min: i32, max: i32) -> B {
}
}
// ---- AxolotlAi -----------------------------------------------------------
#[derive(Clone, Copy, Debug)]
enum AxolotlAction {
ValidateDead,
StartAttack,
StopAttack,
Chase,
Bite,
EraseAttackBreeding,
EraseDeadBreeding,
FindLiquid,
SwimStroll,
WalkFromLook,
StayWater,
StayGround,
}
fn axolotl_speed(m: &Mob, chase: bool) -> f32 {
if m.fluids.in_water {
if chase { 0.6 } else { 0.5 }
} else {
0.15
}
}
pub fn set_play_dead(m: &mut Mob) {
if m.extra.animal_brain.is_none() {
init(m, i64::from(m.id));
}
mem(m).play_dead_ticks.set(super::axolotl::PLAY_DEAD_TICKS);
}
pub fn hunting_cooldown(m: &Mob) -> Option<i64> {
mem_ref(m).and_then(|mm| {
mm.hunting_cooldown
.get()
.and_then(|_| (mm.hunting_cooldown.ttl > 0).then_some(mm.hunting_cooldown.ttl))
})
}
pub fn set_hunting_cooldown(m: &mut Mob, ticks: i64) {
if m.extra.animal_brain.is_none() {
init(m, i64::from(m.id));
}
if ticks > 0 {
mem(m).hunting_cooldown.set_ttl(true, ticks);
} else {
mem(m).hunting_cooldown.clear();
}
}
fn validate_play_dead(b: &mut Brain) -> bool {
let Some(ticks) = b.mem.play_dead_ticks.value() else {
return false;
};
if ticks <= 0 {
b.mem.play_dead_ticks.clear();
b.mem.hurt_by_entity.clear();
b.activity = Act::Idle;
} else {
b.mem.play_dead_ticks.set(ticks - 1);
}
true
}
fn update_axolotl_activity(b: &mut Brain) {
let old = b.activity;
// PLAY_DEAD remains active until ValidatePlayDead resets to default IDLE.
if old == Act::PlayDead {
return;
}
b.activity = if b.mem.play_dead_ticks.present() {
Act::PlayDead
} else if b.mem.attack_target.present() {
Act::Fight
} else {
Act::Idle
};
if old != b.activity && old == Act::Fight {
b.mem
.hunting_cooldown
.set_ttl(true, super::axolotl::HUNTING_COOLDOWN);
b.mem.attack_target.clear();
}
}
fn sense_axolotl_attackables(m: &mut Mob, w: &MobWorld) {
let cooldown = mem(m).hunting_cooldown.present();
let target = find_closest(m, w, |m, who| {
let Who::Mob(id) = who else { return false };
let Some(s) = w.seen(id) else { return false };
let id = format!("minecraft:{}", super::species::def(s.species).name);
super::axolotl::prey_eligible(
m.distance_sqr(s.position),
s.in_water,
w.data.entity_has("minecraft:axolotl_always_hostiles", &id),
w.data.entity_has("minecraft:axolotl_hunt_targets", &id),
cooldown,
s.alive && !s.playing_dead,
)
});
mem(m).nearest_attackable.set_opt(target);
}
fn axolotl_action(m: &mut Mob, cx: &mut Bx, action: AxolotlAction, until: &mut i64) -> bool {
use AxolotlAction::*;
match action {
ValidateDead => validate_play_dead(brain_mut(m)),
StartAttack => {
let mm = mem(m);
if mm.attack_target.present() || mm.breed_target.present() {
return false;
}
let Some(target) = mm.nearest_attackable.value() else {
return false;
};
if !cx
.w
.target_info(target)
.is_some_and(|t| t.alive && !t.creative)
{
return false;
}
mem(m).attack_target.set(target);
mem(m).cant_reach_walk_target_since.clear();
m.ai.target = Some(target);
true
}
StopAttack => {
let Some(target) = mem(m).attack_target.value() else {
return false;
};
let tired = mem(m)
.cant_reach_walk_target_since
.value()
.is_some_and(|t| cx.now - t > 200);
let valid =
cx.w.target_info(target)
.is_some_and(|t| t.alive && !t.creative)
&& match target {
Who::Mob(id) => cx.w.seen(id).is_some_and(|s| !s.playing_dead),
Who::Player => true,
};
if tired || !valid {
super::axolotl::on_stop_attacking(m, cx.w, target, cx.events);
mem(m).attack_target.clear();
m.ai.target = None;
}
true
}
Chase => {
let Some(target) = mem(m).attack_target.value() else {
return false;
};
let speed = axolotl_speed(m, true);
if cx
.w
.target_info(target)
.is_some_and(|t| m.within_melee_range(&t))
&& visible_contains(m, cx.w, target)
{
mem(m).walk_target.clear();
} else {
let tracker = Tracker::entity(target, true);
mem(m).look_target.set(tracker);
mem(m).walk_target.set(WalkTarget {
target: Tracker::entity(target, false),
speed,
close: 0,
});
}
true
}
Bite => {
let mm = mem(m);
if mm.attack_cooling_down.present() {
return false;
}
let Some(target) = mm.attack_target.value() else {
return false;
};
if !visible_contains(m, cx.w, target)
|| !cx
.w
.target_info(target)
.is_some_and(|t| m.within_melee_range(&t))
{
return false;
}
mem(m).look_target.set(Tracker::entity(target, true));
m.swing();
super::ai::do_hurt_target(
m,
target,
&mut super::goals::Cx {
w: cx.w,
events: cx.events,
},
);
mem(m).attack_cooling_down.set_ttl(true, 20);
true
}
EraseAttackBreeding | EraseDeadBreeding => {
if !mem(m).breed_target.present() {
return false;
}
if matches!(action, EraseAttackBreeding) {
mem(m).attack_target.clear();
} else {
mem(m).play_dead_ticks.clear();
}
true
}
FindLiquid => {
if mem(m).walk_target.present() || mem(m).attack_target.present() {
return false;
}
let p = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
if cx.w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water {
return false;
}
if cx.now < *until {
*until = cx.now + 22;
return true;
}
let mut positions = Vec::new();
// BlockPos.withinManhattan: distance, x, y, then positive/negative z.
for distance in 0..=18i32 {
for x in -6..=6i32 {
for y in -6..=6i32 {
let z = distance - x.abs() - y.abs();
if !(0..=6).contains(&z) {
continue;
}
positions.push([p[0] + x, p[1] + y, p[2] + z]);
if z != 0 {
positions.push([p[0] + x, p[1] + y, p[2] - z]);
}
}
}
}
let mut found = None;
for q in positions {
if (q[0] == p[0] && q[2] == p[2])
|| cx.w.fluid(q[0], q[1], q[2]) != crate::blocks::Fluid::Water
{
continue;
}
let name = cx.w.block_name(q[0], q[1], q[2]);
if name != "minecraft:water" {
continue;
}
if cx.w.block_name(q[0], q[1] + 1, q[2]).ends_with("air") {
found = Some(q);
break;
}
let v = Vec3::new(
f64::from(q[0]) + 0.5,
f64::from(q[1]) + 0.5,
f64::from(q[2]) + 0.5,
);
if found.is_none() && m.distance_sqr(v) >= 2.25 {
found = Some(q);
}
}
if let Some(q) = found {
mem(m).look_target.set(Tracker::Block(q));
mem(m).walk_target.set(WalkTarget {
target: Tracker::Block(q),
speed: 0.15,
close: 0,
});
}
*until = cx.now + 40;
true
}
SwimStroll => {
if mem(m).walk_target.present() || !m.fluids.in_water {
return false;
}
let mut fallback: Option<Vec3> = None;
for (h, v) in [(1, 1), (3, 3), (5, 5), (6, 5), (7, 7), (10, 7)] {
let point = if let Some(p) = fallback {
let delta =
Vec3::new(p.x - m.position.x, p.y - m.position.y, p.z - m.position.z);
let length = (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z).sqrt();
let n = if length < 1.0e-5 {
Vec3::ZERO
} else {
Vec3::new(delta.x / length, delta.y / length, delta.z / length)
};
Some(Vec3::new(
m.position.x + n.x * f64::from(h),
m.position.y + n.y * f64::from(v),
m.position.z + n.z * f64::from(h),
))
} else {
let mut p = m.default_random_pos(cx.w, h, v);
let mut count = 0;
while let Some(q) = p {
let state = cx.w.world.block(
q[0].floor() as i32,
q[1].floor() as i32,
q[2].floor() as i32,
);
if cx.w.data.state(state).flags & super::data::WATER != 0 || count >= 10 {
break;
}
count += 1;
p = m.default_random_pos(cx.w, h, v);
}
p.map(|q| Vec3::new(q[0], q[1], q[2]))
};
let Some(point) = point else { break };
let q = [
point.x.floor() as i32,
point.y.floor() as i32,
point.z.floor() as i32,
];
let restricted = m.restricted(f64::from(h), q);
if cx.w.fluid(q[0], q[1], q[2]) == crate::blocks::Fluid::None || restricted {
break;
}
fallback = Some(point);
}
mem(m)
.walk_target
.set_opt(fallback.map(|p| WalkTarget::point([p.x, p.y, p.z], 0.5, 0)));
true
}
WalkFromLook => {
if mem(m).walk_target.present() {
return false;
}
let Some(t) = mem(m).look_target.value() else {
return false;
};
let Some(p) = t.block(cx.w) else { return false };
if (cx.w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water) != m.fluids.in_water {
return false;
}
let speed = axolotl_speed(m, false);
mem(m).walk_target.set(WalkTarget {
target: t,
speed,
close: 3,
});
true
}
StayWater => m.fluids.in_water,
StayGround => m.on_ground,
}
}
fn axolotl_package(seed: i64) -> Vec<Entry> {
use Act::*;
use AxolotlAction::*;
let e = |act, b| Entry { act, b };
let action = |action| B::AxolotlAction {
action,
running: false,
until: 0,
};
vec![
// Native activity slots, merged by behavior priority.
e(Core, B::LookAtTargetSink(Timed::new(45, 90))),
e(Idle, B::LookAtPlayerSometimes(false, 0)),
e(Fight, action(StopAttack)),
e(PlayDead, B::PlayDead(Timed::new(200, 200))),
e(Core, move_to_target_sink(150, 250)),
e(
Idle,
B::MakeLove {
t: Timed::new(110, 110),
spawn_at: 0,
},
),
e(Fight, action(Chase)),
e(PlayDead, action(EraseDeadBreeding)),
e(Core, action(ValidateDead)),
e(
Idle,
B::Gate(Box::new(Gate::run_one(
seed,
vec![
(
B::FollowTemptation {
t: Timed::new(60, 60),
look_in_the_eyes: false,
},
1,
),
(
B::FollowAdult {
running: false,
player: false,
},
1,
),
],
))),
),
e(Fight, action(Bite)),
e(Core, B::CountDownTemptation(Timed::new(60, 60))),
e(Idle, action(StartAttack)),
e(Idle, action(FindLiquid)),
e(Fight, action(EraseAttackBreeding)),
e(
Idle,
B::Gate(Box::new(Gate {
running: false,
shuffle: false,
try_all: true,
random: horizon_core::random::LegacyRandom::new(seed),
kids: vec![
(action(SwimStroll), 2, 0.0),
(
B::Stroll {
running: false,
fly: false,
speed: 0.15,
range: (10, 7),
},
2,
0.0,
),
(action(WalkFromLook), 3, 0.0),
(action(StayWater), 5, 0.0),
(action(StayGround), 5, 0.0),
],
when: Some(|mm| !mm.walk_target.present()),
})),
),
]
}
// ---- Debug output (the mob AI harness) ------------------------------------
fn pos(p: [i32; 3]) -> String {
@@ -2134,6 +2722,16 @@ pub fn describe(m: &Mob) -> Option<(String, String)> {
};
}
let n = |l: &Vec<Who>| format!("n{}", l.len());
slot!("nearest_attackable", mm.nearest_attackable, |v: &Who| who(
*v
));
slot!("attack_target", mm.attack_target, |v: &Who| who(*v));
slot!("attack_cooling_down", mm.attack_cooling_down, |v: &bool| v
.to_string());
slot!("has_hunting_cooldown", mm.hunting_cooldown, |v: &bool| v
.to_string());
slot!("play_dead_ticks", mm.play_dead_ticks, |v: &i32| v
.to_string());
slot!("mobs", mm.mobs, n);
slot!("visible_mobs", mm.visible_mobs, |_: &Visible| {
"NearestVisibleLivingEntities".to_string()
@@ -2219,3 +2817,75 @@ pub fn describe(m: &Mob) -> Option<(String, String)> {
out.sort();
Some((acts.join("|"), out.join(" ")))
}
#[cfg(test)]
mod axolotl_parity_tests {
use super::*;
fn empty_brain() -> Brain {
Brain {
kind: Kind::Axolotl,
mem: Memories::default(),
sensors: Vec::new(),
activity: Act::Idle,
list: Vec::new(),
}
}
#[test]
fn fight_exit_sets_hunting_cooldown_and_play_dead_has_priority() {
let mut b = empty_brain();
b.mem.attack_target.set(Who::Mob(1));
update_axolotl_activity(&mut b);
assert_eq!(b.activity, Act::Fight);
b.mem.play_dead_ticks.set(200);
update_axolotl_activity(&mut b);
assert_eq!(b.activity, Act::PlayDead);
assert_eq!(b.mem.hunting_cooldown.ttl, 2400);
assert!(!b.mem.attack_target.present());
for _ in 0..2400 {
b.mem.hunting_cooldown.tick();
}
assert!(b.mem.hunting_cooldown.present());
b.mem.hunting_cooldown.tick();
assert!(!b.mem.hunting_cooldown.present());
}
#[test]
fn play_dead_flag_ends_at_zero_before_memory_is_erased() {
let mut b = empty_brain();
b.activity = Act::PlayDead;
b.mem.play_dead_ticks.set(200);
b.mem.hurt_by_entity.set(Who::Mob(7));
for _ in 0..200 {
assert!(validate_play_dead(&mut b));
}
assert_eq!(b.mem.play_dead_ticks.value(), Some(0));
assert_eq!(b.activity, Act::PlayDead);
assert!(validate_play_dead(&mut b));
assert!(!b.mem.play_dead_ticks.present());
assert!(!b.mem.hurt_by_entity.present());
assert_eq!(b.activity, Act::Idle);
}
#[test]
fn axolotl_has_native_activity_brain_not_fallback_goals() {
assert!(kind_for_species(Species::Axolotl).is_some());
}
}
#[cfg(test)]
mod breeding_duration_tests {
use super::*;
#[test]
fn axolotl_breeding_uses_native_110_tick_timeout() {
let package = axolotl_package(1);
let timed = package
.iter()
.find_map(|e| {
if let B::MakeLove { t, .. } = &e.b {
Some(t)
} else {
None
}
})
.unwrap();
assert_eq!((timed.min, timed.max), (110, 110));
}
}
+20
View File
@@ -35,6 +35,19 @@ pub fn register(m: &mut Mob) {
let speed = 1.0 / (m.random.next_float() + 1.0) * 0.2;
m.anim.v[TENTACLE_SPEED] = speed;
}
S::Axolotl => {
// Native controller scaling is essential: the base speed attribute is 1.0.
m.ai.mov.kind = MoveKind::SmoothSwimming {
max_turn_x: 85.0,
max_turn_y: 10.0,
in_water: 0.1,
outside: 0.5,
gravity: false,
};
m.ai.look.kind = super::control::LookKind::SmoothSwimming(20.0);
m.ai.nav.kind = NavKind::Amphibious;
super::animal_brain::init(m, i64::from(m.id));
}
S::Tadpole => {
// TadpoleAi: panic, swim around and look about.
let g = &mut m.ai.goals;
@@ -267,6 +280,13 @@ pub fn travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>
m.do_move(w, events);
true
}
// Axolotl.travelInWater: no fish sinking or generic water gravity.
S::Axolotl if m.fluids.in_water => {
m.move_relative(m.ai.speed, input);
m.do_move(w, events);
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
true
}
// AbstractFish.travelInWater / Dolphin.travelInWater.
S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin if m.fluids.in_water => {
let speed = if m.species() == S::Dolphin {
+205
View File
@@ -0,0 +1,205 @@
//! Axolotl-specific damage, animation and prey rules; activities live in animal_brain.
use super::{Mob, MobEvent, MobWorld, Species, Who, animal_brain, keyframes::AnimationState};
use horizon_core::random::RandomSource;
pub const PLAY_DEAD_TICKS: i32 = 200;
pub const HUNTING_COOLDOWN: i64 = 2400;
/// AxolotlAttackablesSensor: always-hostile targets bypass the hunting cooldown.
pub fn prey_eligible(
distance: f64,
water: bool,
hostile: bool,
hunt: bool,
cooldown: bool,
attackable: bool,
) -> bool {
distance <= 64.0 && water && (hostile || hunt && !cooldown) && attackable
}
/// Preserve the ordered random draws in Axolotl.hurtServer, even out of water.
fn roll_play_dead(
random: &mut impl RandomSource,
no_ai: bool,
health: f32,
max: f32,
damage: f32,
water: bool,
entity_source: bool,
already: bool,
) -> bool {
!no_ai
&& random.next_int_bound(3).unwrap_or(0) == 0
&& ((random.next_int_bound(3).unwrap_or(0) as f32) < damage || health / max < 0.5)
&& damage < health
&& water
&& entity_source
&& !already
}
pub fn before_damage(m: &mut Mob, damage: f32, source: &super::Damage) {
if m.species() != Species::Axolotl {
return;
}
let playing = m.extra.axolotl.playing_dead;
if roll_play_dead(
&mut m.random,
m.no_ai,
m.health,
m.attrs.max_health,
damage,
m.fluids.in_water,
source.attacker.is_some() || source.is_projectile(),
playing,
) {
animal_brain::set_play_dead(m);
}
}
pub fn is_playing_dead(m: &Mob) -> bool {
m.species() == Species::Axolotl && m.extra.axolotl.playing_dead
}
/// Axolotl.onStopAttacking: help the player whose last damage killed the target.
pub fn on_stop_attacking(m: &Mob, w: &MobWorld, target: Who, events: &mut Vec<MobEvent>) {
if let Who::Mob(id) = target
&& let Some(s) = w.seen(id)
&& !s.alive
&& s.last_damage
.is_some_and(|d| d.attacker == Some(Who::Player))
&& w.player.as_ref().is_some_and(|p| {
m.bounds()
.inflate(horizon_core::geometry::Vec3::new(20.0, 20.0, 20.0))
.intersects(p.bounds)
})
{
events.push(MobEvent::AxolotlSupportPlayer);
}
}
/// BinaryAnimator(10, IN_OUT_SINE), plus the seven exclusive baby animation states.
#[derive(Clone, Debug, Default)]
pub struct Animation {
pub playing_dead: bool,
old: [u8; 4],
value: [u8; 4],
pub states: [AnimationState; 7],
}
impl Animation {
pub fn tick(&mut self, baby: bool, water: bool, ground: bool, moving: bool, age: f32) {
self.old = self.value;
let flags = [
self.playing_dead,
!self.playing_dead && water,
!self.playing_dead && !water && ground,
moving,
];
for (v, on) in self.value.iter_mut().zip(flags) {
*v = if on {
(*v + 1).min(10)
} else {
v.saturating_sub(1)
};
}
if baby {
let selected = if self.playing_dead {
6
} else if moving {
if water && !ground {
1
} else if !water && ground {
0
} else {
2
}
} else if water && !ground {
4
} else if water && ground {
5
} else {
3
};
for (i, state) in self.states.iter_mut().enumerate() {
if i == selected {
state.start_if_stopped(age);
} else {
state.stop();
}
}
}
}
pub fn factor(&self, i: usize, partial: f32) -> f32 {
let x = (f32::from(self.old[i])
+ (f32::from(self.value[i]) - f32::from(self.old[i])) * partial)
/ 10.0;
((1.0 - horizon_core::jmath::cos(f64::from(x) * std::f64::consts::PI)) / 2.0) as f32
}
}
pub fn tick_animation(m: &mut Mob) {
if m.species() != Species::Axolotl {
return;
}
let moving =
m.limb_speed > 1.0e-5 || m.yaw != m.previous_yaw || m.head_pitch != m.previous_head_pitch;
let baby = m.is_baby();
m.extra
.axolotl
.tick(baby, m.fluids.in_water, m.on_ground, moving, m.age as f32);
}
#[cfg(test)]
mod axolotl_parity_tests {
use super::*;
use horizon_core::random::LegacyRandom;
#[test]
fn prey_water_range_and_cooldown_match_native() {
assert!(prey_eligible(64.0, true, false, true, false, true));
assert!(!prey_eligible(64.01, true, false, true, false, true));
assert!(!prey_eligible(4.0, false, true, true, false, true));
assert!(!prey_eligible(4.0, true, false, true, true, true));
assert!(prey_eligible(4.0, true, true, false, true, true));
assert!(!prey_eligible(4.0, true, false, false, false, true));
assert!(!prey_eligible(4.0, true, true, true, false, false));
}
#[test]
fn damage_roll_matches_native_draw_order_and_gates() {
for seed in 0..100 {
for (water, entity, already, no_ai) in [
(true, true, false, false),
(false, true, false, false),
(true, false, false, false),
(true, true, true, false),
(true, true, false, true),
] {
let mut expected = LegacyRandom::new(seed);
let mut actual = LegacyRandom::new(seed);
let result = !no_ai
&& expected.next_int_bound(3).unwrap() == 0
&& ((expected.next_int_bound(3).unwrap() as f32) < 2.0 || 4.0f32 / 14.0 < 0.5)
&& 2.0 < 4.0
&& water
&& entity
&& !already;
assert_eq!(
roll_play_dead(&mut actual, no_ai, 4.0, 14.0, 2.0, water, entity, already),
result
);
assert_eq!(actual.next_int(), expected.next_int());
}
}
}
#[test]
fn playing_dead_eases_and_selects_exclusive_baby_pose() {
let mut x = Animation {
playing_dead: true,
..Animation::default()
};
for _ in 0..10 {
x.tick(true, true, true, true, 20.0);
}
assert_eq!(x.factor(0, 1.0), 1.0);
assert_eq!(x.factor(1, 1.0), 0.0);
assert_eq!(x.states.iter().filter(|s| s.started.is_some()).count(), 1);
assert!(x.states[6].started.is_some());
x.playing_dead = false;
for _ in 0..10 {
x.tick(true, true, false, true, 30.0);
}
assert_eq!(x.factor(0, 1.0), 0.0);
assert_eq!(x.factor(1, 1.0), 1.0);
assert!(x.states[1].started.is_some());
}
}
+14 -8
View File
@@ -1011,7 +1011,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
},
a,
),
Species::Axolotl => axolotl(p, s, &Axolotl::from_mob(m), a),
Species::Axolotl => axolotl(p, s, &Axolotl::from_mob(m, s.partial), a),
Species::Frog => frog(
p,
s,
@@ -1031,14 +1031,20 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
true
}
impl Axolotl {
pub fn from_mob(m: &Mob) -> Self {
let in_water = m.fluids.in_water;
pub fn from_mob(m: &Mob, partial: f32) -> Self {
let x = &m.extra.axolotl;
Self {
in_water: if in_water { 1.0 } else { 0.0 },
on_ground: if m.on_ground { 1.0 } else { 0.0 },
walk: m.anim.states[0],
swim: m.anim.states[1],
..Self::default()
playing_dead: x.factor(0, partial),
in_water: x.factor(1, partial),
on_ground: x.factor(2, partial),
moving: x.factor(3, partial),
// Native baby model deliberately reads walkAnimationState, not its underwater counterpart.
walk: x.states[0],
swim: x.states[1],
idle_on_ground: x.states[3],
idle_underwater: x.states[4],
idle_underwater_on_ground: x.states[5],
play_dead: x.states[6],
}
}
}
+1
View File
@@ -301,6 +301,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack {
enchantments: Vec::new(),
potion: None,
map: false,
exploration: None,
ominous_amplifier: None,
}
}
+7 -3
View File
@@ -404,9 +404,10 @@ pub enum Attr {
SpawnReinforcements,
JumpStrength,
Armor,
BurningTime,
}
impl Attr {
pub const ALL: [Self; 8] = [
pub const ALL: [Self; 9] = [
Self::MaxHealth,
Self::MovementSpeed,
Self::FollowRange,
@@ -415,6 +416,7 @@ impl Attr {
Self::SpawnReinforcements,
Self::JumpStrength,
Self::Armor,
Self::BurningTime,
];
pub fn name(self) -> &'static str {
match self {
@@ -426,6 +428,7 @@ impl Attr {
Self::SpawnReinforcements => "spawn_reinforcements",
Self::JumpStrength => "jump_strength",
Self::Armor => "armor",
Self::BurningTime => "burning_time",
}
}
/// `RangedAttribute` bounds.
@@ -438,6 +441,7 @@ impl Attr {
Self::KnockbackResistance | Self::SpawnReinforcements => (0.0, 1.0),
Self::JumpStrength => (0.0, 32.0),
Self::Armor => (0.0, 30.0),
Self::BurningTime => (0.0, 1024.0),
}
}
}
@@ -476,7 +480,7 @@ pub fn base_value(m: &Mob, a: Attr) -> f64 {
.as_ref()
.and_then(|s| s.bases.iter().find(|(x, _)| *x == a).map(|(_, v)| *v))
.or_else(|| default_value(m, a))
.unwrap_or(0.0)
.unwrap_or(if a == Attr::BurningTime { 1.0 } else { 0.0 })
}
/// The transient modifiers of the mob's state (`SPEED_MODIFIER_BABY`).
fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> {
@@ -560,7 +564,7 @@ fn refresh(m: &mut Mob, a: Attr) {
Attr::KnockbackResistance => m.attrs.knockback_resistance = value(m, a),
Attr::SpawnReinforcements => m.attrs.spawn_reinforcements = value(m, a),
Attr::JumpStrength => m.attrs.jump_strength = value(m, a),
Attr::Armor => {}
Attr::Armor | Attr::BurningTime => {}
}
}
/// The value without the transient baby modifier (`speed_bonus` applies
+3 -2
View File
@@ -1229,7 +1229,7 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m
let Some(t) = cx.w.target_info(who) else {
return false;
};
if !t.alive || t.is_player && t.creative {
if !t.alive || !t.can_be_seen_as_enemy || t.is_player && t.creative {
return false;
}
let follow = m.attrs.follow_range * st.follow_scale;
@@ -1287,6 +1287,7 @@ impl Goal for NearestTarget {
let candidates: Vec<(u32, Vec3)> =
cx.w.nearby(pos, range, move |s| {
s.id != id
&& !s.playing_dead
&& match prey {
Prey::Species(list) => list.contains(&s.species),
Prey::Filter(f) => f(s),
@@ -1381,7 +1382,7 @@ impl Goal for HurtByTarget {
let Some(t) = cx.w.target_info(by) else {
return false;
};
t.alive && !(t.is_player && t.creative)
t.alive && t.can_be_seen_as_enemy && !(t.is_player && t.creative)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
target_continue(&mut self.st, true, m, cx)
@@ -364,7 +364,9 @@ fn can_attack(m: &Mob, w: &MobWorld, who: Who) -> bool {
.is_some_and(|p| p.alive && !p.creative && !p.spectator),
Who::Mob(id) => {
let Some(s) = w.seen(id) else { return false };
s.alive && (m.species() != Species::Breeze || s.species == Species::IronGolem)
s.alive
&& !s.playing_dead
&& (m.species() != Species::Breeze || s.species == Species::IronGolem)
}
}
}
+22
View File
@@ -747,6 +747,28 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
};
let mut base = origin * rotation;
if m.extra.fall_flying {
let ticks = m.extra.fall_fly_ticks as f32 + alpha;
let scale = (ticks * ticks / 100.0).min(1.0);
let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha;
base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians());
let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha;
let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos());
let v = m.velocity;
let view_scale = (pitch.to_radians()).mcos();
let (look_x, look_z) = (look_x * view_scale, look_z * view_scale);
let view_length = f64::from(look_x * look_x + look_z * look_z);
let speed = v.x * v.x + v.z * v.z;
if speed > f64::from(1.0e-5f32) && view_length > f64::from(1.0e-5f32) {
let dot =
(v.x * f64::from(look_x) + v.z * f64::from(look_z)) / (speed * view_length).sqrt();
let sign = (v.x * f64::from(look_z) - v.z * f64::from(look_x)).signum();
base *= glam::Mat4::from_rotation_y(
(sign * horizon_core::jmath::acos(dot.abs().min(1.0))) as f32,
);
}
}
if m.death_time > 0 && !super::creaking::tearing_down(m) {
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
.sqrt()
+3
View File
@@ -15,6 +15,7 @@ pub struct TargetInfo {
pub eye_y: f64,
pub bounds: Aabb,
pub alive: bool,
pub can_be_seen_as_enemy: bool,
pub is_player: bool,
pub creative: bool,
}
@@ -205,6 +206,7 @@ impl MobWorld<'_> {
eye_y: p.eye[1],
bounds: p.bounds,
alive: p.alive,
can_be_seen_as_enemy: true,
is_player: true,
creative: p.creative,
}),
@@ -213,6 +215,7 @@ impl MobWorld<'_> {
eye_y: s.eye_y,
bounds: s.bounds,
alive: s.alive,
can_be_seen_as_enemy: !s.playing_dead,
is_player: false,
creative: false,
}),
+2 -2
View File
@@ -56,7 +56,7 @@ pub fn prepare(
sprites: &mut Sprites,
) -> Result<PreparedModels> {
let facts: serde_json::Map<String, Value> =
serde_json::from_reader(std::fs::File::open(root.join("model-states.json"))?)?;
serde_json::from_slice(&std::fs::read(root.join("model-states.json"))?)?;
let blocks: Vec<&str> = facts
.keys()
.filter(|name| registry.default_state(name).is_some())
@@ -111,7 +111,7 @@ pub fn load_visibility(
.tag;
let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?;
let raw: BTreeMap<String, Value> =
serde_json::from_reader(fs::File::open(root.join("render-definitions.json"))?)?;
serde_json::from_slice(&fs::read(root.join("render-definitions.json"))?)?;
let definitions = raw
.into_iter()
.map(|(name, v)| {
+1 -1
View File
@@ -56,7 +56,7 @@ impl StateModels {
sprites: &mut Sprites,
) -> Result<Self> {
let facts: BTreeMap<String, Value> =
serde_json::from_reader(fs::File::open(root.join("model-states.json"))?)?;
serde_json::from_slice(&fs::read(root.join("model-states.json"))?)?;
let mut choices = Vec::new();
let mut states = BTreeMap::new();
let mut variants = BTreeSet::new();
+685 -11
View File
@@ -43,6 +43,7 @@ use std::{
sync::Arc,
};
pub(crate) mod environment;
mod fluids;
pub use fluids::{FluidResources, LAVA, PlayerFluids, WATER};
@@ -112,6 +113,7 @@ pub enum MotionEvent {
enabled: bool,
},
Health(crate::health::HealthEvent),
HurtSound(&'static str),
Fall(crate::landing::FallEvent),
Recorded {
mover: MoverType,
@@ -172,6 +174,11 @@ pub enum MotionEvent {
SplashEvent,
}
pub struct PlayerMotion {
pub swimming: bool,
pub fire_ticks: i32,
pub air: i32,
pub respiration: i32,
pub position: Vec3,
pub velocity: Vec3,
pub ground: GroundState,
@@ -257,6 +264,34 @@ fn attribute_error(error: impl std::fmt::Debug) -> io::Error {
io::Error::other(format!("movement attribute: {error:?}"))
}
impl PlayerMotion {
pub fn load_environment_once(
&mut self,
pending: &mut bool,
extra: Option<&horizon_world::nbt::Tag>,
) {
if std::mem::take(pending) {
self.fire_ticks = extra
.and_then(|t| crate::save::number(t.get("Fire")))
.unwrap_or(-20) as i32;
self.air = extra
.and_then(|t| crate::save::number(t.get("Air")))
.unwrap_or(300) as i32;
}
}
pub fn set_remaining_fire_ticks(&mut self, ticks: i32) {
self.fire_ticks = if self.invulnerable {
ticks.min(1)
} else {
ticks
};
}
pub fn ignite_for_ticks(&mut self, ticks: i32) -> Result<()> {
let scaled = (f64::from(ticks) * self.attribute("minecraft:burning_time")?).ceil() as i32;
self.set_remaining_fire_ticks(self.fire_ticks.max(scaled));
self.ticks_frozen = 0;
Ok(())
}
pub fn new(resources: &MotionResources, position: Vec3) -> Result<Self> {
// Process-owned identities determine native collection callback order.
// Differential fixtures can replay a reference process's identities.
@@ -324,6 +359,10 @@ impl PlayerMotion {
local_crouching: false,
pose: crate::pose::Pose::Standing,
dimensions: crate::pose::Pose::Standing.dimensions(1.0),
swimming: false,
fire_ticks: -20,
air: 300,
respiration: 0,
speed: 0.0,
item_use_speed: None,
last_climbable: None,
@@ -486,6 +525,9 @@ impl PlayerMotion {
horizontal_collision: self.collision.horizontal,
minor_horizontal_collision: self.collision.minor,
moving_slowly: self.moving_slowly(),
in_water: self.fluids.was_touching_water,
under_water: self.is_under_water(),
swimming: self.swimming,
..Default::default()
};
// The sprint setter edits attributes and flags, independent of local
@@ -611,10 +653,17 @@ impl MotionWorld<'_, '_, '_> {
/// caller applies LocalPlayer input preparation once. Empty inventory,
/// equipment and nearby-entity sets are the current scene domain.
pub fn player_movement_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> {
self.fluid_base_tick()?;
self.player_movement_tick_with_fluids(direction, jumping)
}
fn player_movement_tick_with_fluids(
&mut self,
direction: [f32; 2],
jumping: bool,
) -> Result<()> {
// Entity.baseTick
self.player.was_in_powder_snow = self.player.in_powder_snow;
self.player.in_powder_snow = false;
self.fluid_base_tick()?;
self.player.old_position = self.player.position;
if self.player.jump_trigger_time > 0 {
self.player.jump_trigger_time -= 1;
@@ -641,14 +690,22 @@ impl MotionWorld<'_, '_, '_> {
}
let toggled = flying_before != self.player.flying;
// Player.tryToStartFallFlying (canGlide: airborne, not flying, a glider).
let can_glide = self.player.glider && !self.player.ground.on_ground && !self.player.flying;
let can_glide = self.player.glider
&& !self.player.ground.on_ground
&& !self.player.flying
&& !self.player.fluids.was_touching_water
&& !self.player.is_in_lava();
if jumping && !toggled && !was_jumping && !self.player.fall_flying && can_glide {
self.player.fall_flying = true;
}
// LivingEntity.tick fallFlyTicks, then updateFallFlying.
if self.player.fall_flying {
self.player.fall_fly_ticks += 1;
let still = self.player.glider && !self.player.ground.on_ground && !self.player.flying;
let still = self.player.glider
&& !self.player.ground.on_ground
&& !self.player.flying
&& !self.player.fluids.was_touching_water
&& !self.player.is_in_lava();
if !still {
self.player.fall_flying = false;
} else if (self.player.fall_fly_ticks + 1) % 10 == 0
@@ -688,8 +745,14 @@ impl MotionWorld<'_, '_, '_> {
/// services are still incomplete; this composes clocks, movement and hunger.
pub fn simulation_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> {
self.player.health.advance_clock();
self.fluid_base_tick()?;
self.simulation_tick_with_fluids(direction, jumping)
}
fn simulation_tick_with_fluids(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> {
self.tick_environment_damage()?;
let previous = self.player.position;
self.player_movement_tick(direction, jumping)?;
self.player_movement_tick_with_fluids(direction, jumping)?;
self.apply_fire_contact()?;
self.player.refresh_attributes()?;
self.update_player_pose()?;
// The resident scene accepts the resolved local movement directly.
@@ -708,6 +771,8 @@ impl MotionWorld<'_, '_, '_> {
self.player.auto_jump_time -= 1;
keys.jump = true;
}
self.player.health.advance_clock();
self.fluid_base_tick()?;
self.player.sprint_input_tick(keys)?;
self.player.shift_key_down = keys.shift;
let direction = keys.direction();
@@ -719,7 +784,7 @@ impl MotionWorld<'_, '_, '_> {
} else {
None
};
self.simulation_tick(
self.simulation_tick_with_fluids(
crate::input::modify_input(direction, self.player.item_use_speed, sneak),
keys.jump,
)
@@ -756,14 +821,44 @@ impl MotionWorld<'_, '_, '_> {
input.x = 0.0;
input.z = 0.0;
}
if self.player.shift_key_down
&& !self.player.flying
&& self.player.fluids.was_touching_water
{
self.player.velocity.y -= f64::from(0.04f32);
}
if self.player.jumping {
if self.player.ground.on_ground && self.player.no_jump_delay == 0 {
let in_lava = self.player.is_in_lava();
let height = self.player.fluid_height(if in_lava { LAVA } else { WATER });
let water_jump = self.player.fluids.was_touching_water
&& height > 0.0
&& (!self.player.ground.on_ground || height > 0.4);
let lava_jump = in_lava && (!self.player.ground.on_ground || height > 0.4);
if !self.player.flying && (water_jump || lava_jump) {
self.player.velocity.y += f64::from(0.04f32);
} else if self.player.ground.on_ground && self.player.no_jump_delay == 0 {
self.jump_from_ground()?;
self.player.no_jump_delay = 10;
}
} else {
self.player.no_jump_delay = 0;
}
if self.player.swimming {
let look_y =
horizon_world::view_direction::view_vector(self.player.pitch, self.player.yaw).y;
let near_surface = BlockPos::containing(Vec3::new(
self.player.position.x,
self.player.position.y + 0.9,
self.player.position.z,
));
if look_y <= 0.0
|| self.player.jumping
|| self.fluid_at(near_surface).kind() != horizon_world::fluid::FluidKind::Empty
{
let blend = if look_y < -0.2 { 0.085 } else { 0.06 };
self.player.velocity.y += (look_y - self.player.velocity.y) * blend;
}
}
if self.player.fall_flying {
self.travel_fall_flying()?;
} else if self.player.flying {
@@ -771,6 +866,10 @@ impl MotionWorld<'_, '_, '_> {
let y = self.player.velocity.y;
self.travel_in_air(input)?;
self.player.velocity.y = y * 0.6;
} else if !self.player.flying
&& (self.player.fluids.was_touching_water || self.player.is_in_lava())
{
horizon_world::living_fluid::travel_in_fluid(self, input)?;
} else {
self.travel_in_air(input)?;
}
@@ -1229,13 +1328,13 @@ impl MovementStatisticsWorld for MotionWorld<'_, '_, '_> {
Ok(false)
}
fn swimming(&mut self) -> Result<bool> {
Ok(false)
Ok(self.player.swimming)
}
fn eyes_in_water(&mut self) -> Result<bool> {
Ok(false)
Ok(self.player.is_eye_in_fluid(WATER))
}
fn in_water(&mut self) -> Result<bool> {
Ok(false)
Ok(self.player.fluids.was_touching_water)
}
fn on_climbable(&mut self) -> Result<bool> {
self.climbable()
@@ -1560,10 +1659,10 @@ impl MovementEmissionWorld for MotionWorld<'_, '_, '_> {
Ok(false)
}
fn swimming(&mut self) -> Result<bool> {
Ok(false)
Ok(self.player.swimming)
}
fn in_water(&mut self) -> Result<bool> {
Ok(false)
Ok(self.player.fluids.was_touching_water)
}
fn walking_step_sound(&mut self, position: BlockPos, state: BlockStateId) -> Result<()> {
self.player
@@ -1838,9 +1937,584 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> {
mod tests {
use super::*;
#[test]
fn player_fire_damage_queues_hurt_sound_only_for_fresh_hits() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
for name in ["on_fire", "in_fire", "lava"] {
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
let source = resources
.health
.damage
.id(&format!("minecraft:{name}"))
.unwrap();
assert!(
player
.hurt(&resources.health, Default::default(), source, 1.0)
.unwrap()
);
assert_eq!(
player
.events
.iter()
.filter(|e| matches!(
e,
MotionEvent::HurtSound("minecraft:entity.player.hurt_on_fire")
))
.count(),
1
);
player.events.clear();
assert!(
!player
.hurt(&resources.health, Default::default(), source, 1.0)
.unwrap()
);
assert!(
!player
.events
.iter()
.any(|e| matches!(e, MotionEvent::HurtSound(_)))
);
for _ in 0..20 {
player.health.advance_clock();
}
player.invulnerable = true;
player.events.clear();
assert!(
!player
.hurt(&resources.health, Default::default(), source, 1.0)
.unwrap()
);
assert!(
!player
.events
.iter()
.any(|e| matches!(e, MotionEvent::HurtSound(_)))
);
}
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
let source = resources.health.damage.id("minecraft:mob_attack").unwrap();
assert!(
player
.hurt_blocking(&resources.health, Default::default(), source, 2.0, None)
.unwrap()
.hurt
);
assert_eq!(
player
.events
.iter()
.filter(|e| matches!(e, MotionEvent::HurtSound("minecraft:entity.player.hurt")))
.count(),
1
);
}
/// Footsteps on the prepared vanilla resources, when they are present:
/// none while standing (gravity still moves the player every tick), one
/// per `nextStep` metre while walking.
#[test]
fn resident_water_landing_cancels_a_preset_fall() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let binding = crate::collisions::load(&root, assets.registry).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
for wet in [false, true] {
let mut scene = World::test_scene(&assets, 2).unwrap();
if wet {
let water = assets.registry.default_state("minecraft:water").unwrap();
for x in 19..=21 {
for z in 19..=21 {
scene.set(x, 3, z, water).unwrap();
}
}
}
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 20.0, 20.5)).unwrap();
player.fall_distance = 30.0;
let mut w = MotionWorld {
player: &mut player,
scene: &mut scene,
assets: &assets,
collision_binding: &binding,
resources: &resources,
};
w.move_self(Vec3::new(0.0, -30.0, 0.0)).unwrap();
assert!(w.player.ground.on_ground);
assert_eq!(w.player.fluids.was_touching_water, wet);
if wet {
assert_eq!(w.player.health.health(), 20.0);
assert_eq!(w.player.fall_distance, 0.0);
} else {
assert!(w.player.health.health() < 20.0);
}
}
}
#[test]
fn resident_water_and_lava_are_not_treated_as_air() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let binding = crate::collisions::load(&root, assets.registry).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
let mut scene = World::test_scene(&assets, 3).unwrap();
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
let water = assets.registry.default_state("minecraft:water").unwrap();
for x in 19..=21 {
for y in 3..=7 {
for z in 19..=21 {
scene.set(x, y, z, water).unwrap();
}
}
}
let mut w = MotionWorld {
player: &mut player,
scene: &mut scene,
assets: &assets,
collision_binding: &binding,
resources: &resources,
};
w.controlled_simulation_tick(Default::default()).unwrap();
assert!(
MovementStatisticsWorld::in_water(&mut w).unwrap(),
"resident water must reach the player movement adapter"
);
assert!(MovementStatisticsWorld::eyes_in_water(&mut w).unwrap());
assert!(
!w.player.fluids.was_eye_in_water,
"the first controlled tick must run only one fluid base phase"
);
assert!(
(w.player.velocity.y + 0.005).abs() < 1e-5,
"water drag/gravity must replace air travel: {:?}",
w.player.velocity
);
let lava = assets.registry.default_state("minecraft:lava").unwrap();
for x in 19..=21 {
for y in 3..=7 {
for z in 19..=21 {
w.scene.set(x, y, z, lava).unwrap();
}
}
}
w.controlled_simulation_tick(Default::default()).unwrap();
assert!(
w.player.health.health() < 20.0,
"lava must damage a survival player"
);
// Water extinguishes, swimming is a real pose, and deep water consumes air.
for x in 19..=21 {
for y in 3..=7 {
for z in 19..=21 {
w.scene.set(x, y, z, water).unwrap();
}
}
}
w.player.fire_ticks = 160;
w.controlled_simulation_tick(Default::default()).unwrap();
assert!(w.player.fire_ticks <= 0);
w.player.air = -19;
w.player.health.hurt.cooldown = 0;
let hp = w.player.health.health();
w.controlled_simulation_tick(Default::default()).unwrap();
assert_eq!(w.player.air, 0);
assert!(w.player.health.health() < hp, "drowning must hurt");
w.player.invulnerable = true;
let hp = w.player.health.health();
w.player.air = -19;
w.controlled_simulation_tick(Default::default()).unwrap();
assert_eq!(w.player.health.health(), hp);
w.player.invulnerable = false;
w.player.air = 300;
w.controlled_simulation_tick(crate::sprint::Keys {
forward: true,
sprint: true,
..Default::default()
})
.unwrap();
assert!(w.player.sprinting);
assert!(
!w.player.swimming,
"sprint input follows the swimming phase"
);
w.controlled_simulation_tick(crate::sprint::Keys {
forward: true,
sprint: true,
..Default::default()
})
.unwrap();
assert!(w.player.swimming);
assert_eq!(w.player.pose, crate::pose::Pose::Swimming);
// Direct fire contact ignites; resistance prevents damage but does not hide flames.
let fire = assets.registry.default_state("minecraft:fire").unwrap();
for x in 19..=21 {
for y in 3..=7 {
for z in 19..=21 {
w.scene.set(x, y, z, fire).unwrap();
}
}
}
w.player.position = Vec3::new(20.5, 4.0, 20.5);
w.player.velocity = Vec3::ZERO;
w.player.fire_ticks = -20;
w.player.health.hurt.cooldown = 0;
w.player.ticks_frozen = 140;
let hp = w.player.health.health();
w.controlled_simulation_tick(Default::default()).unwrap();
assert!(
w.player.fire_ticks < 0,
"direct fire hurts during the immunity delay"
);
assert_eq!(
w.player.ticks_frozen, 0,
"fire contact clears freeze during the delay"
);
assert!(w.player.health.health() < hp);
w.player.status.fire_resistance = true;
w.player.health.hurt.cooldown = 0;
let hp = w.player.health.health();
w.controlled_simulation_tick(Default::default()).unwrap();
assert_eq!(w.player.health.health(), hp);
w.player.invulnerable = true;
w.player.fire_ticks = -20;
w.player.ticks_frozen = 140;
w.controlled_simulation_tick(Default::default()).unwrap();
assert_eq!(w.player.ticks_frozen, 0);
assert_eq!(
w.player.fire_ticks, -19,
"creative preserves the fire-contact delay"
);
for _ in 0..18 {
w.apply_fire_contact().unwrap();
}
assert_eq!(w.player.fire_ticks, -1);
w.apply_fire_contact().unwrap();
assert_eq!(
w.player.fire_ticks, 1,
"creative clamps only after ignition"
);
w.player.ticks_frozen = 140;
w.player.ignite_for_ticks(160).unwrap();
assert_eq!(w.player.ticks_frozen, 0);
assert_eq!(w.player.fire_ticks, 1);
w.player.invulnerable = false;
// Sprint swimming must keep full input, not the dry crawl/sneak multiplier.
for x in 19..=21 {
for y in 2..=7 {
for z in 19..=30 {
w.scene.set(x, y, z, water).unwrap();
}
}
}
w.player.position = Vec3::new(20.5, 4.0, 20.5);
w.player.velocity = Vec3::ZERO;
w.player.local_crouching = false;
w.player.swimming = true;
w.player.sprinting = true;
w.player.set_pose(crate::pose::Pose::Swimming).unwrap();
for _ in 0..30 {
w.controlled_simulation_tick(crate::sprint::Keys {
forward: true,
sprint: true,
..Default::default()
})
.unwrap();
}
assert!(
w.player.velocity.z > 0.165,
"native sprint swim speed must not receive crawl slowdown: {:?}",
w.player.velocity
);
assert!(!w.player.moving_slowly());
w.player.position = Vec3::new(20.5, 4.0, 20.5);
w.player.velocity = Vec3::ZERO;
w.player.pitch = 45.0;
w.controlled_simulation_tick(crate::sprint::Keys {
forward: true,
sprint: true,
..Default::default()
})
.unwrap();
assert!(
w.player.velocity.y < -0.04,
"look down must steer a swimming player downward"
);
w.player.position = Vec3::new(20.5, 4.0, 20.5);
w.player.velocity = Vec3::ZERO;
w.player.pitch = -45.0;
w.controlled_simulation_tick(crate::sprint::Keys {
forward: true,
sprint: true,
..Default::default()
})
.unwrap();
assert!(
w.player.velocity.y > 0.02,
"look up must steer a submerged swimmer upward"
);
let extra = horizon_world::nbt::Tag::compound([
("Fire", horizon_world::nbt::Tag::Short(160)),
("Air", horizon_world::nbt::Tag::Short(8)),
]);
let mut pending = true;
w.player.load_environment_once(&mut pending, Some(&extra));
assert_eq!((w.player.fire_ticks, w.player.air), (160, 8));
let mut respawn = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
respawn.load_environment_once(&mut pending, Some(&extra));
assert_eq!((respawn.fire_ticks, respawn.air), (-20, 300));
w.player.fluids.was_touching_water = false;
assert!(
w.player.moving_slowly(),
"dry crawling must still slow input"
);
}
#[test]
fn resident_swimming_uses_previous_eyes_and_requires_water_at_the_feet() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let binding = crate::collisions::load(&root, assets.registry).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
let mut scene = World::test_scene(&assets, 3).unwrap();
let water = assets.registry.default_state("minecraft:water").unwrap();
for y in 4..=6 {
scene.set(20, y, 20, water).unwrap();
}
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
let mut w = MotionWorld {
player: &mut player,
scene: &mut scene,
assets: &assets,
collision_binding: &binding,
resources: &resources,
};
w.player.local_crouching = true;
let sprint = crate::sprint::Keys {
forward: true,
sprint: true,
..Default::default()
};
w.fluid_base_tick().unwrap();
assert!(w.player.is_eye_in_fluid(WATER));
assert!(!w.player.is_under_water());
w.player.sprint_input_tick(sprint).unwrap();
assert!(
!w.player.sprinting,
"new eye immersion cannot bypass crouching"
);
w.fluid_base_tick().unwrap();
assert!(w.player.is_under_water());
w.player.sprint_input_tick(sprint).unwrap();
assert!(w.player.sprinting);
assert!(!w.player.swimming, "sprint starts after the base tick");
w.fluid_base_tick().unwrap();
assert!(w.player.swimming);
let air = assets.registry.default_state("minecraft:air").unwrap();
w.scene.set(20, 4, 20, air).unwrap();
w.player.swimming = false;
w.fluid_base_tick().unwrap();
assert!(w.player.is_under_water());
assert!(
!w.player.swimming,
"starting a swim requires water in the feet cell"
);
w.player.swimming = true;
w.fluid_base_tick().unwrap();
assert!(
w.player.swimming,
"an existing swim only requires touching water"
);
w.player.flying = true;
w.fluid_base_tick().unwrap();
assert!(!w.player.swimming);
w.player.flying = false;
w.player.spectator = true;
w.scene.set(20, 4, 20, water).unwrap();
w.fluid_base_tick().unwrap();
assert!(
w.player.swimming,
"spectator flight is applied later in aiStep"
);
}
#[test]
fn resident_fire_precedes_first_tick_lava_and_water_extinguishing() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let binding = crate::collisions::load(&root, assets.registry).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
for name in ["minecraft:lava", "minecraft:water"] {
let mut scene = World::test_scene(&assets, 3).unwrap();
let fluid = assets.registry.default_state(name).unwrap();
scene.set(20, 4, 20, fluid).unwrap();
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
player.fire_ticks = 160;
player.fall_distance = 8.0;
let mut w = MotionWorld {
player: &mut player,
scene: &mut scene,
assets: &assets,
collision_binding: &binding,
resources: &resources,
};
w.fluid_base_tick().unwrap();
assert_eq!(
w.player.health.health(),
19.0,
"base on-fire damage: {name}"
);
if name == "minecraft:lava" {
assert_eq!(w.player.fire_ticks, 159);
assert_eq!(w.player.fall_distance, 8.0, "first tick excludes lava");
w.fluid_base_tick().unwrap();
assert_eq!(
w.player.fall_distance, 4.0,
"later ticks halve exactly once"
);
} else {
assert_eq!(w.player.fire_ticks, 0, "water extinguishes after the hurt");
assert_eq!(w.player.fall_distance, 0.0);
w.player.fire_ticks = -7;
w.fluid_base_tick().unwrap();
assert_eq!(
w.player.fire_ticks, -7,
"clearing fire retains negative delay"
);
}
}
}
#[test]
fn resident_bubble_columns_and_nautilus_preserve_their_air_rules() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let binding = crate::collisions::load(&root, assets.registry).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
let mut scene = World::test_scene(&assets, 3).unwrap();
let water = assets.registry.default_state("minecraft:water").unwrap();
scene.set(20, 4, 20, water).unwrap();
scene.set(20, 5, 20, water).unwrap();
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
let mut w = MotionWorld {
player: &mut player,
scene: &mut scene,
assets: &assets,
collision_binding: &binding,
resources: &resources,
};
for (extra_effect, expected_air) in [
(None, -19),
(Some("water_breathing"), -15),
(Some("conduit_power"), -15),
] {
let mut effects = crate::effects::PlayerEffects::default();
effects.add(crate::effects::EffectInstance::new(
"breath_of_the_nautilus",
200,
0,
));
if let Some(id) = extra_effect {
effects.add(crate::effects::EffectInstance::new(id, 200, 0));
}
w.player.status = effects.status();
assert!(w.player.status.breath_of_the_nautilus);
w.player.air = -19;
w.fluid_base_tick().unwrap();
w.tick_environment_damage().unwrap();
assert_eq!(w.player.air, expected_air);
assert_eq!(w.player.health.health(), 20.0);
}
w.player.status.water_breathing = false;
for (name, nautilus) in [
("minecraft:bubble_column", false),
("minecraft:bubble_column", true),
("minecraft:air", true),
] {
w.scene
.set(20, 5, 20, assets.registry.default_state(name).unwrap())
.unwrap();
w.player.status.breath_of_the_nautilus = nautilus;
w.player.air = -19;
w.fluid_base_tick().unwrap();
w.tick_environment_damage().unwrap();
assert_eq!(w.player.air, -15, "{name}, nautilus={nautilus}");
assert_eq!(w.player.health.health(), 20.0);
}
w.scene.set(20, 5, 20, water).unwrap();
w.player.status.breath_of_the_nautilus = false;
w.player.air = -19;
w.fluid_base_tick().unwrap();
w.tick_environment_damage().unwrap();
assert_eq!(w.player.air, 0);
assert_eq!(w.player.health.health(), 18.0);
}
#[test]
fn resident_mixed_fluids_use_lava_height_for_ground_jumps() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let binding = crate::collisions::load(&root, assets.registry).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
for (water_level, lava_level, ground_jump) in [(0, 6, true), (6, 0, false)] {
let mut scene = World::test_scene(&assets, 3).unwrap();
for (name, level, x) in [
("minecraft:water", water_level, 20),
("minecraft:lava", lava_level, 21),
] {
let mut state = assets
.registry
.state(assets.registry.default_state(name).unwrap())
.unwrap()
.clone();
state.properties.insert("level".into(), level.to_string());
scene
.set(x, 4, 20, assets.registry.id(&state).unwrap())
.unwrap();
}
let mut player = PlayerMotion::new(&resources, Vec3::new(21.0, 4.0, 20.5)).unwrap();
player.ground.on_ground = true;
let mut w = MotionWorld {
player: &mut player,
scene: &mut scene,
assets: &assets,
collision_binding: &binding,
resources: &resources,
};
w.fluid_base_tick().unwrap();
assert!(w.player.fluids.was_touching_water && w.player.is_in_lava());
assert_eq!(w.player.fluid_height(LAVA) <= 0.4, ground_jump);
assert_eq!(w.player.fluid_height(WATER) > 0.4, ground_jump);
w.dry_tick(TickInput::PreparedLocal {
direction: [0.0; 2],
jumping: true,
})
.unwrap();
assert_eq!(w.player.no_jump_delay == 10, ground_jump);
}
}
#[test]
fn footsteps_follow_the_walked_distance_not_the_tick() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
@@ -0,0 +1,217 @@
//! Player liquid travel and environmental damage over the shared fluid state.
use super::*;
use horizon_core::random::RandomSource;
use horizon_world::{
fluid::FluidKind,
living_fluid::{LivingFluidWorld, TravelFluidTag},
};
impl MotionWorld<'_, '_, '_> {
fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> {
if self.player.invulnerable || self.player.spectator {
return Ok(());
}
let id = self
.resources
.health
.damage
.id(source)
.ok_or("missing environment damage type")?;
self.player
.hurt(&self.resources.health, self.scene.health_rules, id, damage)?;
Ok(())
}
pub(super) fn tick_remaining_fire(&mut self) -> Result<()> {
if self.player.spectator {
self.player.fire_ticks = 0;
}
if self.player.invulnerable && self.player.fire_ticks > 1 {
self.player.fire_ticks = 1;
}
if self.player.fire_ticks > 0 {
if self.player.fire_ticks % 20 == 0 && !self.player.is_in_lava() {
self.environment_hurt("minecraft:on_fire", 1.0)?;
}
self.player.fire_ticks -= 1;
}
if self.player.fluids.was_touching_water {
self.player.fire_ticks = self.player.fire_ticks.min(0);
}
Ok(())
}
pub(super) fn tick_environment_damage(&mut self) -> Result<()> {
let eye = BlockPos::containing(self.player.position.add_vector(Vec3::new(
0.0,
f64::from(self.player.dimensions.eye_height),
0.0,
)));
let bubble_column = self
.assets
.registry
.state(self.block(eye))
.is_some_and(|state| state.name == "minecraft:bubble_column");
let submerged = self.player.is_eye_in_fluid(WATER) && !bubble_column;
if submerged
&& !self.player.status.water_breathing
&& !self.player.status.breath_of_the_nautilus
&& !self.player.invulnerable
&& !self.player.spectator
{
let oxygen = self
.player
.attribute("minecraft:oxygen_bonus")?
.max(f64::from(self.player.respiration));
if oxygen <= 0.0 || self.scene.random.next_double() < 1.0 / (oxygen + 1.0) {
self.player.air -= 1;
}
if self.player.air <= -20 {
self.player.air = 0;
self.environment_hurt("minecraft:drown", 2.0)?;
}
} else if !submerged
|| !self.player.status.breath_of_the_nautilus
|| self.player.status.water_breathing
{
self.player.air = (self.player.air + 4).min(300);
}
if self.player.is_in_lava() {
self.player.ignite_for_ticks(300)?;
self.environment_hurt("minecraft:lava", 4.0)?;
}
Ok(())
}
pub(super) fn apply_fire_contact(&mut self) -> Result<()> {
if self.player.spectator {
self.player.fire_ticks = 0;
return Ok(());
}
let damage = fire_contact(self.scene, self.assets.registry, self.player.bounds());
if damage > 0.0 {
self.player.ticks_frozen = 0;
if !self.player.fluids.was_touching_water {
let multiplier = self.player.attribute("minecraft:burning_time")?;
let ticks = ignite_contact(
self.player.fire_ticks,
true,
&mut self.scene.random,
multiplier,
);
self.player.set_remaining_fire_ticks(ticks);
}
self.environment_hurt("minecraft:in_fire", damage)?;
} else if self.player.fire_ticks <= 0 {
self.player.fire_ticks = -20;
}
Ok(())
}
}
pub(crate) fn fire_contact(
world: &World,
registry: &horizon_world::registry::BlockRegistry,
bounds: Aabb,
) -> f32 {
let b = bounds.deflate(Vec3::new(1e-5, 1e-5, 1e-5));
let mut damage = 0.0f32;
for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 {
for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 {
for z in b.min_position().z.floor() as i32..=b.max_position().z.floor() as i32 {
damage = damage.max(
match registry
.state(world.block(x, y, z))
.map(|s| s.name.as_str())
{
Some("minecraft:fire") => 1.0,
Some("minecraft:soul_fire") => 2.0,
_ => 0.0,
},
);
}
}
}
damage
}
impl LivingFluidWorld for MotionWorld<'_, '_, '_> {
fn in_water(&mut self) -> Result<bool> {
Ok(self.player.fluids.was_touching_water)
}
fn sprinting(&mut self) -> Result<bool> {
Ok(self.player.sprinting)
}
fn water_slow_down(&mut self) -> Result<f32> {
Ok(0.8)
}
fn water_movement_efficiency(&mut self) -> Result<f64> {
self.player.attribute("minecraft:water_movement_efficiency")
}
fn dolphins_grace(&mut self) -> Result<bool> {
Ok(self.player.status.dolphins_grace)
}
fn fluid_height(&mut self, tag: TravelFluidTag) -> Result<f64> {
Ok(self.player.fluid_height(if tag == TravelFluidTag::Lava {
LAVA
} else {
WATER
}))
}
fn fluid_jump_threshold(&mut self) -> Result<f64> {
Ok(0.4)
}
fn is_free(&mut self, v: Vec3) -> Result<bool> {
let b = self.player.bounds().move_by(v);
Ok(self.no_player_collision(b)? && !self.has_liquid(b)?)
}
fn is_vehicle(&mut self) -> Result<bool> {
Ok(false)
}
fn can_float_while_ridden(&mut self) -> Result<bool> {
Ok(false)
}
}
impl MotionWorld<'_, '_, '_> {
fn has_liquid(&self, b: Aabb) -> Result<bool> {
for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 {
for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 {
for z in b.min_position().z.floor() as i32..=b.max_position().z.floor() as i32 {
if self.fluid_at(BlockPos::new(x, y, z)).kind() != FluidKind::Empty {
return Ok(true);
}
}
}
}
Ok(false)
}
}
pub(crate) fn ignite_contact(
ticks: i32,
player: bool,
random: &mut impl RandomSource,
multiplier: f64,
) -> i32 {
let ticks = if ticks < 0 {
ticks + 1
} else if player {
ticks + 1 + random.next_int_bound(2).unwrap_or(0)
} else {
ticks
};
if ticks >= 0 {
ticks.max((160.0 * multiplier).ceil() as i32)
} else {
ticks
}
}
#[cfg(test)]
mod fire_ignition_tests {
use super::*;
#[test]
fn fire_hurts_before_twenty_tick_ignition_and_scales_duration() {
let mut r = horizon_core::random::LegacyRandom::new(3);
let mut ticks = -20;
for _ in 0..19 {
ticks = ignite_contact(ticks, true, &mut r, 0.4);
assert!(ticks < 0);
}
assert_eq!(ignite_contact(ticks, true, &mut r, 0.4), 64);
}
}
+19 -2
View File
@@ -109,6 +109,10 @@ impl PlayerMotion {
pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool {
self.fluids.interaction.is_eye_in_fluid(&Membership, tag)
}
/// `Player.isUnderWater`: the eye sample from the start of the base tick.
pub fn is_under_water(&self) -> bool {
self.fluids.was_eye_in_water && self.fluids.was_touching_water
}
/// `Entity.isInLava`.
pub fn is_in_lava(&self) -> bool {
!self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA)
@@ -121,14 +125,27 @@ impl FluidMembership for Membership {
}
}
impl MotionWorld<'_, '_, '_> {
fn fluid_at(&self, p: BlockPos) -> FluidState {
pub(super) fn fluid_at(&self, p: BlockPos) -> FluidState {
self.resources.fluids.fluid(self.block(p))
}
/// `Entity.baseTick`'s fluid phase: `wasEyeInWater`, `updateFluidInteraction`,
/// the lava's fall halving, and the end of the first tick.
/// swimming and remaining fire, lava's fall halving, then the first-tick clear.
pub fn fluid_base_tick(&mut self) -> Result<()> {
self.player.fluids.was_eye_in_water = self.player.is_eye_in_fluid(WATER);
self.update_fluids()?;
self.player.swimming = !self.player.flying
&& self.player.sprinting
&& if self.player.swimming {
self.player.fluids.was_touching_water
} else {
self.player.is_under_water()
&& is_tagged(
self.fluid_at(BlockPos::containing(self.player.position))
.kind(),
WATER,
)
};
self.tick_remaining_fire()?;
if self.player.is_in_lava() {
self.player.fall_distance *= 0.5;
}
+122
View File
@@ -0,0 +1,122 @@
//! The offline player name, when neither `--name`, `HORIZON_PLAYER_NAME` nor a
//! signed-in account gives one. Vanilla's client defaults `--username` to
//! `"Player" + System.currentTimeMillis() % 1000` (net.minecraft.client.main.Main)
//! and the official launcher always passes the account's name, so two players
//! rarely share one. Horizon used plain `Player` for everyone, which is also
//! the LAN host's own profile: every guest got the host's offline UUID and was
//! refused with "You logged in from another location". The generated name is
//! kept in `horizon-player.txt` next to `options.txt` so the same player gets
//! the same offline UUID (and inventory on a friend's world) every time.
use std::{fs, path::Path};
pub const FILE: &str = "horizon-player.txt";
const KEY: &str = "name:";
/// StringUtil.isValidPlayerName, plus not empty (the login screen sends at least one character).
pub fn is_valid(name: &str) -> bool {
crate::lan::conn::valid_name(name)
}
/// `Player` and five digits (vanilla's default has three: one shared name in a
/// thousand pairs is too many for a game that keeps it).
pub fn generate(seed: u64) -> String {
format!("Player{:05}", seed % 100_000)
}
/// The name kept in `dir`, created on first use. A file that can't be written
/// still yields a name for this run.
pub fn load_or_create(dir: &Path) -> String {
let path = dir.join(FILE);
if let Some(name) = fs::read_to_string(&path).ok().and_then(|text| parse(&text)) {
return name;
}
let name = generate(seed());
if let Err(e) = fs::write(&path, format!("{KEY}{name}\n")) {
log::warn!(
"Horizon: could not keep the player name in {}: {e}",
path.display()
);
}
name
}
fn parse(text: &str) -> Option<String> {
text.lines()
.find_map(|line| line.trim_end_matches('\r').strip_prefix(KEY))
.filter(|name| is_valid(name))
.map(str::to_owned)
}
fn seed() -> u64 {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as u64);
// Two players starting the game in the same millisecond still differ.
let mut x = nanos ^ u64::from(std::process::id()).rotate_left(32);
x ^= x >> 33;
x = x.wrapping_mul(0xff51_afd7_ed55_8ccd);
x ^ (x >> 33)
}
#[cfg(test)]
mod tests {
use super::*;
fn dir(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!(
"horizon-offline-name-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn generated_names_are_valid_and_never_the_hosts_profile() {
for seed in [0, 7, 99_999, 100_000, u64::MAX] {
let name = generate(seed);
assert!(is_valid(&name), "{name}");
// The LAN host's own profile (game/chat.rs PLAYER_NAME).
assert_ne!(name, "Player");
assert_eq!(name.len(), 11);
}
assert_eq!(generate(42), "Player00042");
}
#[test]
fn the_name_is_kept_and_reused() {
let d = dir("kept");
let first = load_or_create(&d);
assert_eq!(
fs::read_to_string(d.join(FILE)).unwrap(),
format!("name:{first}\n")
);
assert_eq!(load_or_create(&d), first);
// An edited name is used as it is.
fs::write(d.join(FILE), "name:Alex_2\r\n").unwrap();
assert_eq!(load_or_create(&d), "Alex_2");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn invalid_names_are_replaced() {
for text in [
"",
"name:",
"name:has space",
"name:ThisNameIsTooLong17",
"name:été",
] {
let d = dir("invalid");
fs::write(d.join(FILE), text).unwrap();
let name = load_or_create(&d);
assert!(
name.starts_with("Player") && is_valid(&name),
"{text:?} -> {name}"
);
assert_eq!(load_or_create(&d), name);
let _ = fs::remove_dir_all(&d);
}
}
}
+4 -1
View File
@@ -72,7 +72,7 @@ impl PlayerMotion {
Ok(())
}
pub fn moving_slowly(&self) -> bool {
self.local_crouching || self.pose == Pose::Swimming // dry scene: not in water
self.local_crouching || (self.pose == Pose::Swimming && !self.fluids.was_touching_water)
}
}
impl MotionWorld<'_, '_, '_> {
@@ -87,6 +87,7 @@ impl MotionWorld<'_, '_, '_> {
/// the old shift input. This is distinct from Entity's current pose.
pub fn update_local_crouching(&mut self) -> Result<()> {
self.player.local_crouching = !self.player.flying
&& !self.player.swimming
&& self.can_fit_pose(Pose::Crouching)?
&& (self.player.shift_key_down || !self.can_fit_pose(Pose::Standing)?);
Ok(())
@@ -99,6 +100,8 @@ impl MotionWorld<'_, '_, '_> {
}
let desired = if self.player.fall_flying {
Pose::FallFlying
} else if self.player.swimming {
Pose::Swimming
} else if self.player.shift_key_down && !self.player.flying {
Pose::Crouching
} else {
+85
View File
@@ -175,6 +175,41 @@ impl Projectile {
*critical = value;
}
}
/// `AbstractArrow.tick`: critical streaks and submerged bubble trails.
pub fn arrow_trail(
&self,
water: bool,
) -> Vec<(crate::particles::ParticleType, [f64; 3], [f64; 3])> {
use crate::particles::ParticleType;
let mut trail = Vec::new();
if self.stuck || !self.is_arrow() {
return trail;
}
let (p, v) = (self.position, self.velocity);
if water {
let drag = f64::from(0.6f32);
let speed = [v.x * drag, v.y * drag, v.z * drag];
let at = [
p.x - speed[0] * 0.25,
p.y - speed[1] * 0.25,
p.z - speed[2] * 0.25,
];
for _ in 0..4 {
trail.push((ParticleType::Bubble, at, speed));
}
}
if matches!(self.kind, ProjectileKind::Arrow { critical: true, .. }) {
for i in 0..4 {
let t = i as f64 / 4.0;
trail.push((
ParticleType::Crit,
[p.x + v.x * t, p.y + v.y * t, p.z + v.z * t],
[-v.x, -v.y + 0.2, -v.z],
));
}
}
trail
}
pub fn is_arrow(&self) -> bool {
matches!(self.kind, ProjectileKind::Arrow { .. })
}
@@ -743,3 +778,53 @@ mod tests {
assert!((p.velocity.x - 0.19).abs() < 1e-9);
}
}
#[cfg(test)]
mod trail_tests {
use super::*;
use crate::particles::ParticleType;
fn arrow(critical: bool) -> Projectile {
let mut p = Projectile::new(
ProjectileKind::Arrow {
base_damage: 2.0,
critical,
effect: None,
},
Vec3::new(1.0, 2.0, 3.0),
None,
);
p.velocity = Vec3::new(4.0, 2.0, -1.0);
p
}
#[test]
fn critical_arrow_emits_four_native_streak_samples() {
let trail = arrow(true).arrow_trail(false);
assert_eq!(trail.len(), 4);
for (i, (ty, pos, speed)) in trail.iter().enumerate() {
assert_eq!(*ty, ParticleType::Crit);
assert_eq!(
*pos,
[1.0 + i as f64, 2.0 + i as f64 * 0.5, 3.0 - i as f64 * 0.25]
);
assert_eq!(*speed, [-4.0, -1.8, 1.0]);
}
}
#[test]
fn submerged_arrow_emits_four_bubbles_after_water_inertia() {
let trail = arrow(false).arrow_trail(true);
assert_eq!(trail.len(), 4);
let drag = f64::from(0.6f32);
for (ty, pos, speed) in trail {
assert_eq!(ty, ParticleType::Bubble);
assert_eq!(speed, [4.0 * drag, 2.0 * drag, -drag]);
assert_eq!(pos, [1.0 - drag, 2.0 - drag * 0.5, 3.0 + drag * 0.25]);
}
}
#[test]
fn ordinary_and_stuck_arrows_do_not_emit_critical_trails() {
assert!(arrow(false).arrow_trail(false).is_empty());
let mut p = arrow(true);
p.stuck = true;
assert!(p.arrow_trail(true).is_empty());
}
}
+146
View File
@@ -19,6 +19,18 @@ impl SpriteAnimation {
pub fn frame(&self, tick: u64) -> usize {
self.clip.sample(tick).frame as usize
}
pub fn resized_pixels(&self, frame: usize, width: u32, height: u32) -> Vec<u8> {
let source = self.pixels(frame);
let side = (source.len() / 4).isqrt() as u32;
let mut out = Vec::with_capacity((width * height * 4) as usize);
for y in 0..height {
for x in 0..width {
let offset = ((y * side / height * side + x * side / width) * 4) as usize;
out.extend_from_slice(&source[offset..offset + 4]);
}
}
out
}
pub fn pixels(&self, frame: usize) -> &[u8] {
&self.frames[frame]
}
@@ -29,6 +41,8 @@ pub struct Sprites {
/// Edge length of every array layer and the layers' current frames, set
/// by [`Sprites::finish`].
pub size: u32,
/// Smallest native layer before array-size resampling.
pub minimum_size: u32,
pub pixels: Vec<u8>,
pub layers: BTreeMap<String, u32>,
pub animations: Vec<SpriteAnimation>,
@@ -68,6 +82,7 @@ impl Sprites {
pub fn finish(&mut self) {
let layers = self.native.len().max(1) as u64;
let largest = self.native.iter().map(|n| n.0).max().unwrap_or(SPRITE_SIZE);
self.minimum_size = self.native.iter().map(|n| n.0).min().unwrap_or(SPRITE_SIZE);
let mut size = largest.max(SPRITE_SIZE).next_power_of_two();
while size > SPRITE_SIZE && layers * u64::from(size * size) * 4 > MAX_ARRAY_BYTES {
size /= 2;
@@ -237,9 +252,140 @@ impl Sprites {
}
}
#[cfg(test)]
pub(crate) fn test_animation(size: u32, layer: u32) -> SpriteAnimation {
let frame = |blue: u8| {
(0..size * size)
.flat_map(|i| [(i % size) as u8, (i / size) as u8, blue, 255])
.collect()
};
let metadata = AnimationMetadata::from_json(r#"{"frametime":1,"frames":[0,1]}"#).unwrap();
SpriteAnimation {
layer,
frames: Arc::new(vec![frame(0), frame(99)]),
clip: Arc::new(metadata.clip(2).unwrap().unwrap()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_32px_only_atlas_does_not_add_an_extra_mipmap() {
let mut sprites = Sprites {
native: vec![
(32, Arc::new(vec![vec![255; 32 * 32 * 4]]), 0),
(32, Arc::new(vec![vec![128; 32 * 32 * 4]]), 0),
],
..Default::default()
};
sprites.finish();
assert_eq!((sprites.size, sprites.minimum_size), (32, 32));
for level in 0..=4 {
assert_eq!(
crate::gfx::sprite_mipmap_limit(level, sprites.size, sprites.minimum_size, 6),
level
);
}
sprites
.native
.push((16, Arc::new(vec![vec![255; 16 * 16 * 4]]), 0));
sprites.finish();
assert_eq!((sprites.size, sprites.minimum_size), (32, 16));
assert_eq!(
crate::gfx::sprite_mipmap_limit(0, sprites.size, sprites.minimum_size, 6),
1
);
}
#[test]
fn hud_animation_resampling_uses_the_actual_frame_size() {
for size in [16, 32, 64] {
let animation = test_animation(size, 0);
let resized = animation.resized_pixels(1, 16, 16);
let last = (15 * size / 16) as u8;
assert_eq!(&resized[15 * 4..16 * 4], &[last, 0, 99, 255]);
assert_eq!(&resized[255 * 4..256 * 4], &[last, last, 99, 255]);
}
}
#[test]
fn native_fire_sprites_register_full_animation_sequences() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root
.join("assets/minecraft/textures/block/fire_0.png")
.exists()
{
return;
}
let mut sprites = Sprites::default();
for name in ["fire_0", "fire_1", "soul_fire_0", "soul_fire_1"] {
let layer = sprites
.insert(&root, &format!("minecraft:block/{name}"))
.unwrap();
let animation = sprites
.animations
.iter()
.find(|a| a.layer == layer)
.expect("fire must be animated");
assert_ne!(
animation.pixels(animation.frame(0)),
animation.pixels(animation.frame(1))
);
assert_ne!(
animation.resized_pixels(animation.frame(0), 16, 16),
animation.resized_pixels(animation.frame(1), 16, 16)
);
assert_eq!(
animation.pixels(animation.frame(0)).len(),
(SPRITE_SIZE * SPRITE_SIZE * 4) as usize
);
}
}
#[test]
fn native_32_pixel_animation_frames_keep_every_texel() {
let root = std::env::temp_dir().join(format!(
"horizon-sprite-detail-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let directory = root.join("assets/test/textures");
fs::create_dir_all(&directory).unwrap();
let path = directory.join("flow.png");
let mut pixels = Vec::new();
for y in 0..64u8 {
for x in 0..32u8 {
pixels.extend([x, y, 0, 255]);
}
}
let mut encoder = png::Encoder::new(File::create(&path).unwrap(), 32, 64);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.unwrap()
.write_image_data(&pixels)
.unwrap();
fs::write(path.with_extension("png.mcmeta"), r#"{"animation":{}}"#).unwrap();
let mut sprites = Sprites::default();
sprites.insert(&root, "test:flow").unwrap();
sprites.finish();
let size = sprites.size;
let initial = sprites.pixels.clone();
let animation = sprites.animations[0].clone();
fs::remove_dir_all(root).unwrap();
assert_eq!(
size, 32,
"half a flowing-water frame must retain 16 texels, not 8"
);
assert_eq!(initial, pixels[..32 * 32 * 4]);
assert_eq!(animation.pixels(animation.frame(1)), &pixels[32 * 32 * 4..]);
}
#[test]
fn animation_boundaries_and_repeated_frames_do_not_depend_on_render_rate() {
let animation = SpriteAnimation {
+138 -14
View File
@@ -12,6 +12,81 @@ use std::{
sync::{Arc, OnceLock},
};
/// The `custom_data` key holding an exploration map's search until the game
/// runs it (vanilla runs `ExplorationMapFunction` when the chest is unpacked,
/// on first open; here loot is rolled with the chunk).
const PENDING_MAP: &str = "horizon:exploration_map";
const CUSTOM_DATA: &str = "minecraft:custom_data";
/// A generated chest's item, with its exploration map search kept in
/// `minecraft:custom_data` (which vanilla loads as is).
fn loot_item(s: &horizon_world::loot::LootStack) -> ItemStack {
let mut item = ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
};
if let Some(map) = &s.exploration {
let search = Tag::compound([
("destination", Tag::String(map.destination.as_str().into())),
("decoration", Tag::String(map.decoration.as_str().into())),
("zoom", Tag::Byte(map.zoom as i8)),
("search_radius", Tag::Int(map.search_radius)),
(
"skip_existing_chunks",
Tag::Byte(i8::from(map.skip_existing_chunks)),
),
]);
item.data_mut()
.other
.push((CUSTOM_DATA.into(), Tag::compound([(PENDING_MAP, search)])));
}
item
}
/// The exploration map search an item still waits for, removed from it.
pub fn take_pending_map(item: &mut ItemStack) -> Option<horizon_world::loot::ExplorationMap> {
let data = item.extra.as_deref_mut()?;
let i = data
.other
.iter()
.position(|(k, t)| k == CUSTOM_DATA && t.get(PENDING_MAP).is_some())?;
let (_, mut custom) = data.other.remove(i);
let search = match &mut custom {
Tag::Compound(c) => c.remove(&JavaString::from(PENDING_MAP))?,
_ => return None,
};
if matches!(&custom, Tag::Compound(c) if !c.is_empty()) {
data.other.insert(i, (CUSTOM_DATA.into(), custom));
}
let text = |k: &str| match search.get(k) {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
};
let int = |k: &str| match search.get(k) {
Some(Tag::Int(v)) => Some(*v),
Some(Tag::Byte(v)) => Some(i32::from(*v)),
_ => None,
};
Some(horizon_world::loot::ExplorationMap {
destination: text("destination")?,
decoration: text("decoration")?,
zoom: int("zoom").unwrap_or(2).clamp(0, 4) as u8,
search_radius: int("search_radius").unwrap_or(50),
skip_existing_chunks: int("skip_existing_chunks").unwrap_or(1) != 0,
})
}
/// Whether an item still waits for its exploration map search.
pub fn has_pending_map(item: &ItemStack) -> bool {
item.data().is_some_and(|d| {
d.other
.iter()
.any(|(k, t)| k == CUSTOM_DATA && t.get(PENDING_MAP).is_some())
})
}
/// Loot data of the resource root, loaded once per process.
pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
static LOOT: OnceLock<Option<Arc<LootData>>> = OnceLock::new();
@@ -64,12 +139,7 @@ pub fn block_entities(
.zip(loot.fill(&table, seed, 27, Some(biome)))
{
*slot = stack.map(|s| {
let mut item = ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
};
let mut item = loot_item(&s);
// An ominous bottle's level (the default, 0, is no component).
if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) {
item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8);
@@ -114,17 +184,71 @@ pub fn unpack_entity_loot(
let slots: Vec<Option<ItemStack>> = loot
.fill(&table, seed, 27, Some(biome))
.into_iter()
.map(|s| {
s.map(|s| ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
})
})
.map(|s| s.map(|s| loot_item(&s)))
.collect();
nbt.remove(&JavaString::from("LootTable"));
nbt.remove(&JavaString::from("LootTableSeed"));
nbt.insert("Items".into(), crate::save::encode_items(&slots));
nbt
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_world::loot::{ExplorationMap, LootStack};
#[test]
fn exploration_maps_wait_in_custom_data_until_searched() {
let mut stack = LootStack {
item: "minecraft:buried_treasure_map".into(),
count: 1,
damage: 0,
enchantments: Vec::new(),
potion: None,
map: true,
exploration: Some(Box::new(ExplorationMap::from_json(&serde_json::json!({
"decoration": "minecraft:red_x",
"destination": "#minecraft:on_treasure_maps",
"skip_existing_chunks": false,
"zoom": 1
})))),
ominous_amplifier: None,
};
let mut item = loot_item(&stack);
assert!(has_pending_map(&item));
// The rest of custom_data stays.
if let Some(Tag::Compound(c)) = item
.data_mut()
.other
.iter_mut()
.find(|(k, _)| k == CUSTOM_DATA)
.map(|(_, t)| t)
{
c.insert("note".into(), Tag::Int(7));
}
let map = take_pending_map(&mut item).unwrap();
assert_eq!(
map,
ExplorationMap {
destination: "minecraft:on_treasure_maps".into(),
decoration: "minecraft:red_x".into(),
zoom: 1,
search_radius: 50,
skip_existing_chunks: false,
}
);
assert!(!has_pending_map(&item));
assert!(take_pending_map(&mut item).is_none());
let custom = &item.data().unwrap().other;
assert_eq!(custom.len(), 1);
assert_eq!(custom[0].1.get("note"), Some(&Tag::Int(7)));
// Only the search: the component goes away with it.
stack.item = "minecraft:abandoned_camp_map".into();
let mut item = loot_item(&stack);
take_pending_map(&mut item).unwrap();
assert!(item.data().unwrap().other.is_empty());
// A plain item has nothing pending.
stack.exploration = None;
assert!(!has_pending_map(&loot_item(&stack)));
}
}
+34 -21
View File
@@ -245,6 +245,26 @@ impl Title {
self.mode = Mode::Select { worlds, selected };
*self.recent.borrow_mut() = None;
}
/// Deletes the world `Mode::Delete` asks about and goes back to the
/// refreshed list; a failure (the world is open elsewhere, say) shows the
/// error instead and leaves the world. Returns the deleted world's row in
/// the list before it went, for a layout that moves the selection there.
pub(crate) fn confirm_delete(&mut self) -> Option<usize> {
let Mode::Delete { world } = &self.mode else {
return None;
};
let folder = world.folder.clone();
let row = list_worlds(&self.saves)
.iter()
.position(|w| w.folder == folder);
if let Err(error) = world_management::delete(&self.saves, &folder) {
self.failed(error);
return None;
}
self.return_to_list(None);
self.icons.borrow_mut().clear();
row
}
fn cancel_create(&mut self) {
if self.create_return_to_main {
self.mode = Mode::Main;
@@ -652,24 +672,21 @@ impl Title {
let (w, h) = (batch.width.ceil(), batch.height.ceil());
match &self.mode {
Mode::Main => {
// Logo: minecraft.png is a 1024x256 sheet drawn at 256x64.
batch.sprite_scaled(
// LogoRenderer: the logo's top 44 of 64 rows, then the edition
// banner's top 14 of 16 rows overlapping its bottom by 7.
batch.sprite_region(
atlas,
"gui/title/minecraft",
(w / 2.0).floor() - 128.0,
30.0,
[(w / 2.0).floor() - 128.0, 30.0, 256.0, 44.0],
256.0,
64.0,
u32::MAX,
);
batch.sprite_scaled(
batch.sprite_region(
atlas,
"gui/title/edition",
(w / 2.0).floor() - 64.0,
30.0 + 64.0 - 7.0,
crate::title_edition::SPRITE,
[(w / 2.0).floor() - 64.0, 30.0 + 44.0 - 7.0, 128.0, 14.0],
128.0,
14.0,
u32::MAX,
16.0,
);
let version = "Horizon 26.3 (Rust)";
batch.text(atlas, version, 2.0, h - 10.0, u32::MAX, true);
@@ -1176,16 +1193,12 @@ impl Title {
&& (x - (w / 2.0).floor()).abs() < 100.0;
Action::None
}
(Mode::Delete { world }, Some(id @ (37 | 38))) => {
let folder = world.folder.clone();
if id == 37
&& let Err(error) = world_management::delete(&self.saves, &folder)
{
self.failed(error);
return Action::None;
}
self.return_to_list(Some(&folder));
self.icons.borrow_mut().clear();
(Mode::Delete { .. }, Some(37)) => {
self.confirm_delete();
Action::None
}
(Mode::Delete { .. }, Some(38)) => {
self.escape();
Action::None
}
(Mode::Error { return_to, .. }, Some(39)) => {
+28
View File
@@ -533,3 +533,31 @@ fn failed_world_operation_back_button_plays_the_click_sound() {
assert_eq!(f.click_with_sound("Back"), (Action::None, true));
assert!(matches!(f.title.mode, Mode::Edit { .. }));
}
#[test]
fn delete_refuses_an_open_world_then_removes_it_with_its_lock() {
let f = Fixture::new();
f.world("World", "World");
let open = crate::save::SessionLock::acquire(&f.title.saves.join("World")).unwrap();
assert!(world_management::delete(&f.title.saves, "World").is_err());
assert!(f.title.saves.join("World/level.dat").is_file());
drop(open);
world_management::delete(&f.title.saves, "World").unwrap();
assert!(!f.title.saves.join("World").exists());
}
#[cfg(unix)]
#[test]
fn delete_removes_links_without_following_them() {
let f = Fixture::new();
f.world("World", "World");
let outside = f.root.join("outside");
fs::create_dir_all(&outside).unwrap();
fs::write(outside.join("keep.txt"), "keep").unwrap();
std::os::unix::fs::symlink(&outside, f.title.saves.join("World/link")).unwrap();
std::os::unix::fs::symlink(&outside, f.title.saves.join("Linked")).unwrap();
assert!(world_management::delete(&f.title.saves, "Linked").is_err());
world_management::delete(&f.title.saves, "World").unwrap();
assert!(!f.title.saves.join("World").exists());
assert!(outside.join("keep.txt").is_file());
}
@@ -38,8 +38,51 @@ pub(super) fn reset_icon(saves: &Path, folder: &str) -> crate::Result<()> {
Ok(())
}
/// `LevelStorageAccess.deleteLevel`, shared by both menu styles. The world's
/// session lock is taken first, so a world open in this or another instance is
/// refused rather than pulled from under it; everything but the lock goes,
/// then the lock is released and removed with the folder. A failed pass (a
/// file briefly held by a virus scanner, say) is retried up to five times,
/// half a second apart, as vanilla does. Only the named folder directly in
/// `saves` is touched: symbolic links inside it are removed, never followed.
pub(super) fn delete(saves: &Path, folder: &str) -> crate::Result<()> {
fs::remove_dir_all(world_path(saves, folder)?)?;
let world = world_path(saves, folder)?;
let lock = crate::save::SessionLock::acquire(&world)?;
let lock_path = world.join("session.lock");
log::info!("Deleting level {folder}");
for attempt in 1.. {
match remove_contents(&world, &lock_path) {
Ok(()) => break,
Err(e) if attempt >= 5 => return Err(e.into()),
Err(e) => {
log::warn!("Failed to delete {}: {e}", world.display());
std::thread::sleep(std::time::Duration::from_millis(500));
}
}
}
drop(lock);
match fs::remove_file(&lock_path) {
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e.into()),
_ => {}
}
fs::remove_dir(&world)?;
Ok(())
}
fn remove_contents(world: &Path, lock: &Path) -> io::Result<()> {
for entry in fs::read_dir(world)? {
let entry = entry?;
let path = entry.path();
if path == lock {
continue;
}
// `file_type` does not follow links, and `remove_dir_all` never does.
if entry.file_type()?.is_dir() {
fs::remove_dir_all(&path)?;
} else {
fs::remove_file(&path)?;
}
}
Ok(())
}
+489
View File
@@ -0,0 +1,489 @@
//! "RUST EDITION" under the classic title screen's logo.
//!
//! Vanilla's `textures/gui/title/edition.png` reads "JAVA EDITION". Horizon
//! never ships Mojang's art, so the banner is rebuilt at load time from the
//! player's own texture: "EDITION" is kept column for column, the "T" is lifted
//! out of it, and R, U and S are Horizon's own glyphs (MIT, the rectangles
//! below), drawn the way the texture's letters are built (a face with darker
//! sides and a light bottom edge, a dark extrusion under it, a black outline
//! and a soft rim) in the shades sampled from the texture itself. Only
//! vanilla 26.3's exact texture is rebuilt: a resource pack's edition.png
//! stays as its author drew it.
use std::collections::{HashMap, VecDeque};
use std::ops::Range;
/// The atlas sprite.
pub const SPRITE: &str = "gui/title/edition";
const WIDTH: usize = 512;
const HEIGHT: usize = 64;
/// FNV-1a over the size and RGBA pixels of 26.3's edition.png.
const VANILLA: u64 = 0x4249_0538_6dfb_181f;
/// "EDITION", outline included, starts at this column; left of it is "JAVA".
const EDITION_START: usize = 204;
/// The columns of the "T"'s body (face and extrusion) inside "EDITION".
const T_BODY: (usize, usize) = (335, 376);
/// Where the texture's letters put their faces, and how deep they are drawn.
const FACE_TOP: usize = 4;
const EXTRUSION: usize = 8;
const OUTLINE: usize = 3;
/// The face-to-face spacing between letters.
const LETTER_GAP: usize = 6;
/// The new glyphs' face width: "RUST" then spans "JAVA"'s columns to within
/// a texel, so "EDITION" stays where it is and the banner stays centred.
const GLYPH_WIDTH: usize = 42;
/// The first face column, as "JAVA"'s.
const FIRST_FACE: usize = 4;
/// Horizon's R, U and S: face rectangles `[x0, y0, x1, y1)` in texels from the
/// face's top-left, 42 wide and 39 tall, with 11-texel stems, 10-texel bars and
/// 7-texel notches for the rounded corners.
const R: &[[usize; 4]] = &[
[0, 0, 11, 39],
[0, 0, 35, 10],
[31, 7, 42, 19],
[0, 15, 35, 25],
[31, 25, 42, 39],
];
const U: &[[usize; 4]] = &[[0, 0, 11, 32], [31, 0, 42, 32], [7, 29, 35, 39]];
const S: &[[usize; 4]] = &[
[7, 0, 42, 10],
[0, 7, 11, 19],
[7, 15, 35, 25],
[31, 21, 42, 32],
[0, 29, 35, 39],
];
/// The banner rebuilt to read "RUST EDITION", or `None` when the texture is
/// not vanilla's (a resource pack's own).
pub fn rust_edition(width: u32, height: u32, pixels: &[u8]) -> Option<Vec<u8>> {
(fingerprint(width, height, pixels) == VANILLA).then(|| compose(pixels))
}
fn fingerprint(width: u32, height: u32, pixels: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325u64;
let bytes = width.to_le_bytes().into_iter().chain(height.to_le_bytes());
for b in bytes.chain(pixels.iter().copied()) {
hash = (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
}
hash
}
type Rgba = [u8; 4];
fn lum(p: Rgba) -> u32 {
(u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2])) / 3
}
fn pixel(pixels: &[u8], x: usize, y: usize) -> Rgba {
let i = (y * WIDTH + x) * 4;
[pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
}
/// The texture's shades: the most common colour in each brightness band.
struct Palette {
highlight: Rgba,
face: Rgba,
rim: Rgba,
extrusion: Rgba,
edge: Rgba,
outline: Rgba,
soft: Rgba,
}
impl Palette {
fn sample(pixels: &[u8]) -> Self {
let mut bands: [HashMap<Rgba, u32>; 7] = Default::default();
for &p in pixels.as_chunks::<4>().0 {
let band = match (p[3], lum(p)) {
(0, _) => continue,
(255, 215..) => 0,
(255, 170..) => 1,
(255, 100..) => 2,
(255, 45..) => 3,
(255, 20..) => 4,
(255, _) => 5,
_ => 6,
};
*bands[band].entry(p).or_default() += 1;
}
let mode = |band: &HashMap<Rgba, u32>, fallback: Rgba| {
band.iter()
.max_by_key(|&(p, n)| (*n, std::cmp::Reverse(*p)))
.map_or(fallback, |(p, _)| *p)
};
let outline = mode(&bands[5], [0, 0, 0, 255]);
let face = mode(&bands[1], [200, 200, 200, 255]);
Self {
highlight: mode(&bands[0], face),
face,
rim: mode(&bands[2], face),
extrusion: mode(&bands[3], outline),
edge: mode(&bands[4], outline),
outline,
soft: mode(&bands[6], outline),
}
}
}
/// Faces of the new glyphs, positioned in the texture.
fn glyph_faces() -> Vec<bool> {
let mut face = vec![false; WIDTH * HEIGHT];
for (i, glyph) in [R, U, S].into_iter().enumerate() {
let left = FIRST_FACE + i * (GLYPH_WIDTH + LETTER_GAP);
for &[x0, y0, x1, y1] in glyph {
for y in FACE_TOP + y0..FACE_TOP + y1 {
for x in left + x0..left + x1 {
face[y * WIDTH + x] = true;
}
}
}
}
face
}
/// Where the "T" lifted from "EDITION" goes: one letter gap after the S.
fn t_left() -> usize {
FIRST_FACE + 3 * (GLYPH_WIDTH + LETTER_GAP)
}
/// Draw faces within `columns` the way the texture's letters are drawn.
fn draw_glyphs(out: &mut [u8], face: &[bool], palette: &Palette, columns: Range<usize>) {
let at = |grid: &[bool], x: isize, y: isize| {
(columns.start as isize..columns.end as isize).contains(&x)
&& (0..HEIGHT as isize).contains(&y)
&& grid[y as usize * WIDTH + x as usize]
};
let mut body = face.to_vec();
for y in 0..HEIGHT {
for x in columns.clone() {
let (xi, yi) = (x as isize, y as isize);
body[y * WIDTH + x] |= (1..=EXTRUSION as isize).any(|k| at(face, xi, yi - k));
}
}
let reach = OUTLINE as isize + 1;
for y in 0..HEIGHT {
for x in columns.clone() {
let (xi, yi) = (x as isize, y as isize);
let colour = if at(face, xi, yi) {
if !at(face, xi, yi + 1) {
palette.highlight
} else if !at(face, xi - 1, yi) || !at(face, xi + 1, yi) {
palette.rim
} else {
palette.face
}
} else if at(&body, xi, yi) {
if at(face, xi, yi - 1) {
palette.rim
} else if !at(&body, xi - 1, yi) || !at(&body, xi + 1, yi) || !at(&body, xi, yi + 1)
{
palette.edge
} else {
palette.extrusion
}
} else {
let distance = (-reach..=reach)
.flat_map(|dy| (-reach..=reach).map(move |dx| (dx, dy)))
.filter(|&(dx, dy)| at(&body, xi + dx, yi + dy))
.map(|(dx, dy)| dx.abs().max(dy.abs()))
.min();
match distance {
Some(d) if d <= OUTLINE as isize => palette.outline,
Some(_) => palette.soft,
None => continue,
}
};
put(out, x, y, colour);
}
}
}
/// Paint `p` over what is there unless that is more opaque, or as opaque and
/// brighter (a letter's body wins over a neighbour's outline).
fn put(out: &mut [u8], x: usize, y: usize, p: Rgba) {
let old = pixel(out, x, y);
if (p[3], lum(p)) > (old[3], lum(old)) {
out[(y * WIDTH + x) * 4..][..4].copy_from_slice(&p);
}
}
/// Every pixel of "EDITION"'s "T": its body, and the outline pixels nearer to
/// it than to its neighbours.
fn t_pixels(pixels: &[u8]) -> Vec<(usize, usize)> {
const NONE: u8 = 0;
const T: u8 = 1;
const OTHER: u8 = 2;
let mut owner = vec![NONE; WIDTH * HEIGHT];
let mut queue = VecDeque::new();
for y in 0..HEIGHT {
for x in EDITION_START..WIDTH {
let p = pixel(pixels, x, y);
if p[3] == 255 && lum(p) >= 30 {
owner[y * WIDTH + x] = if (T_BODY.0..=T_BODY.1).contains(&x) {
T
} else {
OTHER
};
queue.push_back((x, y));
}
}
}
while let Some((x, y)) = queue.pop_front() {
let label = owner[y * WIDTH + x];
for (dx, dy) in [
(-1, -1),
(0, -1),
(1, -1),
(-1, 0),
(1, 0),
(-1, 1),
(0, 1),
(1, 1),
] {
let (nx, ny) = (x as isize + dx, y as isize + dy);
if !(EDITION_START as isize..WIDTH as isize).contains(&nx)
|| !(0..HEIGHT as isize).contains(&ny)
{
continue;
}
let (nx, ny) = (nx as usize, ny as usize);
if owner[ny * WIDTH + nx] == NONE && pixel(pixels, nx, ny)[3] > 0 {
owner[ny * WIDTH + nx] = label;
queue.push_back((nx, ny));
}
}
}
(0..HEIGHT)
.flat_map(|y| (EDITION_START..WIDTH).map(move |x| (x, y)))
.filter(|&(x, y)| owner[y * WIDTH + x] == T)
.collect()
}
/// Close the pockets left of "EDITION" that no gap reaches from outside, as
/// the texture's letters fill their counters with the outline.
fn fill_counters(out: &mut [u8], outline: Rgba) {
let open = |out: &[u8], x: usize, y: usize| pixel(out, x, y)[3] < 255;
let mut seen = vec![false; WIDTH * HEIGHT];
let mut queue = VecDeque::new();
for y in 0..HEIGHT {
for x in 0..EDITION_START {
let border = x == 0 || y == 0 || x == EDITION_START - 1 || y == HEIGHT - 1;
if border && open(out, x, y) {
seen[y * WIDTH + x] = true;
queue.push_back((x, y));
}
}
}
while let Some((x, y)) = queue.pop_front() {
for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
let (nx, ny) = (x as isize + dx, y as isize + dy);
if !(0..EDITION_START as isize).contains(&nx) || !(0..HEIGHT as isize).contains(&ny) {
continue;
}
let (nx, ny) = (nx as usize, ny as usize);
if !seen[ny * WIDTH + nx] && open(out, nx, ny) {
seen[ny * WIDTH + nx] = true;
queue.push_back((nx, ny));
}
}
}
for y in 0..HEIGHT {
for x in 0..EDITION_START {
if !seen[y * WIDTH + x] && open(out, x, y) {
out[(y * WIDTH + x) * 4..][..4].copy_from_slice(&outline);
}
}
}
}
/// Give every edge left of "EDITION" the soft rim the texture's outlines have
/// (the "T"'s right side shared its outline with the next letter).
fn soften_edges(out: &mut [u8], soft: Rgba) {
let opaque = |out: &[u8], x: isize, y: isize| {
(0..EDITION_START as isize).contains(&x)
&& (0..HEIGHT as isize).contains(&y)
&& pixel(out, x as usize, y as usize)[3] == 255
};
let mut rim = Vec::new();
for y in 0..HEIGHT {
for x in 0..EDITION_START {
let (xi, yi) = (x as isize, y as isize);
let near = (-1..=1).any(|dy| (-1..=1).any(|dx| opaque(out, xi + dx, yi + dy)));
if pixel(out, x, y)[3] == 0 && near {
rim.push((x, y));
}
}
}
for (x, y) in rim {
out[(y * WIDTH + x) * 4..][..4].copy_from_slice(&soft);
}
}
/// "RUST" in place of "JAVA"; `pixels` is a 512x64 RGBA banner laid out as
/// vanilla's.
fn compose(pixels: &[u8]) -> Vec<u8> {
let palette = Palette::sample(pixels);
let mut out = pixels.to_vec();
for row in out.as_chunks_mut::<{ WIDTH * 4 }>().0 {
row[..EDITION_START * 4].fill(0);
}
draw_glyphs(&mut out, &glyph_faces(), &palette, 0..EDITION_START);
let left = t_left();
for (x, y) in t_pixels(pixels) {
put(&mut out, x + left - T_BODY.0, y, pixel(pixels, x, y));
}
fill_counters(&mut out, palette.outline);
soften_edges(&mut out, palette.soft);
out
}
#[cfg(test)]
mod tests {
use super::*;
const FACE: Rgba = [208, 197, 192, 255];
/// A banner laid out as vanilla's, in made-up colours: every letter a
/// solid block over its vanilla columns, with the font's shading.
fn stand_in() -> Vec<u8> {
// Vanilla's letter bodies (extrusion edge included) by column.
let runs = [
(4, 97),
(101, 144),
(147, 190),
(208, 249),
(256, 296),
(303, 330),
(335, 376),
(381, 411),
(413, 507),
];
let mut face = vec![false; WIDTH * HEIGHT];
for (x0, x1) in runs {
for y in FACE_TOP..FACE_TOP + 39 {
for x in x0..=x1 {
face[y * WIDTH + x] = true;
}
}
}
let palette = Palette {
highlight: [226, 216, 213, 255],
face: FACE,
rim: [153, 147, 145, 255],
extrusion: [61, 57, 56, 255],
edge: [45, 42, 42, 255],
outline: [0, 0, 0, 255],
soft: [0, 0, 0, 244],
};
let mut out = vec![0; WIDTH * HEIGHT * 4];
draw_glyphs(&mut out, &face, &palette, 0..WIDTH);
// A colour only "JAVA" has, to see it go.
out[(20 * WIDTH + 30) * 4..][..4].copy_from_slice(&[255, 0, 255, 255]);
out
}
fn columns(pixels: &[u8], range: Range<usize>) -> Vec<u8> {
pixels
.as_chunks::<{ WIDTH * 4 }>()
.0
.iter()
.flat_map(|row| row[range.start * 4..range.end * 4].to_vec())
.collect()
}
/// Outlines left of "EDITION" keep their soft rim all round.
fn assert_soft_rim(out: &[u8]) {
for y in 1..HEIGHT - 1 {
for x in 1..EDITION_START - 1 {
if pixel(out, x, y)[3] == 255 {
let near = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)];
assert!(
near.iter().all(|&(nx, ny)| pixel(out, nx, ny)[3] > 0),
"{x},{y}"
);
}
}
}
}
#[test]
fn rust_replaces_java_and_edition_is_untouched() {
let source = stand_in();
let out = compose(&source);
assert_eq!(out.len(), WIDTH * HEIGHT * 4);
assert_eq!(
columns(&out, EDITION_START..WIDTH),
columns(&source, EDITION_START..WIDTH)
);
assert!(!out.as_chunks::<4>().0.contains(&[255, 0, 255, 255]));
// R, U and S: their strokes are faces, their notches and counters not.
let lit = |x: usize, y: usize| lum(pixel(&out, x, y)) >= 100;
let glyph = |i: usize, x: usize, y: usize| {
lit(
FIRST_FACE + i * (GLYPH_WIDTH + LETTER_GAP) + x,
FACE_TOP + y,
)
};
for (i, shape) in [R, U, S].into_iter().enumerate() {
for &[x0, y0, x1, y1] in shape {
assert!(glyph(i, (x0 + x1) / 2, (y0 + y1) / 2), "glyph {i}");
}
}
assert!(!glyph(0, 38, 21), "R's notch between bowl and leg");
assert!(!glyph(0, 20, 30), "R's open bottom");
assert!(!glyph(1, 20, 5), "U's open top");
assert!(!glyph(1, 2, 36), "U's rounded corner");
assert!(!glyph(2, 2, 22), "S's lower-left notch");
assert!(!glyph(2, 38, 17), "S's upper-right notch");
// The T is EDITION's, moved.
let shift = T_BODY.0 - t_left();
for y in 0..HEIGHT {
for x in T_BODY.0..=T_BODY.1 {
let p = pixel(&source, x, y);
if p[3] == 255 && lum(p) >= 30 {
assert_eq!(pixel(&out, x - shift, y), p, "T at {x},{y}");
}
}
}
assert_soft_rim(&out);
// Nothing below the 14 GUI rows vanilla draws, and the word gap stays open.
assert!(out[WIDTH * 55 * 4..].iter().all(|&b| b == 0));
let gap = columns(&out, 195..EDITION_START);
assert!(gap.as_chunks::<4>().0.iter().all(|p| p[3] == 0));
// Centred: "RUST" spans "JAVA"'s columns to within a texel.
let used = |x: usize| (0..HEIGHT).any(|y| pixel(&out, x, y)[3] > 0);
let last = (0..EDITION_START).rev().find(|&x| used(x)).unwrap();
assert!(
used(0) && (193..=195).contains(&last),
"RUST ends at {last}"
);
}
#[test]
fn only_vanilla_is_rebuilt() {
let source = stand_in();
assert!(rust_edition(512, 64, &source).is_none());
}
/// Against the prepared vanilla resources when they are present.
#[test]
fn prepared_vanilla_edition() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(
"../../.local/horizon-client/26.3/assets/minecraft/textures/gui/title/edition.png",
);
let Ok((w, h, pixels)) = crate::hud::decode(&path) else {
return;
};
let out = rust_edition(w, h, &pixels).expect("vanilla 26.3's edition.png");
assert_eq!(
columns(&out, EDITION_START..WIDTH),
columns(&pixels, EDITION_START..WIDTH)
);
assert_eq!(Palette::sample(&pixels).face, FACE);
assert_soft_rim(&out);
let mut edited = pixels.clone();
edited[3] ^= 1;
assert!(rust_edition(w, h, &edited).is_none());
}
}
+7
View File
@@ -117,6 +117,13 @@ impl VanillaTerrain {
let worker = worker.get_or_insert_with(|| self.generator.worker());
worker.find_closest_biome(search)
}
/// `BiomeSource.getNoiseBiome` at quart positions, for places that may not
/// be generated yet (`MapItem.renderBiomePreviewMap`).
pub fn noise_biomes(&self, quarts: &[[i32; 3]]) -> Vec<Option<String>> {
let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner());
let worker = worker.get_or_insert_with(|| self.generator.worker());
worker.noise_biomes(quarts)
}
/// `/place jigsaw`: `JigsawPlacement.addPieces`.
pub fn jigsaw_pieces(
&self,
+2
View File
@@ -9,6 +9,7 @@ use std::{
};
pub struct World {
pub fast_lava: bool,
pub chunks: crate::fast_hash::FxHashMap<(i32, i32), Arc<Chunk>>,
pub random: LegacyRandom,
pub revision: u64,
@@ -113,6 +114,7 @@ impl World {
revision: 0,
health_rules: crate::health::HealthRules::default(),
air,
fast_lava: false,
dirty_sections: Default::default(),
dirty_light: Default::default(),
light_edits: Vec::new(),
+6 -1
View File
@@ -424,7 +424,12 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
if !creative && data.is(Class::Tnt) && b.table.bool(state, p.unstable) {
self.prime_tnt(pos);
}
self.level_event(2001, pos, state.0 as i32);
// BaseFireBlock emits extinguish and suppresses generic destroy particles/sound.
if data.is(Class::BaseFire) {
self.level_event(1009, pos, 0);
} else {
self.level_event(2001, pos, state.0 as i32);
}
self.game_event(pos, "minecraft:block_destroy");
self.remove_block(pos, false)
}
+69
View File
@@ -367,6 +367,40 @@ fn water_spreads_on_a_floor() {
assert_eq!(w.prop(BlockPos::new(2, 1, 2), "level"), "4");
}
#[test]
fn bucket_source_removal_drains_spread_water() {
let mut w = world!();
w.floor(0, 10, "stone");
let at = BlockPos::new(0, 1, 0);
assert!(w.b().bucket_empty(
&mut w.level,
&mut w.ticks,
at,
BucketContent::Fluid(crate::fluid::FluidKind::Water),
"minecraft:item.bucket.empty"
));
for _ in 0..60 {
w.tick();
}
assert_ne!(w.get(BlockPos::new(1, 1, 0)), w.b().air());
assert_eq!(
w.b().bucket_pickup(&mut w.level, &mut w.ticks, at),
Some("minecraft:water_bucket")
);
for _ in 0..120 {
w.tick();
}
for x in -8..=8 {
for z in -8..=8 {
assert_eq!(
w.get(BlockPos::new(x, 1, z)),
w.b().air(),
"water remains at {x}, {z}"
);
}
}
}
#[test]
fn water_falls_and_makes_sources() {
let mut w = world!();
@@ -1192,3 +1226,38 @@ fn creaking_heart_follows_its_logs_and_the_night() {
}
assert_eq!(w.prop(heart_at, "creaking_heart_state"), "uprooted");
}
#[test]
fn player_breaks_fire_with_extinguish_not_generic_break_event() {
for name in ["fire", "soul_fire", "white_wool"] {
let mut w = world!();
let pos = BlockPos::new(0, 1, 0);
let support = w.id("soul_soil", &[]);
w.put(BlockPos::new(0, 0, 0), support);
let state = w.id(name, &[]);
w.put(pos, state);
w.level.events.clear();
assert!(
w.f.behaviours
.player_destroy_block(&mut w.level, &mut w.ticks, pos, false)
);
let is_fire = name != "white_wool";
assert_eq!(
w.level
.events
.iter()
.any(|e| matches!(e,LevelEvent::LevelEvent {id:1009,pos:p,..} if *p==pos)),
is_fire,
"extinguish for {name}"
);
assert_eq!(
w.level
.events
.iter()
.any(|e| matches!(e,LevelEvent::LevelEvent {id:2001,pos:p,..} if *p==pos)),
!is_fire,
"generic break for {name}"
);
assert_eq!(w.get(pos), w.b().air());
}
}
+44 -2
View File
@@ -26,9 +26,43 @@ pub struct LootStack {
pub potion: Option<String>,
/// Set by exploration_map (the map_id component of a found map).
pub map: bool,
/// The search an exploration_map function asked for, left to the game
/// (it needs the level's structures and maps).
pub exploration: Option<Box<ExplorationMap>>,
/// Set by set_ominous_bottle_amplifier.
pub ominous_amplifier: Option<i32>,
}
/// `ExplorationMapFunction`'s settings.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExplorationMap {
/// A structure tag, without `#`.
pub destination: String,
pub decoration: String,
pub zoom: u8,
pub search_radius: i32,
pub skip_existing_chunks: bool,
}
impl ExplorationMap {
/// The function's fields with their codec defaults (`DEFAULT_DESTINATION`
/// on_treasure_maps, `DEFAULT_DECORATION` mansion, zoom 2, radius 50,
/// skipping known structures).
pub fn from_json(f: &Value) -> Self {
Self {
destination: f["destination"]
.as_str()
.unwrap_or("#minecraft:on_treasure_maps")
.trim_start_matches('#')
.to_owned(),
decoration: f["decoration"]
.as_str()
.unwrap_or("minecraft:mansion")
.to_owned(),
zoom: f["zoom"].as_u64().unwrap_or(2) as u8,
search_radius: f["search_radius"].as_i64().unwrap_or(50) as i32,
skip_existing_chunks: f["skip_existing_chunks"].as_bool().unwrap_or(true),
}
}
}
impl LootStack {
fn new(item: &str) -> Self {
Self {
@@ -38,6 +72,7 @@ impl LootStack {
enchantments: Vec::new(),
potion: None,
map: false,
exploration: None,
ominous_amplifier: None,
}
}
@@ -1045,8 +1080,15 @@ impl<R: RandomSource> Context<'_, R> {
}
}
// ExplorationMapFunction needs an origin; with one, the map is
// taken as found (the structure search itself is not run).
"minecraft:exploration_map" => stack.map = self.biome.is_some(),
// taken as found here and the game runs the structure search
// (it drops the map when nothing is found, as the filtered
// map_id check after it would).
"minecraft:exploration_map" => {
stack.map = self.biome.is_some();
if stack.map {
stack.exploration = Some(Box::new(ExplorationMap::from_json(f)));
}
}
"minecraft:filtered" => {
let pass = self.item_matches(&f["item_filter"], &stack);
let branch = if pass { &f["on_pass"] } else { &f["on_fail"] };
@@ -1403,6 +1403,8 @@ trait SeededPipeline: Send + Sync {
worker: &mut WorkerState,
search: &BiomeSearch<'_>,
) -> Option<(String, [i32; 3])>;
/// `BiomeSource.getNoiseBiome` at each quart position (unloaded chunks).
fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec<Option<String>>;
fn jigsaw_pieces(
&self,
worker: &mut WorkerState,
@@ -1562,6 +1564,21 @@ where
}
None
}
fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec<Option<String>> {
let mut resolver = self.source.resolver(
&self.climate,
self.router.get(RouterField::Erosion).as_ref(),
);
quarts
.iter()
.map(|&quart| {
resolver
.sample(&mut worker.carver_context, quart)
.ok()
.map(str::to_owned)
})
.collect()
}
fn jigsaw_pieces(
&self,
worker: &mut WorkerState,
@@ -1841,6 +1858,9 @@ impl GeneratorWorker {
}
/// `BiomeSource.findClosestBiome3d`: the first sampled position whose
/// noise biome passes `allowed`, spiralling out from the origin.
pub fn noise_biomes(&mut self, quarts: &[[i32; 3]]) -> Vec<Option<String>> {
self.pipeline.noise_biomes(&mut self.state, quarts)
}
pub fn find_closest_biome(&mut self, search: &BiomeSearch<'_>) -> Option<(String, [i32; 3])> {
self.pipeline.find_closest_biome(&mut self.state, search)
}
+6
View File
@@ -41,6 +41,12 @@ cd website && npm install
node -e 'const {chromium}=require("playwright");(async()=>{const b=await chromium.launch();for(const[f,w,h,o]of[["card",1280,640,"github-social-1280x640"],["banner",960,540,"discord-banner-960x540"]]){const p=await b.newPage({viewport:{width:w,height:h}});await p.goto("file://"+require("path").resolve("../docs/media/brand/social/"+f+".html"));await p.waitForTimeout(300);await p.screenshot({path:"../docs/media/brand/social/"+o+".png"})}await b.close()})()'
```
## Drawn in code
| Where | What |
|-------|------|
| `crates/horizon-client/src/title_edition.rs` | the R, U and S of "RUST EDITION" under the classic title screen's logo: Horizon's own glyphs (MIT), rectangles in that file. The banner is rebuilt at load time from the player's own `textures/gui/title/edition.png` (its "EDITION" and "T" carried over, its shades sampled), so no Mojang pixels are in the repository; a resource pack's banner is left as drawn |
## Uploading (the accounts are Ludovic's)
- **GitHub avatar**: github.com/settings/profile (or the organisation's settings), *Edit* the
+21 -6
View File
@@ -73,7 +73,7 @@ blocks a fork's pull request; the maintainer decides whether to run it.
## Game releases
`.github/workflows/release.yml` releases the game by itself. It starts after every green `checks` run of a push
to main, every hour at :17 (so a release the cooldown held goes out without another merge), and by hand.
to main, every 10 minutes (so a release waiting for merges to settle goes out without another merge), and by hand.
```mermaid
flowchart LR
@@ -83,7 +83,7 @@ flowchart LR
main --> mainchecks{"checks on main"}
mainchecks -- green --> decide{"decide<br/>tools/release_train.py"}
cron(["every hour :17"]) --> decide
decide -- "player-facing PRs, 3 h since the last release,<br/>or release-now" --> build
decide -- "player-facing PRs settled 15 min<br/>(or waiting 1 h), or release-now" --> build
decide -- otherwise --> wait(["wait"])
subgraph build["build, in parallel"]
linux["Linux x86_64<br/>GitHub ubuntu-22.04"]
@@ -104,8 +104,10 @@ commits) since the last **published** game release:
`xtask/`, `packaging/`, `Cargo.toml`, `Cargo.lock`, `research-lock.json`, or an exporter `horizon-prepare`
compiles (the `mods/horizon/src/test/java/dev/horizonlab/parity/*.java` files its sources name). Markdown never
counts.
- It releases when at least one pull request counts and the last game release is at least 3 hours old.
- A pull request labelled `release-now` (a crash or a blocker) releases at once, cooldown or not.
- It releases when at least one pull request counts and the newest of them merged at least 15 minutes ago, so a burst
of merges becomes one release; if merges never pause, it releases once the oldest has waited an hour. There is no
minimum time between releases: every settled player-facing change ships.
- A pull request labelled `release-now` (a crash or a blocker) releases at once.
- A pull request labelled `skip-release` (work players don't see) doesn't count and isn't listed in the notes.
- One release at a time (concurrency group `game-release`); a run that finds nothing new does nothing.
- A scheduled or hand-started run releases main's newest commit whose `checks` passed; after `checks`, the commit
@@ -116,7 +118,7 @@ commits) since the last **published** game release:
| Label | Effect |
| --- | --- |
| `feature` | Listed under **New** (Kira pings the releases role); makes the next launcher release a minor one |
| `release-now` | Releases as soon as main's checks pass, without the cooldown |
| `release-now` | Releases as soon as main's checks pass, without waiting for merges to settle |
| `skip-release` | Doesn't trigger a release and isn't listed in the notes |
| `run-parity` | Runs the parity job once on a fork's pull request |
| `parity-regression` | Opened by the nightly audit for a harness that fails on main |
@@ -193,7 +195,7 @@ and by hand; pushes to `launcher` and `launcher-*` branches only build.
- `tools/release_train.py decide --kind launcher` counts the pull requests merged since the last published
launcher release that changed those paths (not `launcher/links.json`, which the launcher reads from main, nor
tests or Markdown), with the same 3-hour cooldown, `release-now`, `skip-release` and `RELEASES_PAUSED`.
tests or Markdown), with the same settling rule (15 minutes, at most an hour), `release-now`, `skip-release` and `RELEASES_PAUSED`.
- The tag is `launcher-vX.Y.Z`: the patch after the last launcher tag, or the next minor (`X.Y+1.0`) when one of
those pull requests is labelled `feature`.
- No version-bump commits: the build gets the version in `HORIZON_LAUNCHER_VERSION`, which
@@ -227,3 +229,16 @@ time, on the Mac mini's runner, after preparing the resources again if the prepa
The bugs session picks the issues up. The audit's logs are the run's `nightly-parity-logs` artifact; harnesses
listed `linux_only` are skipped there (see above). By hand: `gh workflow run "nightly audit"` (add
`-f dry_run=true` to leave issues alone).
## Disk
Releases ship often, so nothing they leave behind may grow without bound.
- **Artifacts:** every upload keeps 3 days (nightly parity logs 7); a release's assets live on the release itself.
- **Mac runners:** `tools/ci/runner-gc.sh` runs every 6 hours from launchd on the Mac mini, as a copy taken from main
(`~/.actions-runners/runner-gc.sh`, plist `dev.horizon.runner-gc`), never from a pull request's checkout. It skips a
runner in a job, removes a checkout's cargo build folders past 12 GB (`MAX_TARGET_GB`) and harness work folders
under `.local/` untouched for 3 days (`STALE_DAYS`), and keeps the 2 newest shared preparations (`KEEP_PREPARED`)
while no runner works. Runner builds go through the machine's sccache (`tools/ci/runner-env.sh`), so what it removes
comes back from the cache. Update the copy after changing the script:
`ssh macmini 'curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/tools/ci/runner-gc.sh -o ~/.actions-runners/runner-gc.sh'`.
+46
View File
@@ -0,0 +1,46 @@
# Shared startup release response
Startup previously fetched `/releases?per_page=100` on two worker threads: one
for game releases and one for updates. It now decodes that response once and
parses game releases once, publishing them before older-launcher fallback
lookups. Manual and four-hour update checks still request fresh data. Release
page retries remain independent. Existing self-update guards still apply.
Run the committed benchmark against the actual backend implementation:
```sh
CARGO_INCREMENTAL=0 CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0 \
cargo test --manifest-path launcher/Cargo.toml --locked --lib \
backend::release_loading_tests::benchmark_shared_startup_response \
-- --ignored --nocapture
```
Measured on 2026-10-14, Linux x86_64, AMD Ryzen 5 5600X, Rust 1.99.0,
unoptimized Cargo test profile with debug information disabled. A shared
`CARGO_TARGET_DIR` was used for local build reuse. Each case warms up 20 times
and takes the median of 201 samples; outputs are validated for equivalence
and passed to `black_box`.
| Scenario | Before median | After median | Ratio | Fetches per startup |
| --- | ---: | ---: | ---: | ---: |
| Serial parsing/decoding work, zero transport delay | 14.701 ms | 7.339 ms | 2.003x | 2 → 1 |
| Concurrent startup workers, 5 ms per mock request | 14.778 ms | 13.642 ms | 1.083x | 2 → 1 |
The measured 201 samples make 402 mock release-list fetches before and 201
after. The concurrent case reduces elapsed time by 7.7%; the two old requests
can overlap, so halving requests does not halve startup latency.
The synthetic 453,197-byte JSON contains 99 game releases (including a draft)
with roughly 4 KiB of notes each and one launcher release with a platform asset.
The mock fetch decodes identical bytes for each request; it does not exercise
HTTP, TLS, GitHub rate limits, filesystem installation scans, GUI rendering or
self-update downloads. The comparison covers backend orchestration, JSON
decoding, sorting, filtering and update selection, not end-to-end launcher
startup or release-build timing. Fallback timing is omitted from the benchmark
and its ordering/error behavior is tested separately. No persistent cache or
extra copy of the game-release vector is introduced.
Validation: 26 launcher library tests passed (benchmark ignored by default);
the benchmark passed explicitly; full launcher all-target check and Clippy
with `-D warnings` passed; root and launcher format checks and `git diff --check`
passed. The GUI compiled but was not launched interactively.
+45 -8
View File
@@ -193,13 +193,19 @@ pub fn launcher_releases() -> Result<Vec<Release>, String> {
/// a day, so the newest launcher release can be older than all of those: then the newest
/// `launcher-v` tags are looked up one by one (a draft's tag is skipped: it has no public release).
fn launcher_releases_in(list: &serde_json::Value) -> Vec<Release> {
launcher_releases_in_with(list, |url| {
get(&url)?.into_json().map_err(|e| e.to_string())
})
}
fn launcher_releases_in_with(
list: &serde_json::Value,
json: impl Fn(String) -> Result<serde_json::Value, String>,
) -> Vec<Release> {
let found = parse_releases(list, LAUNCHER_ASSET, is_launcher_tag);
if found.iter().any(|r| r.asset.is_some()) {
return found;
}
let json = |url: String| -> Result<serde_json::Value, String> {
get(&url)?.into_json().map_err(|e| e.to_string())
};
let api = format!("https://api.github.com/repos/{REPO}");
let Ok(refs) = json(format!(
"{api}/git/matching-refs/tags/{LAUNCHER_TAG_PREFIX}"
@@ -1172,15 +1178,42 @@ pub fn launcher_update(releases: &[Release]) -> Option<Release> {
.cloned()
}
/// One request to GitHub, both kinds of update.
pub fn check_updates() -> Result<Updates, String> {
let list = release_list()?;
/// Load the game's release list and both update kinds from the same GitHub response.
/// Publish the game releases before any fallback lookups for older launcher tags, so those
/// lookups cannot hold up the release pages or opening animation. A list error reaches both.
pub fn releases_and_updates(
on_releases: impl FnOnce(Result<Vec<Release>, String>),
) -> Result<Updates, String> {
releases_and_updates_with(release_list, installed, launcher_releases_in, on_releases)
}
fn releases_and_updates_with(
load: impl FnOnce() -> Result<serde_json::Value, String>,
installed: impl FnOnce() -> Vec<String>,
launchers: impl FnOnce(&serde_json::Value) -> Vec<Release>,
on_releases: impl FnOnce(Result<Vec<Release>, String>),
) -> Result<Updates, String> {
let list = match load() {
Ok(list) => list,
Err(e) => {
on_releases(Err(e.clone()));
return Err(e);
}
};
let releases = parse_releases(&list, ASSET, is_game_tag);
let horizon = horizon_update(&releases, &installed());
on_releases(Ok(releases));
Ok(Updates {
horizon: horizon_update(&parse_releases(&list, ASSET, is_game_tag), &installed()),
launcher: launcher_update(&launcher_releases_in(&list)),
horizon,
launcher: launcher_update(&launchers(&list)),
})
}
/// A fresh release-list request for both kinds of update (plus older-launcher fallback if needed).
pub fn check_updates() -> Result<Updates, String> {
releases_and_updates(|_| {})
}
/// Whether a version installed as an update becomes the selected one: only when the player was
/// on the newest installed version before (or had none).
pub fn select_after_update(selected: Option<&str>, installed_before: &[String]) -> bool {
@@ -1633,6 +1666,10 @@ impl Settings {
}
}
#[cfg(test)]
#[path = "backend/release_loading_tests.rs"]
mod release_loading_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,240 @@
use super::*;
use std::cell::RefCell;
use std::hint::black_box;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
fn fixture() -> String {
let mut list: Vec<_> = (1..=99)
.map(|i| {
serde_json::json!({
"tag_name": format!("v2026.10.14.{i}"),
"name": format!("Build {i}"), "body": "Release notes\r\n".repeat(256),
"published_at": "2026-10-14T12:00:00Z", "draft": i == 99,
"assets": [{"name": ASSET.unwrap_or("unsupported"),
"browser_download_url": "https://example.test/game", "size": 12345}]
})
})
.collect();
list.push(serde_json::json!({
"tag_name": "launcher-v99.0.0", "name": "Launcher", "body": "Notes",
"assets": [{"name": LAUNCHER_ASSET.unwrap_or("unsupported"),
"browser_download_url": "https://example.test/launcher", "size": 6789}]
}));
serde_json::to_string(&list).unwrap()
}
fn installed_fixture() -> Vec<String> {
vec!["v2026.10.14.50".into()]
}
// The former startup paths: each decodes its own response; the update path parses games again.
fn baseline(load: impl Fn() -> Result<serde_json::Value, String>) -> (Vec<Release>, Updates) {
let releases = parse_releases(&load().unwrap(), ASSET, is_game_tag);
let list = load().unwrap();
let updates = Updates {
horizon: horizon_update(
&parse_releases(&list, ASSET, is_game_tag),
&installed_fixture(),
),
launcher: launcher_update(&parse_releases(&list, LAUNCHER_ASSET, is_launcher_tag)),
};
(releases, updates)
}
fn shared(load: impl FnOnce() -> Result<serde_json::Value, String>) -> (Vec<Release>, Updates) {
let mut releases = None;
let updates = releases_and_updates_with(
load,
installed_fixture,
|list| parse_releases(list, LAUNCHER_ASSET, is_launcher_tag),
|r| releases = Some(r.unwrap()),
)
.unwrap();
(releases.unwrap(), updates)
}
#[test]
fn one_response_preserves_both_startup_results() {
let text = fixture();
let requests = AtomicUsize::new(0);
let load = || {
requests.fetch_add(1, Ordering::Relaxed);
Ok(serde_json::from_str(&text).unwrap())
};
let old = baseline(load);
assert_eq!(requests.swap(0, Ordering::Relaxed), 2);
let new = shared(load);
assert_eq!(requests.load(Ordering::Relaxed), 1);
assert_eq!(
serde_json::to_value(old).unwrap(),
serde_json::to_value(new).unwrap()
);
}
#[test]
fn errors_reach_releases_and_updates_without_fallback() {
for error in [
"No connection: offline",
"GitHub's rate limit was reached.",
"invalid JSON",
] {
let mut published = None;
let result = releases_and_updates_with(
|| Err(error.into()),
|| panic!("no installed scan after failure"),
|_| panic!("no fallback after failure"),
|r| published = Some(r),
);
assert_eq!(published.unwrap().unwrap_err(), error);
assert_eq!(result.unwrap_err(), error);
}
}
#[test]
fn publish_games_before_older_launcher_fallback() {
let events = RefCell::new(Vec::new());
let result = releases_and_updates_with(
|| Ok(serde_json::json!([{"tag_name": "v2026.10.14", "assets": []}])),
Vec::new,
|list| {
launcher_releases_in_with(list, |url| {
assert_eq!(events.borrow().first(), Some(&"releases"));
events.borrow_mut().push("fallback");
if url.contains("matching-refs") {
Ok(serde_json::json!([{"ref": "refs/tags/launcher-v99.0.0"}]))
} else {
Ok(
serde_json::json!({"tag_name": "launcher-v99.0.0", "assets": [{
"name": LAUNCHER_ASSET.unwrap_or("unsupported"),
"browser_download_url": "u", "size": 1
}]}),
)
}
})
},
|r| {
assert_eq!(r.unwrap()[0].tag, "v2026.10.14");
events.borrow_mut().push("releases");
},
)
.unwrap();
assert_eq!(*events.borrow(), ["releases", "fallback", "fallback"]);
assert_eq!(result.launcher.is_some(), LAUNCHER_ASSET.is_some());
}
#[test]
fn failed_launcher_fallback_keeps_game_result_and_checks_stay_fresh() {
let requests = AtomicUsize::new(0);
for day in [14, 15] {
let mut published = None;
let updates = releases_and_updates_with(
|| {
requests.fetch_add(1, Ordering::Relaxed);
Ok(serde_json::json!([{"tag_name": format!("v2026.10.{day}")}]))
},
Vec::new,
|list| launcher_releases_in_with(list, |_| Err("offline".into())),
|r| published = Some(r.unwrap()),
)
.unwrap();
assert_eq!(published.unwrap()[0].tag, format!("v2026.10.{day}"));
assert!(updates.launcher.is_none());
}
assert_eq!(requests.load(Ordering::Relaxed), 2);
}
#[test]
#[ignore = "local release-loading benchmark; run explicitly with --ignored --nocapture"]
fn benchmark_shared_startup_response() {
let text = fixture();
let requests = AtomicUsize::new(0);
let load = |delay: Duration| {
requests.fetch_add(1, Ordering::Relaxed);
if !delay.is_zero() {
std::thread::sleep(delay);
}
serde_json::from_str(black_box(&text)).map_err(|e| e.to_string())
};
let old = || baseline(|| load(Duration::ZERO));
let new = || shared(|| load(Duration::ZERO));
assert_eq!(
serde_json::to_value(old()).unwrap(),
serde_json::to_value(new()).unwrap()
);
let concurrent_old = || {
std::thread::scope(|scope| {
let releases = scope.spawn(|| {
parse_releases(&load(Duration::from_millis(5)).unwrap(), ASSET, is_game_tag)
});
let updates = scope.spawn(|| {
let list = load(Duration::from_millis(5)).unwrap();
Updates {
horizon: horizon_update(
&parse_releases(&list, ASSET, is_game_tag),
&installed_fixture(),
),
launcher: launcher_update(&parse_releases(
&list,
LAUNCHER_ASSET,
is_launcher_tag,
)),
}
});
(releases.join().unwrap(), updates.join().unwrap())
})
};
let threaded_new = || {
std::thread::scope(|scope| {
scope
.spawn(|| shared(|| load(Duration::from_millis(5))))
.join()
.unwrap()
})
};
assert_eq!(
serde_json::to_value(concurrent_old()).unwrap(),
serde_json::to_value(threaded_new()).unwrap()
);
fn measure<T>(run: impl Fn() -> T, requests: &AtomicUsize) -> (u128, usize) {
for _ in 0..20 {
black_box(run());
}
requests.store(0, Ordering::Relaxed);
let mut times: Vec<_> = (0..201)
.map(|_| {
let start = Instant::now();
black_box(run());
start.elapsed().as_nanos()
})
.collect();
times.sort_unstable();
(times[100], requests.load(Ordering::Relaxed))
}
println!(
"fixture={} bytes; 100 releases; 20 warmups, 201 samples; median ns",
text.len()
);
for (label, before, after) in [
(
"serial zero-delay work",
measure(old, &requests),
measure(new, &requests),
),
(
"concurrent startup, 5ms/request",
measure(concurrent_old, &requests),
measure(threaded_new, &requests),
),
] {
assert_eq!((before.1, after.1), (402, 201));
println!(
"{label}: before={} after={} ratio={:.3}x requests={}->{}",
before.0,
after.0,
before.0 as f64 / after.0 as f64,
before.1,
after.1
);
}
}
+12 -2
View File
@@ -250,9 +250,8 @@ impl Launcher {
let _ = tx.send(Msg::Reused(reused));
}
});
this.fetch_releases();
this.fetch_startup_releases();
this.fetch_links();
this.check_updates();
this
}
@@ -319,6 +318,17 @@ impl Launcher {
});
}
fn fetch_startup_releases(&mut self) {
self.checked = Some(Instant::now());
let tx = self.tx.clone();
std::thread::spawn(move || {
let updates = backend::releases_and_updates(|releases| {
let _ = tx.send(Msg::Releases(releases));
});
let _ = tx.send(Msg::Updates(updates));
});
}
fn fetch_links(&self) {
let tx = self.tx.clone();
std::thread::spawn(move || {
+19 -13
View File
@@ -8,9 +8,10 @@ from tools import release_train as train
NOW = dt.datetime(2026, 10, 15, 12, 0, tzinfo=dt.timezone.utc)
def pr(number, title="Fix a thing", labels=(), paths=("crates/horizon-client/src/game.rs",), issues=(), author="ludovic111"):
def pr(number, title="Fix a thing", labels=(), paths=("crates/horizon-client/src/game.rs",), issues=(), author="ludovic111",
merged=dt.timedelta(hours=9)):
return {"number": number, "title": title, "labels": list(labels), "paths": list(paths), "issues": list(issues),
"author": author, "url": f"https://github.com/ludovic111/horizon/pull/{number}"}
"author": author, "url": f"https://github.com/ludovic111/horizon/pull/{number}", "merged_at": NOW - merged}
class ReleaseTrainTests(unittest.TestCase):
@@ -47,17 +48,19 @@ class ReleaseTrainTests(unittest.TestCase):
self.assertEqual(train.next_launcher_tag(tags, minor=True), "launcher-v0.2.0")
def test_decision(self):
hour = dt.timedelta(hours=1)
decide = lambda prs, age, **kw: train.decision("game", prs, NOW - age, NOW, **kw)[0]
self.assertTrue(decide([pr(1)], 4 * hour))
self.assertFalse(decide([pr(1)], 2 * hour), "within the cooldown")
self.assertTrue(decide([pr(1, labels=["release-now"])], 0.1 * hour))
self.assertFalse(decide([pr(1, paths=[])], 9 * hour), "nothing players run")
self.assertFalse(decide([pr(1, labels=["skip-release"])], 9 * hour))
self.assertFalse(decide([pr(1, labels=["release-now", "skip-release"])], 9 * hour))
self.assertFalse(decide([pr(1)], 9 * hour, paused=True))
self.assertTrue(decide([], 0.1 * hour, paused=True, force=True))
self.assertTrue(train.decision("game", [pr(1)], None, NOW)[0], "the first release")
minute = dt.timedelta(minutes=1)
decide = lambda prs, **kw: train.decision("game", prs, NOW, **kw)[0]
self.assertTrue(decide([pr(1, merged=16 * minute)]), "settled for the debounce")
self.assertFalse(decide([pr(1, merged=5 * minute)]), "merged moments ago")
self.assertFalse(decide([pr(1, merged=40 * minute), pr(2, merged=5 * minute)]), "a burst still merging")
self.assertTrue(decide([pr(1, merged=61 * minute), pr(2, merged=2 * minute)]), "merges that never pause still ship")
self.assertTrue(decide([pr(1, labels=["release-now"], merged=minute)]))
self.assertFalse(decide([pr(1, paths=[])]), "nothing players run")
self.assertFalse(decide([pr(1, labels=["skip-release"])]))
self.assertFalse(decide([pr(1, labels=["release-now", "skip-release"])]))
self.assertFalse(decide([pr(1, merged=5 * minute), pr(2, labels=["skip-release"], merged=minute)]), "the settled one waits for nothing")
self.assertFalse(decide([pr(1)], paused=True))
self.assertTrue(decide([], paused=True, force=True))
def test_notes(self):
prs = [pr(5, "Nether portals: vanilla timing and linking (fixes #94)", issues=[94]),
@@ -73,6 +76,9 @@ class ReleaseTrainTests(unittest.TestCase):
self.assertNotIn("#8", body)
self.assertIn("Thanks to @cosmic.", body)
self.assertLess(body.index("### New"), body.index("### Fixed"))
title, _ = train.notes("game", "v2026.10.15.2", [pr(9, "Horizon's mark", labels=["feature"]),
pr(10, "Game menus", labels=["feature"])], [])
self.assertEqual(title, "Horizon 2026.10.15.2: Game menus, Horizon's mark", "proper nouns keep their capital")
def test_a_long_release_is_named_after_its_first_titles(self):
prs = [pr(n, f"Change number {n} with a fairly long title") for n in range(1, 10)]
+5
View File
@@ -12,5 +12,10 @@ if [ "$(uname)" = Darwin ]; then
java_home=$(/usr/libexec/java_home -v "$java_major")
{ echo "$bin"; echo "$java_home/bin"; echo /opt/homebrew/bin; } >> "$GITHUB_PATH"
echo "JAVA_HOME=$java_home" >> "$GITHUB_ENV"
# Builds go through the machine's sccache (shared with ~/fleet/rbuild), so the build folders runner-gc.sh
# removes come back from the cache instead of compiling cold.
if [ -x /opt/homebrew/bin/sccache ]; then
{ echo "RUSTC_WRAPPER=/opt/homebrew/bin/sccache"; echo "CARGO_INCREMENTAL=0"; } >> "$GITHUB_ENV"
fi
fi
echo "HORIZON_NO_AUDIO=1" >> "$GITHUB_ENV"
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Keeps the Mac mini's Horizon runners from filling its disk. launchd runs a copy taken from main
# (~/.actions-runners/runner-gc.sh, never a pull request's checkout) every 6 hours; see docs/release-flow.md.
# - A runner in the middle of a job is left alone.
# - A checkout whose cargo build folders (target/ and the harness probes' targets under .local/, the
# directories holding a CACHEDIR.TAG) pass MAX_TARGET_GB loses them: sccache (tools/ci/runner-env.sh)
# makes the next build cheap. Symlinks into the shared vanilla data are never followed.
# - Harness work folders under .local/ (vanilla exports, probe outputs: real directories, not the links into
# the shared vanilla data) that nothing touched for STALE_DAYS go; a harness that runs again rebuilds its own.
# .local/parity-runner (run state, oracle cache) stays.
# - The shared prepared resources keep their KEEP_PREPARED newest preparations, only while no runner works.
set -euo pipefail
root=${RUNNERS:-$HOME/.actions-runners}
max_kb=$(( ${MAX_TARGET_GB:-12} * 1024 * 1024 ))
keep=${KEEP_PREPARED:-2}
stale_min=$(( ${STALE_DAYS:-3} * 24 * 60 ))
busy() { pgrep -f "$1/bin/Runner.Worker" > /dev/null; }
any_busy=0
for runner in "$root"/horizon "$root"/horizon-[0-9]*; do
[ -d "$runner/_work" ] || continue
if busy "$runner"; then echo "$(basename "$runner"): in a job, skipped"; any_busy=1; continue; fi
rm -rf "${runner:?}/_work/_temp/"* 2>/dev/null || true
checkout="$runner/_work/horizon/horizon"
[ -d "$checkout" ] || continue
stale=0
for dir in "$checkout"/.local/*/; do
dir=${dir%/}
[ -L "$dir" ] || [ "$(basename "$dir")" = parity-runner ] && continue
if [ -z "$(find "$dir" -mmin -"$stale_min" -print -quit 2>/dev/null)" ]; then rm -rf "$dir"; stale=$((stale + 1)); fi
done
[ "$stale" = 0 ] || echo "$(basename "$runner"): removed $stale harness folders untouched for ${STALE_DAYS:-3} days"
targets=()
[ -f "$checkout/target/CACHEDIR.TAG" ] && targets+=("$checkout/target")
while IFS= read -r tag; do targets+=("$(dirname "$tag")"); done < <(
find "$checkout/.local" -mindepth 2 -maxdepth 2 -name CACHEDIR.TAG -type f 2>/dev/null)
[ ${#targets[@]} -gt 0 ] || continue
size=$(du -sk "${targets[@]}" | awk '{s += $1} END {print s}')
if [ "$size" -gt "$max_kb" ]; then
rm -rf "${targets[@]}"
echo "$(basename "$runner"): removed ${#targets[@]} build folders ($(( size / 1024 / 1024 )) GB)"
fi
done
prepared="$root/horizon/_work/horizon/shared-local/prepared"
if [ "$any_busy" = 0 ] && [ -d "$prepared" ] && mkdir "$prepared/.lock" 2>/dev/null; then
trap 'rmdir "$prepared/.lock" 2>/dev/null || true' EXIT
ls -1t "$prepared" | tail -n +"$(( keep + 1 ))" | while read -r old; do
rm -rf "${prepared:?}/$old"
echo "prepared resources $old removed"
done
fi
df -h "$root" | tail -1

Some files were not shown because too many files have changed in this diff Show More