Merge pull request #408 from Online5277/fix/sulfur-cube-inner-layer

🤖 Agent: merged by Ludovic's AI agent. CI parity passed on the head; combined with current main (and #680) locally: workspace clippy clean, horizon-client 826 + horizon-world tests pass, mob_ai/save_roundtrip/spawner PASS. Thanks @Online5277!
This commit is contained in:
Ludovic Marie
2026-10-17 19:30:36 +02:00
committed by GitHub
14 changed files with 433 additions and 36 deletions
+92 -1
View File
@@ -607,6 +607,29 @@ pub struct Entities<'a> {
pub tool: Option<&'a ItemView>,
pub block_pos: Option<[i32; 3]>,
}
/// Conditions shared by item/entity interactions and thrown-item pickups.
pub fn item_entity(
v: &Value,
player: &EntityView,
target: &EntityView,
stack: &ItemView,
w: &dyn World,
) -> bool {
let pctx = Entities {
this: Some(player),
origin: player.position,
tool: None,
block_pos: None,
};
let ectx = Entities {
this: Some(target),
..pctx
};
conditions(&v["player"], &pctx, w)
&& conditions(&v["entity"], &ectx, w)
&& item(&v["item"], stack, w)
}
/// A `ContextAwarePredicate`: a list of loot conditions (or one condition).
pub fn conditions(v: &Value, ctx: &Entities, w: &dyn World) -> bool {
match v {
@@ -996,7 +1019,75 @@ mod tests {
false
}
fn in_tag(&self, _: &str, tag: &str, id: &str) -> bool {
tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone"
(tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone")
|| (tag == "minecraft:sulfur_cube_archetype/explosive" && id == "minecraft:tnt")
}
}
#[test]
fn uh_oh_accepts_either_tnt_event_only_for_adult_sulfur_cubes() {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join(
"../../.local/horizon-client/26.3/data/minecraft/advancement/husbandry/uh_oh.json",
);
if !path.exists() {
return;
}
let json = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
let advancement = parse("minecraft:husbandry/uh_oh", &json).unwrap();
assert_eq!(advancement.criteria.len(), 2);
let player = EntityView {
kind: "minecraft:player".into(),
..Default::default()
};
let mut target = EntityView {
kind: "minecraft:sulfur_cube".into(),
..Default::default()
};
let mut stack = ItemView {
id: "minecraft:tnt".into(),
count: 1,
..Default::default()
};
for criterion in &advancement.criteria {
assert!(item_entity(
&criterion.conditions,
&player,
&target,
&stack,
&Flat
));
let mut progress = Progress::default();
progress.grant(&advancement.id, &criterion.name, "test");
assert!(
progress.done(&advancement),
"either criterion must award Uh Oh"
);
target.baby = true;
assert!(!item_entity(
&criterion.conditions,
&player,
&target,
&stack,
&Flat
));
target.baby = false;
target.kind = "minecraft:pig".into();
assert!(!item_entity(
&criterion.conditions,
&player,
&target,
&stack,
&Flat
));
target.kind = "minecraft:sulfur_cube".into();
stack.id = "minecraft:stone".into();
assert!(!item_entity(
&criterion.conditions,
&player,
&target,
&stack,
&Flat
));
stack.id = "minecraft:tnt".into();
}
}
#[test]
+2
View File
@@ -16,6 +16,7 @@ pub struct ItemEntity {
pub fire_ticks: i32,
pub id: u32,
pub stack: ItemStack,
pub thrower: Option<[i32; 4]>,
pub position: Vec3,
pub previous: Vec3,
pub velocity: Vec3,
@@ -610,6 +611,7 @@ mod fire_environment_tests {
.unwrap();
let make = |id: &str| ItemEntity {
id: 1,
thrower: None,
stack: ItemStack {
item: std::sync::Arc::from(id),
count: 1,
+13 -1
View File
@@ -863,7 +863,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
Some(m)
}
/// `ItemEntity`: Health, Age, PickupDelay, Item.
/// `ItemEntity`: Health, Age, PickupDelay, Item, Thrower.
pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
let base = Base {
id: "minecraft:item",
@@ -887,6 +887,11 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) ->
] {
put(&mut tag, key, value);
}
if let Some(thrower) = e.thrower {
put(&mut tag, "Thrower", Tag::IntArray(thrower.to_vec()));
} else if let Tag::Compound(map) = &mut tag {
map.remove(&"Thrower".into());
}
tag
}
pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option<ItemEntity> {
@@ -897,6 +902,7 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option<ItemE
fire_ticks: number(tag.get("Fire")).unwrap_or(0) as i32,
id,
stack,
thrower: uuid_from_tag(tag.get("Thrower")),
position,
previous: position,
velocity: motion(tag),
@@ -1529,6 +1535,7 @@ mod tests {
let e = ItemEntity {
health: 2,
fire_ticks: 73,
thrower: Some([5, 6, 7, 8]),
id: 7,
stack: ItemStack {
item: Arc::from("minecraft:diamond_pickaxe"),
@@ -1555,6 +1562,11 @@ mod tests {
(120, 10, true)
);
assert_eq!(back.position.x, 100.5);
assert_eq!(back.thrower, e.thrower);
let mut cleared = back;
cleared.thrower = None;
let cleared = item_entity_to_nbt(&cleared, [1, 2, 3, 4], Some(&tag));
assert!(cleared.get("Thrower").is_none());
}
#[test]
fn unknown_fields_survive() {
+7 -1
View File
@@ -1529,6 +1529,7 @@ impl Game<'_> {
self.dropped.push(ItemEntity {
health: 5,
fire_ticks: 0,
thrower: None,
id: self.next_entity,
stack,
position: p,
@@ -1611,6 +1612,10 @@ impl Game<'_> {
yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength,
];
self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40);
if self.lan_acting.is_none() {
let uuid = self.level.ensure_player_uuid();
self.dropped.last_mut().unwrap().thrower = Some(uuid);
}
}
fn tick_items(&mut self) {
let mut items = std::mem::take(&mut self.dropped);
@@ -5716,9 +5721,10 @@ impl Game<'_> {
let start = out.len();
self.block_model_vertices(
f.state,
f.start_pos,
horizon_core::random::position_seed(f.start_pos),
glam::Mat4::from_translation(o),
packed,
false,
&mut out,
);
let tint = horizon_client::mobs::render::abgr(tint);
@@ -642,6 +642,19 @@ impl Game<'_> {
adv::conditions(&c["player"], &pctx, w) && adv::item(&c["item"], &it, w)
});
}
pub(super) fn trigger_item_entity(
&mut self,
name: &str,
stack: &ItemStack,
target: &EntityView,
) {
if self.lan_acting.is_some() {
return;
}
let me = self.player_entity();
let it = item_view(stack);
self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w));
}
/// `EnterBlockTrigger`: the block, its state properties and the player.
pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) {
let Some(definition) = self.pack.assets.registry.state(state).cloned() else {
@@ -700,7 +700,7 @@ impl Game<'_> {
}
}
/// `AbstractSkullBlock.getType` of a skull item.
fn skull_kind(item: &str) -> Option<&'static str> {
pub(super) fn skull_kind(item: &str) -> Option<&'static str> {
Some(match item {
"minecraft:skeleton_skull" => "skeleton",
"minecraft:wither_skeleton_skull" => "wither_skeleton",
@@ -2253,6 +2253,10 @@ impl Game<'_> {
return Ok(true);
}
if self.interact_sulfur_cube(index, &item) {
if let Some(stack) = &held {
let target = self.mob_entity(&self.mobs[index]);
self.trigger_item_entity("minecraft:player_interacted_with_entity", stack, &target);
}
self.swing_arm();
return Ok(true);
}
@@ -2802,6 +2806,17 @@ impl Game<'_> {
if mob.fire_ticks > 0 || matches!(mob.species(), Species::Blaze | Species::MagmaCube) {
packed = (15 * 16) | ((15 * 16) << 8);
}
if mob.species() == Species::SulfurCube
&& !horizon_client::mobs::trader::is_invisible(mob)
{
self.sulfur_cube_body_geometry(
mob,
alpha as f32,
horizon_client::mobs::render::base_transform(mob, alpha as f32, camera),
packed,
out,
);
}
// Other players on a server: PlayerRenderer's HumanoidArmorLayer.
let armor = if &*mob.kind.id == "minecraft:player" {
self.worn_armor_layers(mob)
+25 -7
View File
@@ -17,7 +17,6 @@ use horizon_client::{
};
use horizon_core::{
geometry::{Aabb, Vec3},
position::BlockPos,
random::RandomSource,
};
use horizon_world::registry::BlockStateId;
@@ -1139,16 +1138,17 @@ impl Game<'_> {
}
}
}
/// A block model's faces under `m` (block space 0..1), lit flat.
/// Baked block faces with terrain shade or block-item diffuse lighting.
pub(super) fn block_model_vertices(
&self,
state: BlockStateId,
seed_pos: BlockPos,
seed: i64,
m: glam::Mat4,
light: u32,
diffuse: bool,
out: &mut Vec<Vertex>,
) {
let Ok(models) = self.pack.assets.model_catalog.collect(state, seed_pos) else {
let Ok(models) = self.pack.assets.model_catalog.collect_seeded(state, seed) else {
return;
};
for (_, model) in &models {
@@ -1168,12 +1168,30 @@ impl Game<'_> {
D::North | D::South => 204,
D::West | D::East => 153,
};
let color = 0xFF00_0000 | shade << 16 | shade << 8 | shade;
let color = if diffuse {
u32::MAX
} else {
0xFF00_0000 | shade << 16 | shade << 8 | shade
};
let normal = if diffuse {
use horizon_client::item_render::{direction_vector, transform_normal};
let n = transform_normal(m, direction_vector(face.quad.facing));
let n = n.to_array().map(|v| (v.clamp(-1.0, 1.0) * 127.0) as i8);
[n[0], n[1], n[2], 127]
} else {
[0; 4]
};
let light = if diffuse {
let emission = u32::from(face.quad.light_emission) * 16;
(light & 0xFF) | (light >> 8 & 0xFF).max(emission) << 8
} else {
light
};
for k in 0..4 {
let p = face.quad.positions[k];
let uv = face.quad.uv[k];
out.push(Vertex {
normal: [0; 4],
normal,
pos: m.transform_point3(glam::Vec3::from_array(p)).to_array(),
uv: [s.u0 + uv[0] * (s.u1 - s.u0), s.v0 + uv[1] * (s.v1 - s.v0)],
layer: 0,
@@ -1297,7 +1315,7 @@ impl Game<'_> {
* glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
let flash = c.kind == CartKind::Tnt && c.fuse > -1 && (c.fuse / 5) % 2 == 0;
let start = out.len();
self.block_model_vertices(state, BlockPos::default(), m, packed, out);
self.block_model_vertices(state, 0, m, packed, false, out);
if flash {
// submitWhiteSolidBlock: OverlayTexture.u(1.0) on the cart's own light.
for v in &mut out[start..] {
+1
View File
@@ -2025,6 +2025,7 @@ impl Game<'_> {
self.dropped.push(ItemEntity {
health: 5,
fire_ticks: 0,
thrower: None,
id: id as u32,
stack,
position: at,
@@ -427,6 +427,15 @@ impl Game<'_> {
* glam::Mat4::from_scale(glam::Vec3::splat(scale));
let light = self.world.light(key.0, key.1, key.2);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
if mob.species() == horizon_client::mobs::Species::SulfurCube {
self.sulfur_cube_body_geometry(
mob,
alpha as f32,
horizon_client::mobs::render::base_transform_at(mob, alpha as f32, origin),
packed,
out,
);
}
horizon_client::mobs::render::render_posed(
mob,
alpha as f32,
@@ -5,11 +5,77 @@
use super::Game;
use horizon_client::{
items::ItemStack,
mesher::Vertex,
mobs::{Mob, Species, sulfur_cube},
};
use horizon_core::random::RandomSource;
fn block_transform(base: glam::Mat4, baby: bool) -> glam::Mat4 {
base * glam::Mat4::from_scale(glam::Vec3::new(1.0, -1.0, -1.0))
* glam::Mat4::from_scale(glam::Vec3::splat(if baby { 0.5 } else { 1.0 }))
* glam::Mat4::from_translation(glam::Vec3::new(-0.5, -0.518, -0.5))
}
fn block_overlay(fuse_ticks: i32, alpha: f32, hurt: bool) -> u32 {
let fuse = if fuse_ticks >= 0 {
fuse_ticks as f32 - alpha + 1.0
} else {
0.0
};
if fuse > 0.0 && (fuse / 5.0) as i32 % 2 == 0 {
horizon_client::overlay::living(1.0, false)
} else {
horizon_client::overlay::living(0.0, hurt)
}
}
fn block_light(light: u32, emission: u8) -> u32 {
let block = (light >> 8 & 0xFF).max(u32::from(emission) * 16);
(light & 0xFF) | block << 8
}
impl Game<'_> {
/// The swallowed block replaces the opaque core and precedes the shell.
pub(super) fn sulfur_cube_body_geometry(
&self,
mob: &Mob,
alpha: f32,
base: glam::Mat4,
light: u32,
out: &mut Vec<Vertex>,
) {
let Some(item) = mob.extra.head.as_deref() else {
return;
};
if super::armor_stands::skull_kind(item).is_some() {
return;
}
// shortcut: the body slot retains only an item id; preserve the stack
// before supporting its block-state components here.
let Some(state) = self.res.items.get(item).and_then(|item| item.block) else {
return;
};
let start = out.len();
self.block_model_vertices(
state,
42,
block_transform(base, mob.is_baby()),
block_light(light, self.res.facts.get(state).emission),
true,
out,
);
let overlay = block_overlay(
sulfur_cube::fuse(mob),
alpha,
mob.hurt_time > 0 || mob.death_time > 0,
);
if overlay != 0 {
for vertex in &mut out[start..] {
vertex.layer = overlay;
}
}
}
fn sulfur_sound(&mut self, index: usize, sound: &str) {
let at = self.mobs[index].center();
self.audio
@@ -126,6 +192,11 @@ impl Game<'_> {
continue;
}
let item = e.stack.item.clone();
let thrown_by_player = e
.thrower
.is_some_and(|uuid| Some(uuid) == self.level.player_uuid);
let mut swallowed = e.stack.clone();
swallowed.count = 1;
let (taken_item, id) = (e.clone(), self.mobs[i].id);
self.add_pickup(
super::pickups::Taken::Item(Box::new(taken_item)),
@@ -140,6 +211,14 @@ impl Game<'_> {
m.extra.head = Some(item);
m.extra.point = None;
self.sulfur_sound(i, "entity.sulfur_cube.absorb");
if thrown_by_player {
let target = self.mob_entity(&self.mobs[i]);
self.trigger_item_entity(
"minecraft:thrown_item_picked_up_by_entity",
&swallowed,
&target,
);
}
}
}
/// `AbstractCubeMob.remove`: a dead adult splits into two babies (none
@@ -167,3 +246,46 @@ impl Game<'_> {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn swallowed_block_uses_vanilla_lift_and_baby_scale() {
let base = glam::Mat4::from_translation(glam::Vec3::new(3.0, 4.0, -2.0))
* glam::Mat4::from_rotation_y(0.7)
* glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0));
for baby in [false, true] {
let size = if baby { 0.5 } else { 1.0 };
let block = block_transform(base, baby);
for (point, expected) in [
(glam::Vec3::ZERO, glam::Vec3::new(-0.5, 0.518, 0.5)),
(glam::Vec3::ONE, glam::Vec3::new(0.5, -0.482, -0.5)),
] {
let actual = block.transform_point3(point);
let expected = base.transform_point3(expected * size);
assert!(actual.abs_diff_eq(expected, 1e-5), "baby={baby}");
}
assert!(block.transform_vector3(glam::Vec3::Y).y > 0.0);
}
}
#[test]
fn swallowed_tnt_flashes_white_over_hurt_using_the_interpolated_fuse() {
let white = horizon_client::overlay::WHITE + 15;
assert_eq!(block_overlay(-1, 0.0, false), 0);
assert_eq!(block_overlay(-1, 0.0, true), 1);
assert_eq!(block_overlay(9, 0.0, true), white);
assert_eq!(block_overlay(9, 0.5, false), 0);
assert_eq!(block_overlay(9, 0.5, true), 1);
assert_eq!(block_overlay(0, 0.5, false), white);
}
#[test]
fn contained_block_emission_preserves_brighter_light_and_the_sky_channel() {
assert_eq!(block_light(0x2050, 1), 0x2050);
assert_eq!(block_light(0x2050, 7), 0x7050);
assert_eq!(block_light(0x0070, 0), 0x0070);
}
}
+111 -11
View File
@@ -1041,17 +1041,24 @@ fn render_visible(
.unwrap_or_else(|| m.kind.model.clone());
let mut poses = Poses::new(&model);
anim::setup(m, &s, &mut poses, &data.animations);
if let Some(uv) = atlas(&texture) {
draw(
&model,
base,
&poses,
uv,
body_color(m, alpha),
light,
body_overlay(m, alpha),
out,
);
let draw_body = |out: &mut Vec<Vertex>| {
if let Some(uv) = atlas(&texture) {
draw(
&model,
base,
&poses,
uv,
body_color(m, alpha),
light,
body_overlay(m, alpha),
out,
);
}
};
// The translucent shell writes depth: draw the opaque core before it.
let shell_last = m.species() == Species::SulfurCube;
if !shell_last {
draw_body(out);
}
for (part, uv, color) in extra {
draw(part, base, &poses, *uv, *color, light, overlay, out);
@@ -1109,6 +1116,9 @@ fn render_visible(
}
}
}
if shell_last {
draw_body(out);
}
}
/// The equipment slot of a `HumanoidArmorLayer` model (`zombie#helmet`).
fn armor_slot(model: &str) -> Option<usize> {
@@ -1249,3 +1259,93 @@ pub fn held_item_transform(
anim::setup(m, &s, &mut poses, &data.animations);
hand_base(m, &model, base, &poses, left)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sulfur_cube_opaque_core_is_submitted_before_its_translucent_shell() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("entity-models.json").exists() {
return;
}
let mut types = super::super::MobTypes::load(&root).unwrap();
let kind = std::sync::Arc::new(types.types.remove("minecraft:sulfur_cube").unwrap());
let data = MobData {
states: Vec::new(),
placements: Default::default(),
heightmaps: Default::default(),
animations: Default::default(),
biome_tags: Default::default(),
entity_tags: Default::default(),
villager_hats: Default::default(),
pois: Default::default(),
};
let atlas = |name: &str| {
Some(if name.contains("_inner") {
[0.0, 0.0, 0.25, 0.25]
} else {
[0.5, 0.5, 0.75, 0.75]
})
};
for baby in [false, true] {
let mut mob = Mob::new(1, kind.clone(), horizon_core::geometry::Vec3::ZERO, 0.0);
mob.extra.age = if baby { -24000 } else { 0 };
super::super::sulfur_cube::finalize(&mut mob);
assert_eq!(mob.is_baby(), baby);
for posed in [false, true] {
let mut vertices = Vec::new();
if posed {
render_posed(
&mob,
0.5,
glam::Mat4::IDENTITY,
&atlas,
0xf0f0,
&data,
&mut vertices,
);
} else {
render(
&mob,
0.5,
glam::DVec3::ZERO,
&atlas,
0xf0f0,
&data,
&mut vertices,
);
}
assert_eq!(
vertices.len(),
48,
"both real six-face models must be drawn"
);
assert!(
vertices[..24].iter().all(|v| v.uv[0] <= 0.25),
"opaque core must precede shell"
);
assert!(vertices[24..].iter().all(|v| v.uv[0] >= 0.5));
}
mob.extra.head = Some("minecraft:stone".into());
let mut vertices = Vec::new();
render(
&mob,
0.5,
glam::DVec3::ZERO,
&atlas,
0xf0f0,
&data,
&mut vertices,
);
assert_eq!(
vertices.len(),
24,
"a swallowed block still hides the default core"
);
assert!(vertices.iter().all(|v| v.uv[0] >= 0.5));
}
}
}
+9 -3
View File
@@ -253,14 +253,20 @@ impl StateModels {
&self,
state: BlockStateId,
position: BlockPos,
) -> Result<Vec<(&Variant, &BakedModel)>> {
// Blocks use their position seed; contained/displayed blocks can supply one.
self.collect_seeded(state, position_seed(position))
}
pub fn collect_seeded(
&self,
state: BlockStateId,
seed: i64,
) -> Result<Vec<(&Variant, &BakedModel)>> {
let (choice, selected) = self
.states
.get(&state)
.ok_or("unbound gallery block state")?;
// These inspection blocks use Block's default position seed. Blocks with
// specialized model seeds (e.g. two-block structures) need their callbacks.
let mut random = LegacyRandom::new(position_seed(position));
let mut random = LegacyRandom::new(seed);
let mut variants = Vec::new();
self.choices[*choice].collect(selected, &mut random, &mut variants)?;
variants
+13 -11
View File
@@ -2140,6 +2140,18 @@ pub struct Level {
pub player_extra: Option<Tag>,
}
impl Level {
/// Initialize the offline single-player identity before saving or dropping items.
pub fn ensure_player_uuid(&mut self) -> [i32; 4] {
*self.player_uuid.get_or_insert_with(|| {
let u = horizon_protocol::crypto::offline_uuid("Player");
[
(u >> 96) as u32 as i32,
(u >> 64) as u32 as i32,
(u >> 32) as u32 as i32,
u as u32 as i32,
]
})
}
pub fn game_rule(&self, name: &str) -> i32 {
self.game_rules
.get(name)
@@ -2597,17 +2609,7 @@ impl Level {
map.remove(&JavaString::from(key));
}
}
// A new world's player has the offline profile id of its name
// (UUIDUtil.createOfflinePlayerUUID), as in an offline single-player game.
let uuid = *self.player_uuid.get_or_insert_with(|| {
let u = horizon_protocol::crypto::offline_uuid("Player");
[
(u >> 96) as u32 as i32,
(u >> 64) as u32 as i32,
(u >> 32) as u32 as i32,
u as u32 as i32,
]
});
let uuid = self.ensure_player_uuid();
// A new world's first spawn point is its world spawn.
if self.world_spawn.is_none() {
self.world_spawn = self.spawn.map(|s| {