Merge pull request #2988 from horizon-rust/refactor/be-layer-deps

🤖 Agent: verify passes on this head; full pr_ready green on the Mac mini (1340 tests, parity 89 affected / 0 failed). Move-only step B6 of the crate split (crate-split-1).
This commit is contained in:
Ludovic Marie
2026-10-27 23:27:53 +01:00
committed by GitHub
16 changed files with 201 additions and 174 deletions
@@ -16,3 +16,20 @@ pub fn parse_identifier(raw: &str) -> Option<String> {
});
(ns_ok && path_ok).then(|| format!("{ns}:{path}"))
}
/// `Identifier.CODEC` parsing an entity id: lowercase namespace and path
/// characters, `minecraft` when the namespace is left out.
pub fn normalize_id(s: &str) -> Option<String> {
let (ns, path) = match s.split_once(':') {
Some((ns, path)) => (if ns.is_empty() { "minecraft" } else { ns }, path),
None => ("minecraft", s),
};
let ok = |c: char, slash: bool| {
c.is_ascii_lowercase()
|| c.is_ascii_digit()
|| matches!(c, '_' | '-' | '.')
|| slash && c == '/'
};
(ns.chars().all(|c| ok(c, false)) && path.chars().all(|c| ok(c, true)))
.then(|| format!("{ns}:{path}"))
}
@@ -22,3 +22,11 @@ pub fn number(tag: Option<&Tag>) -> Option<i64> {
_ => return None,
})
}
/// Any numeric tag as f64, keeping a float's or double's fraction.
pub fn float(tag: Option<&Tag>) -> Option<f64> {
Some(match tag? {
Tag::Float(b) => f64::from(f32::from_bits(*b)),
Tag::Double(b) => f64::from_bits(*b),
other => number(Some(other))? as f64,
})
}
+1 -1
View File
@@ -4,8 +4,8 @@
//! `BrewingStandBlockEntity.serverTick`.
pub use crate::chunk::block_entity::BrewingStand;
use crate::{
containers::Providers,
items::{ItemStack, Items},
providers::Providers,
};
use serde_json::Value;
use std::{collections::HashSet, fs, path::Path};
+5 -4
View File
@@ -2,8 +2,9 @@
//! count comparators read, the output it keeps, and the powered, automatic
//! and condition flags `CommandBlock.tick` runs on.
pub use crate::chunk::block_entity::CommandBlock;
use crate::{
save::{number, text},
use horizon_client_core::{
nbt_value::{number, text},
scoreboard,
text::Text,
};
use horizon_world::nbt::Tag;
@@ -108,7 +109,7 @@ impl CommandBlock {
last_output: track_output
.then(|| tag.get("LastOutput"))
.flatten()
.map(|t| crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t))),
.map(|t| scoreboard::comp_text(&scoreboard::tag_to_json(t))),
update_last_execution,
last_execution: if update_last_execution {
number(tag.get("LastExecution")).unwrap_or(-1)
@@ -164,7 +165,7 @@ impl CommandBlock {
pub fn name(&self) -> Text {
self.custom_name.as_ref().map_or_else(
|| Text::literal("@"),
|t| crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)),
|t| scoreboard::comp_text(&scoreboard::tag_to_json(t)),
)
}
}
+2 -118
View File
@@ -9,8 +9,7 @@ use crate::{
crafting::Recipes,
items::{ItemStack, Items},
};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path, sync::Arc};
use std::{collections::HashMap, sync::Arc};
impl FurnaceKind {
pub fn recipe_type(self) -> &'static str {
@@ -380,122 +379,7 @@ impl BlockEntity {
}
}
}
/// Evaluator for `context_int_provider` / `context_float_provider` values.
pub struct Providers {
ints: HashMap<String, Value>,
floats: HashMap<String, Value>,
}
fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap<String, Value>) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for e in entries.flatten() {
let p = e.path();
let name = p
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_owned();
if p.is_dir() {
load_dir(&p, &format!("{prefix}{name}/"), out);
} else if let Ok(bytes) = fs::read(&p)
&& let Ok(v) = serde_json::from_slice(&bytes)
{
out.insert(format!("minecraft:{prefix}{name}"), v);
}
}
}
impl Providers {
pub fn load(root: &Path) -> Self {
let mut ints = HashMap::new();
let mut floats = HashMap::new();
load_dir(
&root.join("data/minecraft/context_int_provider"),
"",
&mut ints,
);
load_dir(
&root.join("data/minecraft/context_float_provider"),
"",
&mut floats,
);
Self { ints, floats }
}
fn eval(v: &Value, fast: bool, table: &HashMap<String, Value>, depth: u32) -> f64 {
if depth > 16 {
return 0.0;
}
match v {
Value::Number(n) => n.as_f64().unwrap_or(0.0),
Value::String(name) => table
.get(name)
.map_or(0.0, |v| Self::eval(v, fast, table, depth + 1)),
Value::Object(o) => {
let f =
|k: &str| Self::eval(o.get(k).unwrap_or(&Value::Null), fast, table, depth + 1);
match o.get("type").and_then(Value::as_str).unwrap_or("") {
"minecraft:div" => {
let r = f("right");
if r == 0.0 {
0.0
} else {
(f("left") / r).trunc()
}
}
"minecraft:mul" => f("left") * f("right"),
"minecraft:add" | "minecraft:sum" => f("left") + f("right"),
"minecraft:sub" => f("left") - f("right"),
"minecraft:constant" => f("value"),
"minecraft:conditional" => {
// The only condition in the pinned data: block/fast_cooking.
let condition = o.get("condition").and_then(Value::as_str)
== Some("minecraft:block/fast_cooking");
if condition && fast {
f("on_true")
} else {
f("on_false")
}
}
_ => 0.0,
}
}
_ => 0.0,
}
}
/// A plain `context_int_provider` value or reference (no context conditions).
pub fn int_value(&self, v: &Value) -> i32 {
Self::eval(v, false, &self.ints, 0) as i32
}
/// A plain `context_float_provider` value or reference; `default` when absent.
pub fn float_value(&self, v: &Value, default: f32) -> f32 {
if v.is_null() {
default
} else {
Self::eval(v, false, &self.floats, 0) as f32
}
}
#[cfg(test)]
pub fn empty() -> Self {
Self {
ints: HashMap::new(),
floats: HashMap::new(),
}
}
pub fn burn_time(&self, items: &Items, stack: &ItemStack, fast: bool) -> i32 {
items
.get(&stack.item)
.and_then(|i| i.fuel.as_ref())
.map_or(0, |(time, _)| Self::eval(time, fast, &self.ints, 0) as i32)
}
pub fn speed(&self, items: &Items, stack: &ItemStack, fast: bool) -> f32 {
items
.get(&stack.item)
.and_then(|i| i.fuel.as_ref())
.map_or(1.0, |(_, speed)| {
Self::eval(speed, fast, &self.floats, 0) as f32
})
}
}
pub use crate::providers::Providers;
fn remainder(item: &str) -> Option<&'static str> {
match item {
"minecraft:lava_bucket" | "minecraft:water_bucket" | "minecraft:milk_bucket" => {
+1
View File
@@ -133,6 +133,7 @@ pub mod portal_sections;
pub mod pose;
pub mod pregen;
pub mod projectiles;
pub mod providers;
pub mod raid;
pub mod random_tick_sections;
pub mod recipe_book;
+1 -16
View File
@@ -111,22 +111,7 @@ impl SpawnData {
}
}
/// `Identifier.CODEC` parsing an entity id: lowercase namespace and path
/// characters, `minecraft` when the namespace is left out.
pub fn normalize_id(s: &str) -> Option<String> {
let (ns, path) = match s.split_once(':') {
Some((ns, path)) => (if ns.is_empty() { "minecraft" } else { ns }, path),
None => ("minecraft", s),
};
let ok = |c: char, slash: bool| {
c.is_ascii_lowercase()
|| c.is_ascii_digit()
|| matches!(c, '_' | '-' | '.')
|| slash && c == '/'
};
(ns.chars().all(|c| ok(c, false)) && path.chars().all(|c| ok(c, true)))
.then(|| format!("{ns}:{path}"))
}
pub use horizon_client_core::identifier::normalize_id;
/// How much a slime's or magma cube's box is scaled by the size its data
/// loads (`Slime.readAdditionalSaveData`: Size + 1, kept in 1..=127), which
@@ -790,20 +790,6 @@ pub fn golem_detected(m: &mut Mob, now: i64) {
// ---- Behaviours ---------------------------------------------------------
pub use crate::poi_sections::Poi;
impl Poi {
fn max_tickets(self) -> usize {
match self {
Poi::Meeting => 32,
_ => 1,
}
}
fn valid_range(self) -> i32 {
match self {
Poi::Meeting => 6,
_ => 1,
}
}
}
/// The POI a block state is (`PoiTypes`): job site blocks, bed heads, bells.
pub fn poi_at(w: &MobWorld, x: i32, y: i32, z: i32) -> Option<Poi> {
poi_of_state(w, w.world.block(x, y, z))
+16
View File
@@ -87,6 +87,22 @@ pub enum Poi {
Home,
Meeting,
}
impl Poi {
/// `PoiType.maxTickets`.
pub fn max_tickets(self) -> usize {
match self {
Poi::Meeting => 32,
_ => 1,
}
}
/// `PoiType.validRange`.
pub fn valid_range(self) -> i32 {
match self {
Poi::Meeting => 6,
_ => 1,
}
}
}
#[cfg(test)]
mod tests {
+122
View File
@@ -0,0 +1,122 @@
//! Vanilla's `context_int_provider` and `context_float_provider` values (furnace
//! fuel times, brewing times), evaluated from the data pack's JSON.
use crate::items::{ItemStack, Items};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
/// Evaluator for `context_int_provider` / `context_float_provider` values.
pub struct Providers {
ints: HashMap<String, Value>,
floats: HashMap<String, Value>,
}
fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap<String, Value>) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for e in entries.flatten() {
let p = e.path();
let name = p
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_owned();
if p.is_dir() {
load_dir(&p, &format!("{prefix}{name}/"), out);
} else if let Ok(bytes) = fs::read(&p)
&& let Ok(v) = serde_json::from_slice(&bytes)
{
out.insert(format!("minecraft:{prefix}{name}"), v);
}
}
}
impl Providers {
pub fn load(root: &Path) -> Self {
let mut ints = HashMap::new();
let mut floats = HashMap::new();
load_dir(
&root.join("data/minecraft/context_int_provider"),
"",
&mut ints,
);
load_dir(
&root.join("data/minecraft/context_float_provider"),
"",
&mut floats,
);
Self { ints, floats }
}
fn eval(v: &Value, fast: bool, table: &HashMap<String, Value>, depth: u32) -> f64 {
if depth > 16 {
return 0.0;
}
match v {
Value::Number(n) => n.as_f64().unwrap_or(0.0),
Value::String(name) => table
.get(name)
.map_or(0.0, |v| Self::eval(v, fast, table, depth + 1)),
Value::Object(o) => {
let f =
|k: &str| Self::eval(o.get(k).unwrap_or(&Value::Null), fast, table, depth + 1);
match o.get("type").and_then(Value::as_str).unwrap_or("") {
"minecraft:div" => {
let r = f("right");
if r == 0.0 {
0.0
} else {
(f("left") / r).trunc()
}
}
"minecraft:mul" => f("left") * f("right"),
"minecraft:add" | "minecraft:sum" => f("left") + f("right"),
"minecraft:sub" => f("left") - f("right"),
"minecraft:constant" => f("value"),
"minecraft:conditional" => {
// The only condition in the pinned data: block/fast_cooking.
let condition = o.get("condition").and_then(Value::as_str)
== Some("minecraft:block/fast_cooking");
if condition && fast {
f("on_true")
} else {
f("on_false")
}
}
_ => 0.0,
}
}
_ => 0.0,
}
}
/// A plain `context_int_provider` value or reference (no context conditions).
pub fn int_value(&self, v: &Value) -> i32 {
Self::eval(v, false, &self.ints, 0) as i32
}
/// A plain `context_float_provider` value or reference; `default` when absent.
pub fn float_value(&self, v: &Value, default: f32) -> f32 {
if v.is_null() {
default
} else {
Self::eval(v, false, &self.floats, 0) as f32
}
}
#[cfg(test)]
pub fn empty() -> Self {
Self {
ints: HashMap::new(),
floats: HashMap::new(),
}
}
pub fn burn_time(&self, items: &Items, stack: &ItemStack, fast: bool) -> i32 {
items
.get(&stack.item)
.and_then(|i| i.fuel.as_ref())
.map_or(0, |(time, _)| Self::eval(time, fast, &self.ints, 0) as i32)
}
pub fn speed(&self, items: &Items, stack: &ItemStack, fast: bool) -> f32 {
items
.get(&stack.item)
.and_then(|i| i.fuel.as_ref())
.map_or(1.0, |(_, speed)| {
Self::eval(speed, fast, &self.floats, 0) as f32
})
}
}
+1 -8
View File
@@ -105,14 +105,7 @@ pub fn chunks_with_block_entities<'a>(
}
use horizon_client_core::nbt_value::string;
pub use horizon_client_core::nbt_value::{number, text};
pub(crate) fn float(tag: Option<&Tag>) -> Option<f64> {
Some(match tag? {
Tag::Float(b) => f64::from(f32::from_bits(*b)),
Tag::Double(b) => f64::from_bits(*b),
other => number(Some(other))? as f64,
})
}
pub use horizon_client_core::nbt_value::{float, number, text};
/// Insert or replace a key of a compound tag.
pub(crate) fn put(tag: &mut Tag, key: &str, value: Tag) {
if let Tag::Compound(map) = tag {
+4 -2
View File
@@ -2,7 +2,7 @@
//! `VibrationSelector`) shared by sculk sensors, shriekers and wardens, the
//! sculk block entities and the per-player warden spawn tracker.
pub use crate::chunk::block_entity::{Data, Info, SculkEntity, SculkKind, Selector};
use crate::mobs::Who;
use horizon_client_core::who::Who;
use horizon_core::{
geometry::{Direction, Vec3, traverse_blocks},
position::BlockPos,
@@ -315,7 +315,9 @@ fn info_to_nbt(info: &Info) -> Tag {
])
}
fn info_from_nbt(tag: &Tag) -> Option<Info> {
let event = intern(&crate::save::text(tag.get("game_event"))?)?;
let event = intern(&horizon_client_core::nbt_value::text(
tag.get("game_event"),
)?)?;
let distance = match tag.get("distance") {
Some(Tag::Float(f)) => f32::from_bits(*f),
_ => 0.0,
+18 -10
View File
@@ -48,7 +48,9 @@ impl VaultConfig {
let Tag::Compound(_) = tag else {
return None;
};
let range = |k: &str, default: f64| crate::save::float(tag.get(k)).unwrap_or(default);
let range = |k: &str, default: f64| {
horizon_client_core::nbt_value::float(tag.get(k)).unwrap_or(default)
};
let config = Self {
loot_table: identifier(tag.get("loot_table"))
.unwrap_or_else(|| DEFAULT_LOOT_TABLE.into()),
@@ -81,7 +83,7 @@ impl VaultConfig {
);
}
if let Some(key) = &self.key_item {
out.insert("key_item".into(), crate::save::item_to_nbt(key));
out.insert("key_item".into(), horizon_items::item_nbt::item_to_nbt(key));
}
if let Some(table) = &self.override_loot_table_to_display {
out.insert(
@@ -181,7 +183,7 @@ impl Default for Vault {
/// An `Identifier` (`minecraft` when the namespace is left out).
fn identifier(t: Option<&Tag>) -> Option<String> {
match t? {
Tag::String(s) => crate::mobs::spawner::normalize_id(&s.to_string_lossy()),
Tag::String(s) => horizon_client_core::identifier::normalize_id(&s.to_string_lossy()),
_ => None,
}
}
@@ -189,11 +191,12 @@ fn identifier(t: Option<&Tag>) -> Option<String> {
fn stack(tag: &Tag) -> Option<ItemStack> {
let id = identifier(tag.get("id"))?;
if let Some(count) = tag.get("count")
&& !crate::save::number(Some(count)).is_some_and(|c| (1..=99).contains(&c))
&& !horizon_client_core::nbt_value::number(Some(count))
.is_some_and(|c| (1..=99).contains(&c))
{
return None;
}
let mut item = crate::save::item_from_nbt(tag)?;
let mut item = horizon_items::item_nbt::item_from_nbt(tag)?;
item.item = id.as_str().into();
(&*item.item != "minecraft:air").then_some(item)
}
@@ -266,7 +269,8 @@ impl Vault {
let get = |k: &str| server.and_then(|s| s.get(k));
v.rewarded_players = uuids(get("rewarded_players")).unwrap_or_default();
v.state_updating_resumes_at =
crate::save::number(get("state_updating_resumes_at")).unwrap_or(0);
horizon_client_core::nbt_value::number(get("state_updating_resumes_at"))
.unwrap_or(0);
v.items_to_eject = match get("items_to_eject") {
Some(Tag::List(list)) => list
.iter()
@@ -281,8 +285,9 @@ impl Vault {
let get = |k: &str| shared.and_then(|s| s.get(k));
v.display_item = get("display_item").and_then(stack);
v.connected_players = uuids(get("connected_players")).unwrap_or_default();
v.connected_particles_range = crate::save::float(get("connected_particles_range"))
.unwrap_or(DEFAULT_DEACTIVATION_RANGE);
v.connected_particles_range =
horizon_client_core::nbt_value::float(get("connected_particles_range"))
.unwrap_or(DEFAULT_DEACTIVATION_RANGE);
}
v
}
@@ -305,7 +310,7 @@ impl Vault {
let items = self
.items_to_eject
.iter()
.map(crate::save::item_to_nbt)
.map(horizon_items::item_nbt::item_to_nbt)
.collect();
server.insert("items_to_eject".into(), Tag::List(items));
}
@@ -325,7 +330,10 @@ impl Vault {
fn update_shared(&self) -> Tag {
let mut out = Compound::new();
if let Some(item) = &self.display_item {
out.insert("display_item".into(), crate::save::item_to_nbt(item));
out.insert(
"display_item".into(),
horizon_items::item_nbt::item_to_nbt(item),
);
}
if !self.connected_players.is_empty() {
out.insert(
+1
View File
@@ -233,6 +233,7 @@ def main():
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs',
lab.ROOT / 'crates/horizon-client/src/chunk/block_entity.rs',
lab.ROOT / 'crates/horizon-client-core/src/identifier.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs']
tested = base.source_hashes(sources)
+1
View File
@@ -198,6 +198,7 @@ def main():
lab.ROOT / 'crates/horizon-client/src/mobs/trial_spawner.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs',
lab.ROOT / 'crates/horizon-client/src/chunk/block_entity.rs',
lab.ROOT / 'crates/horizon-client-core/src/identifier.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs']
tested = base.source_hashes(sources)
+3 -1
View File
@@ -175,7 +175,9 @@ def main():
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/vault.rs',
lab.ROOT / 'crates/horizon-client/src/chunk/block_entity.rs']
lab.ROOT / 'crates/horizon-client/src/chunk/block_entity.rs',
lab.ROOT / 'crates/horizon-client-core/src/identifier.rs',
lab.ROOT / 'crates/horizon-client-core/src/nbt_value.rs']
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
cases = corpus()