From 9967697de235633da0e652043aa3efdba0e0f8c3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:35:52 +0200 Subject: [PATCH 01/16] Add sculk sensor, shrieker and catalyst block behaviour Sculk sensors cycle through active, cooldown and inactive (30 ticks, 10 for the calibrated one), power the block below them and click; the shrieker ends its 90 tick shriek and asks to respond; the catalyst blooms for 8 ticks. The level SculkSpreader moves charge cursors across sculk, veins and plain blocks, growing sensors and shriekers, merging cursors and reporting charge particles. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-world/src/level/data.rs | 7 + crates/horizon-world/src/level/mod.rs | 1 + crates/horizon-world/src/level/sculk.rs | 870 ++++++++++++++++++++++++ crates/horizon-world/src/level/tests.rs | 135 ++++ crates/horizon-world/src/level/tick.rs | 3 + 5 files changed, 1016 insertions(+) create mode 100644 crates/horizon-world/src/level/sculk.rs diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 73efe9158..bd8a0fe18 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -355,6 +355,11 @@ named_blocks! { campfire = "campfire", light = "light", sculk_sensor = "sculk_sensor", + calibrated_sculk_sensor = "calibrated_sculk_sensor", + sculk_shrieker = "sculk_shrieker", + sculk_catalyst = "sculk_catalyst", + sculk = "sculk", + sculk_vein = "sculk_vein", lectern = "lectern", target = "target", daylight_detector = "daylight_detector", @@ -561,6 +566,8 @@ props! { side_chain = "side_chain", copper_golem_pose = "copper_golem_pose", sculk_sensor_phase = "sculk_sensor_phase", + shrieking = "shrieking", + can_summon = "can_summon", potent_sulfur_state = "potent_sulfur_state", } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 1a066cafc..b8fc50f60 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -112,6 +112,7 @@ mod place; mod query; mod rails; mod redstone; +pub mod sculk; mod shapes; mod signals; mod speleothem; diff --git a/crates/horizon-world/src/level/sculk.rs b/crates/horizon-world/src/level/sculk.rs new file mode 100644 index 000000000..a831f2151 --- /dev/null +++ b/crates/horizon-world/src/level/sculk.rs @@ -0,0 +1,870 @@ +//! Sculk: the sensor's phases, the shrieker and catalyst blocks, and the +//! level `SculkSpreader` with the sculk, sculk vein and default charge-cursor +//! behaviours (`SculkBlock`, `SculkVeinBlock`, `SculkBehaviour`). +use super::{ + Behaviours, LevelAccess, LevelEvent, Sim, Ticks, + classes::Class, + update::{above, below, rel}, +}; +use crate::{fluid::FluidState, registry::BlockStateId}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; + +/// `SculkSensorBlock.ACTIVE_TICKS` (calibrated sensors use 10). +pub const SENSOR_ACTIVE_TICKS: i32 = 30; +pub const CALIBRATED_ACTIVE_TICKS: i32 = 10; +/// `SculkSensorBlock.COOLDOWN_TICKS`. +pub const SENSOR_COOLDOWN_TICKS: i32 = 10; +/// `SculkShriekerBlockEntity` shrieking time. +pub const SHRIEKING_TICKS: i32 = 90; +/// `SculkCatalystBlockEntity.CatalystListener.PULSE_TICKS`. +pub const PULSE_TICKS: i32 = 8; + +// SculkSpreader.createLevelSpreader. +const GROWTH_SPAWN_COST: i32 = 10; +const NO_GROWTH_RADIUS: i32 = 4; +const CHARGE_DECAY_RATE: i32 = 10; +const ADDITIONAL_DECAY_RATE: i32 = 5; +const MAX_CURSORS: usize = 32; +const MAX_CHARGE: i32 = 1000; +const MAX_CURSOR_DISTANCE: i32 = 1024; + +/// One `SculkSpreader.ChargeCursor`. +#[derive(Clone, Debug, PartialEq)] +pub struct ChargeCursor { + pub pos: BlockPos, + pub charge: i32, + pub update_delay: i32, + pub decay_delay: i32, + /// The faces of the block the cursor last moved onto, if any. + pub facings: Option>, +} +impl ChargeCursor { + pub fn new(pos: BlockPos, charge: i32) -> Self { + Self { + pos, + charge, + update_delay: 0, + decay_delay: 1, + facings: None, + } + } +} +/// A catalyst's `SculkSpreader` (the level configuration). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SculkSpreader { + pub cursors: Vec, +} +impl SculkSpreader { + /// `addCursors`: charge in chunks of at most 1000, at most 32 cursors. + pub fn add_cursors(&mut self, start: BlockPos, mut charge: i32) { + while charge > 0 { + let current = charge.min(MAX_CHARGE); + self.add_cursor(ChargeCursor::new(start, current)); + charge -= current; + } + } + pub fn add_cursor(&mut self, cursor: ChargeCursor) { + if self.cursors.len() < MAX_CURSORS { + self.cursors.push(cursor); + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Behaviour { + Default, + Sculk, + Vein, +} +#[derive(Clone, Copy)] +enum Spread { + SamePosition, + SamePlane, + WrapAround, +} +const ALL_SPREADS: [Spread; 3] = [Spread::SamePosition, Spread::SamePlane, Spread::WrapAround]; + +/// `MultifaceBlock.pack`: the faces as bits of their ordinals. +pub fn pack_faces(faces: &[Direction]) -> i32 { + faces.iter().fold(0, |code, d| code | 1 << *d as i32) +} +/// `MultifaceBlock.unpack`. +pub fn unpack_faces(data: i32) -> Vec { + Direction::ALL + .into_iter() + .filter(|d| data & (1 << *d as i32) != 0) + .collect() +} + +impl Sim<'_, L> { + fn sculk_rand(&mut self, bound: i32) -> i32 { + self.random().next_int_bound(bound).unwrap_or(0) + } + fn sculk_in_tag(&self, state: BlockStateId, tag: &str) -> bool { + self.b.tag(tag).is_some_and(|set| self.b.in_set(state, set)) + } + fn sculk_sound(&mut self, pos: BlockPos, sound: &str, volume: f32, pitch: f32) { + self.emit(LevelEvent::Sound { + pos, + sound: sound.into(), + volume, + pitch, + }); + } + + // ---- sensors ---- + + /// `SculkSensorBlock.canActivate`. + pub(crate) fn sensor_phase(&self, state: BlockStateId) -> &'static str { + match self.b.table.text(state, self.b.props.sculk_sensor_phase) { + "active" => "active", + "cooldown" => "cooldown", + _ => "inactive", + } + } + fn sensor_update_neighbours(&mut self, pos: BlockPos, state: BlockStateId) { + let block = self.b.block(state); + self.update_neighbors_at(pos, block); + self.update_neighbors_at(below(pos), block); + } + /// `SculkSensorBlock.tick`. + pub(crate) fn sculk_sensor_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + match self.sensor_phase(state) { + "active" => self.sculk_sensor_deactivate(pos, state), + "cooldown" => { + let next = b + .table + .set_text(state, b.props.sculk_sensor_phase, "inactive"); + self.set_block_and_update(pos, next); + if !b.table.bool(state, b.props.waterlogged) { + let pitch = self.random().next_float() * 0.2 + 0.8; + self.sculk_sound( + pos, + "minecraft:block.sculk_sensor.clicking_stop", + 1.0, + pitch, + ); + } + } + _ => {} + } + } + /// `SculkSensorBlock.deactivate`. + pub(crate) fn sculk_sensor_deactivate(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let next = b.table.set_int( + b.table + .set_text(state, b.props.sculk_sensor_phase, "cooldown"), + b.props.power, + 0, + ); + self.set_block_and_update(pos, next); + let block = b.block(state); + self.schedule_tick(pos, block, SENSOR_COOLDOWN_TICKS); + self.sensor_update_neighbours(pos, state); + } + /// `SculkSensorBlock.activate` without the resonance and the tendril + /// event, which need the source entity. + pub(crate) fn sculk_sensor_activate( + &mut self, + pos: BlockPos, + state: BlockStateId, + power: i32, + active_ticks: i32, + ) { + let b = self.b; + let next = b.table.set_int( + b.table + .set_text(state, b.props.sculk_sensor_phase, "active"), + b.props.power, + power, + ); + self.set_block_and_update(pos, next); + let block = b.block(state); + self.schedule_tick(pos, block, active_ticks); + self.sensor_update_neighbours(pos, state); + } + /// The activation sound, played after the tendril event. + pub(crate) fn sculk_sensor_click(&mut self, pos: BlockPos, state: BlockStateId) { + if !self.b.table.bool(state, self.b.props.waterlogged) { + let pitch = self.random().next_float() * 0.2 + 0.8; + self.sculk_sound(pos, "minecraft:block.sculk_sensor.clicking", 1.0, pitch); + } + } + + // ---- shrieker and catalyst ---- + + /// `SculkShriekerBlock.tick`: the shriek ends and the block responds. + pub(crate) fn sculk_shrieker_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.bool(state, b.props.shrieking) { + let next = b.table.set_bool(state, b.props.shrieking, false); + self.set_block_and_update(pos, next); + self.emit(LevelEvent::BlockEvent { + pos, + state: next, + kind: "shrieker_respond", + }); + } + } + /// `SculkCatalystBlock.tick`. + pub(crate) fn sculk_catalyst_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.bool(state, b.props.bloom) { + let next = b.table.set_bool(state, b.props.bloom, false); + self.set_block_and_update(pos, next); + } + } + + // ---- the spreader ---- + + fn sculk_behaviour(&self, state: BlockStateId) -> Behaviour { + let block = self.b.block(state); + if block == self.b.named.sculk { + Behaviour::Sculk + } else if block == self.b.named.sculk_vein { + Behaviour::Vein + } else { + Behaviour::Default + } + } + fn is_vein(&self, state: BlockStateId) -> bool { + self.b.block(state) == self.b.named.sculk_vein + } + fn vein_has_face(&self, state: BlockStateId, face: Direction) -> bool { + self.is_vein(state) && self.multiface_has_face(state, face) + } + fn vein_with_face(&self, state: BlockStateId, face: Direction, value: bool) -> BlockStateId { + self.b + .table + .set_bool(state, self.direction_prop(face), value) + } + fn available_faces(&self, state: BlockStateId) -> Vec { + if !self.b.instance_of(state, Class::Multiface) { + return Vec::new(); + } + Direction::ALL + .into_iter() + .filter(|d| self.multiface_has_face(state, *d)) + .collect() + } + fn is_sculk_source(&self, state: BlockStateId) -> bool { + self.sculk_behaviour(state) != Behaviour::Default + } + + /// `SculkSpreader.updateCursors`. + pub(crate) fn sculk_update_cursors( + &mut self, + spreader: &mut SculkSpreader, + origin: BlockPos, + spread_veins: bool, + ) { + if spreader.cursors.is_empty() { + return; + } + let cursors = std::mem::take(&mut spreader.cursors); + let mut processed: Vec = Vec::new(); + // The cursor each position merges into (index into `processed`). + let mut mergeable: Vec<(BlockPos, usize)> = Vec::new(); + let mut charge_map: Vec<(BlockPos, i32)> = Vec::new(); + for mut cursor in cursors { + let distance = (cursor.pos.x.wrapping_sub(origin.x).wrapping_abs()) + .max(cursor.pos.y.wrapping_sub(origin.y).wrapping_abs()) + .max(cursor.pos.z.wrapping_sub(origin.z).wrapping_abs()); + if distance > MAX_CURSOR_DISTANCE { + continue; + } + self.sculk_cursor_update(&mut cursor, origin, spread_veins); + if cursor.charge <= 0 { + self.level_event(3006, cursor.pos, 0); + continue; + } + let pos = cursor.pos; + match charge_map.iter_mut().find(|(p, _)| *p == pos) { + Some(entry) => entry.1 += cursor.charge, + None => charge_map.push((pos, cursor.charge)), + } + match mergeable.iter().position(|(p, _)| *p == pos) { + None => { + mergeable.push((pos, processed.len())); + processed.push(cursor); + } + Some(slot) => { + let index = mergeable[slot].1; + if cursor.charge + processed[index].charge <= MAX_CHARGE { + // mergeWith + processed[index].charge += cursor.charge; + processed[index].update_delay = + processed[index].update_delay.min(cursor.update_delay); + } else { + let smaller = cursor.charge < processed[index].charge; + processed.push(cursor); + if smaller { + mergeable[slot].1 = processed.len() - 1; + } + } + } + } + } + for (pos, charge) in charge_map { + let faces = mergeable + .iter() + .find(|(p, _)| *p == pos) + .and_then(|(_, i)| processed[*i].facings.clone()); + if charge > 0 + && let Some(faces) = faces + { + let particles = ((f64::from(charge) + 1.0).ln() as f32 / 2.3) as i32 + 1; + let data = (particles << 6) + pack_faces(&faces); + self.level_event(3006, pos, data); + } + } + spreader.cursors = processed; + } + + /// `ChargeCursor.update`. + fn sculk_cursor_update(&mut self, cursor: &mut ChargeCursor, origin: BlockPos, veins: bool) { + // shouldUpdate: charge left and the origin's chunk is ticking. + if cursor.charge <= 0 || !self.level.is_ticking_chunk(origin.chunk()) { + return; + } + if cursor.update_delay > 0 { + cursor.update_delay -= 1; + return; + } + let mut state = self.state(cursor.pos); + let mut behaviour = self.sculk_behaviour(state); + if veins && self.sculk_attempt_spread_vein(behaviour, cursor.pos, state, &cursor.facings) { + // SculkBlock.canChangeBlockStateOnSpread is false. + if behaviour != Behaviour::Sculk { + state = self.state(cursor.pos); + behaviour = self.sculk_behaviour(state); + } + self.sculk_sound(cursor.pos, "minecraft:block.sculk.spread", 1.0, 1.0); + } + cursor.charge = self.sculk_attempt_use_charge(behaviour, cursor, origin, veins); + if cursor.charge <= 0 { + self.sculk_on_discharged(behaviour, state, cursor.pos); + return; + } + let transfer = self.sculk_valid_movement(cursor.pos); + if let Some(target) = transfer { + self.sculk_on_discharged(behaviour, state, cursor.pos); + cursor.pos = target; + state = self.state(target); + } + if self.is_sculk_source(state) { + cursor.facings = Some(self.available_faces(state)); + } + cursor.decay_delay = match behaviour { + Behaviour::Default => (cursor.decay_delay - 1).max(0), + _ => 1, + }; + cursor.update_delay = 1; + } + + /// `SculkBehaviour.attemptSpreadVein` (the default behaviour's override + /// regrows veins or spreads in the same space). + fn sculk_attempt_spread_vein( + &mut self, + behaviour: Behaviour, + pos: BlockPos, + state: BlockStateId, + facings: &Option>, + ) -> bool { + if behaviour == Behaviour::Default { + match facings { + None => { + let current = self.state(pos); + return self.sculk_spread_all(current, pos, &[Spread::SamePosition]) > 0; + } + Some(faces) if !faces.is_empty() => { + let b = self.b; + let water = b.is_block(state, b.named.water) && b.fluid(state).is_source(); + if !b.is_air(state) && !water { + return false; + } + return self.sculk_regrow(pos, state, faces); + } + Some(_) => {} + } + } + self.sculk_spread_all(state, pos, &ALL_SPREADS) > 0 + } + /// `SculkVeinBlock.regrow`. + fn sculk_regrow(&mut self, pos: BlockPos, existing: BlockStateId, faces: &[Direction]) -> bool { + let b = self.b; + let mut state = b.default_of(b.named.sculk_vein); + let mut any = false; + for &face in faces { + if b.multiface_can_attach(self.state(rel(pos, face)), face) { + state = self.vein_with_face(state, face, true); + any = true; + } + } + if !any { + return false; + } + if b.fluid(existing) != FluidState::EMPTY { + state = b.table.set_bool(state, b.props.waterlogged, true); + } + self.set_block_and_update(pos, state); + true + } + /// `MultifaceSpreader.spreadAll` with the sculk vein configuration. + fn sculk_spread_all(&mut self, state: BlockStateId, pos: BlockPos, types: &[Spread]) -> i64 { + let other_source = !self.is_vein(state); + let mut count = 0; + for face in Direction::ALL { + if !(other_source || self.vein_has_face(state, face)) { + continue; + } + for direction in Direction::ALL { + if crate::level::query::axis_of(direction) == crate::level::query::axis_of(face) { + continue; + } + if !(other_source + || (self.vein_has_face(state, face) && !self.vein_has_face(state, direction))) + { + continue; + } + let mut target = None; + for kind in types { + let candidate = match kind { + Spread::SamePosition => (pos, direction), + Spread::SamePlane => (rel(pos, direction), face), + Spread::WrapAround => { + (rel(rel(pos, direction), face), direction.opposite()) + } + }; + if self.sculk_can_spread_into(pos, candidate.0, candidate.1) { + target = Some(candidate); + break; + } + } + let Some((target, face_to)) = target else { + continue; + }; + let old = self.state(target); + let Some(new) = self.sculk_state_for_placement(old, target, face_to) else { + continue; + }; + if self.set_block(target, new, 2) { + count += 1; + } + } + } + count + } + fn sculk_valid_for_placement(&self, old: BlockStateId, pos: BlockPos, face: Direction) -> bool { + if self.vein_has_face(old, face) { + return false; + } + self.b + .multiface_can_attach(self.state(rel(pos, face)), face) + } + /// `MultifaceBlock.getStateForPlacement` for the sculk vein. + fn sculk_state_for_placement( + &self, + old: BlockStateId, + pos: BlockPos, + face: Direction, + ) -> Option { + if !self.sculk_valid_for_placement(old, pos, face) { + return None; + } + let b = self.b; + let base = if self.is_vein(old) { + old + } else if b.fluid(old) == FluidState::WATER { + b.table + .set_bool(b.default_of(b.named.sculk_vein), b.props.waterlogged, true) + } else { + b.default_of(b.named.sculk_vein) + }; + Some(self.vein_with_face(base, face, true)) + } + /// `SculkVeinSpreaderConfig.canSpreadInto` (with the default config). + fn sculk_can_spread_into(&self, source: BlockPos, target: BlockPos, face: Direction) -> bool { + let b = self.b; + let existing = self.state(target); + let against = self.state(rel(target, face)); + let against_block = b.block(against); + if against_block == b.named.sculk + || against_block == b.named.sculk_catalyst + || against_block == b.named.moving_piston + { + return false; + } + let manhattan = + (source.x - target.x).abs() + (source.y - target.y).abs() + (source.z - target.z).abs(); + if manhattan == 2 { + let neighbour = rel(source, face.opposite()); + if b.is_face_sturdy(self.state(neighbour), face) { + return false; + } + } + let fluid = b.fluid(existing); + if fluid != FluidState::EMPTY && !(b.is_block(existing, b.named.water) && fluid.is_source()) + { + return false; + } + if self.sculk_in_tag(existing, "minecraft:fire") { + return false; + } + let replaceable = b.is_replaceable(existing) + || b.is_air(existing) + || self.is_vein(existing) + || (b.is_block(existing, b.named.water) && fluid.is_source()); + replaceable && self.sculk_valid_for_placement(existing, target, face) + } + + /// `SculkBehaviour.attemptUseCharge` per behaviour. + fn sculk_attempt_use_charge( + &mut self, + behaviour: Behaviour, + cursor: &ChargeCursor, + origin: BlockPos, + veins: bool, + ) -> i32 { + let charge = cursor.charge; + match behaviour { + Behaviour::Default => { + if cursor.decay_delay > 0 { + charge + } else { + 0 + } + } + Behaviour::Vein => { + if veins && self.sculk_place_sculk(cursor.pos) { + charge - 1 + } else if self.sculk_rand(CHARGE_DECAY_RATE) == 0 { + (charge as f32 * 0.5).floor() as i32 + } else { + charge + } + } + Behaviour::Sculk => { + if charge == 0 || self.sculk_rand(CHARGE_DECAY_RATE) != 0 { + return charge; + } + let pos = cursor.pos; + let dist_sqr = f64::from( + (pos.x - origin.x).pow(2) + + (pos.y - origin.y).pow(2) + + (pos.z - origin.z).pow(2), + ); + let close = dist_sqr < f64::from(NO_GROWTH_RADIUS * NO_GROWTH_RADIUS); + if !close && self.sculk_can_place_growth(pos) { + if self.sculk_rand(GROWTH_SPAWN_COST) < charge { + let growth_pos = above(pos); + let growth = self.sculk_random_growth(growth_pos); + self.set_block_and_update(growth_pos, growth); + let sounds = self.b.data(growth).sounds.clone(); + self.emit(LevelEvent::Sound { + pos, + sound: sounds.place.clone(), + volume: 1.0, + pitch: 1.0, + }); + } + return (charge - GROWTH_SPAWN_COST).max(0); + } + if self.sculk_rand(ADDITIONAL_DECAY_RATE) != 0 { + return charge; + } + let penalty = if close { + 1 + } else { + // getDecayPenalty + let outer = (dist_sqr.sqrt() as f32 - NO_GROWTH_RADIUS as f32).powi(2); + let reach = (24 - NO_GROWTH_RADIUS) * (24 - NO_GROWTH_RADIUS); + let factor = 1.0f32.min(outer / reach as f32); + 1.max((charge as f32 * factor * 0.5) as i32) + }; + charge - penalty + } + } + } + /// `SculkBlock.getRandomGrowthState` (not for world generation). + fn sculk_random_growth(&mut self, pos: BlockPos) -> BlockStateId { + let b = self.b; + let state = if self.sculk_rand(11) == 0 { + b.default_of(b.named.sculk_shrieker) + } else { + b.default_of(b.named.sculk_sensor) + }; + if self.fluid_at(pos) != FluidState::EMPTY { + b.table.set_bool(state, b.props.waterlogged, true) + } else { + state + } + } + /// `SculkBlock.canPlaceGrowth`. + fn sculk_can_place_growth(&self, pos: BlockPos) -> bool { + let b = self.b; + let state_above = self.state(above(pos)); + let open = b.is_air(state_above) + || (b.is_block(state_above, b.named.water) && b.fluid(state_above).is_source()); + if !open { + return false; + } + let mut matched = 0; + for dz in -4..=4 { + for dy in 0..=2 { + for dx in -4..=4 { + let state = self.state(pos.offset(dx, dy, dz)); + if self.sculk_in_tag(state, "minecraft:sculk_growth_inhibitors") { + matched += 1; + if matched >= 3 { + return false; + } + } + } + } + } + true + } + /// `SculkVeinBlock.attemptPlaceSculk`. + fn sculk_place_sculk(&mut self, pos: BlockPos) -> bool { + let state = self.state(pos); + let mut directions = Direction::ALL; + for i in (2..=directions.len()).rev() { + let swap = self.sculk_rand(i as i32) as usize; + directions.swap(i - 1, swap); + } + for support in directions { + if !self.vein_has_face(state, support) { + continue; + } + let support_pos = rel(pos, support); + let support_state = self.state(support_pos); + if !self.sculk_in_tag(support_state, "minecraft:sculk_replaceable") { + continue; + } + let default_sculk = self.b.default_of(self.b.named.sculk); + self.set_block_and_update(support_pos, default_sculk); + self.sculk_sound(support_pos, "minecraft:block.sculk.spread", 1.0, 1.0); + self.sculk_spread_all(default_sculk, support_pos, &ALL_SPREADS); + let skip = support.opposite(); + for direction in Direction::ALL { + if direction == skip { + continue; + } + let vein_pos = rel(support_pos, direction); + let possible = self.state(vein_pos); + if self.is_vein(possible) { + self.sculk_on_discharged(Behaviour::Vein, possible, vein_pos); + } + } + return true; + } + false + } + /// `SculkVeinBlock.onDischarged`. + fn sculk_on_discharged(&mut self, behaviour: Behaviour, state: BlockStateId, pos: BlockPos) { + if behaviour != Behaviour::Vein || !self.is_vein(state) { + return; + } + let b = self.b; + let mut state = state; + for direction in Direction::ALL { + if self.multiface_has_face(state, direction) + && b.is_block(self.state(rel(pos, direction)), b.named.sculk) + { + state = self.vein_with_face(state, direction, false); + } + } + if !Direction::ALL + .into_iter() + .any(|d| self.multiface_has_face(state, d)) + { + state = if self.fluid_at(pos) == FluidState::EMPTY { + b.default_of(b.named.air) + } else { + b.default_of(b.named.water) + }; + } + self.set_block_and_update(pos, state); + } + /// `ChargeCursor.getValidMovementPos`. + fn sculk_valid_movement(&mut self, pos: BlockPos) -> Option { + let mut offsets = Vec::with_capacity(18); + for z in -1..=1 { + for y in -1..=1 { + for x in -1..=1 { + if (x == 0 || y == 0 || z == 0) && (x, y, z) != (0, 0, 0) { + offsets.push([x, y, z]); + } + } + } + } + for i in (2..=offsets.len()).rev() { + let swap = self.sculk_rand(i as i32) as usize; + offsets.swap(i - 1, swap); + } + let b = self.b; + let mut best = pos; + for o in offsets { + let neighbour = pos.offset(o[0], o[1], o[2]); + let transferee = self.state(neighbour); + if self.sculk_behaviour(transferee) == Behaviour::Default + || !self.sculk_unobstructed_move(pos, neighbour) + { + continue; + } + best = neighbour; + // SculkVeinBlock.hasSubstrateAccess + if self.is_vein(transferee) + && Direction::ALL.into_iter().any(|d| { + self.multiface_has_face(transferee, d) + && self.sculk_in_tag( + self.state(rel(neighbour, d)), + "minecraft:sculk_replaceable", + ) + }) + { + break; + } + } + let _ = b; + (best != pos).then_some(best) + } + fn sculk_unobstructed_move(&self, from: BlockPos, to: BlockPos) -> bool { + let manhattan = (from.x - to.x).abs() + (from.y - to.y).abs() + (from.z - to.z).abs(); + if manhattan == 1 { + return true; + } + let delta = [to.x - from.x, to.y - from.y, to.z - from.z]; + let dir_x = if delta[0] < 0 { + Direction::West + } else { + Direction::East + }; + let dir_y = if delta[1] < 0 { + Direction::Down + } else { + Direction::Up + }; + let dir_z = if delta[2] < 0 { + Direction::North + } else { + Direction::South + }; + let (a, c) = if delta[0] == 0 { + (dir_y, dir_z) + } else if delta[1] == 0 { + (dir_x, dir_z) + } else { + (dir_x, dir_y) + }; + let free = |direction: Direction| { + let test = rel(from, direction); + !self + .b + .is_face_sturdy(self.state(test), direction.opposite()) + }; + free(a) || free(c) + } +} + +impl Behaviours { + /// `SculkSensorBlock.canActivate`: the sensor is inactive. + pub fn sculk_sensor_can_activate(&self, state: BlockStateId) -> bool { + self.table.text(state, self.props.sculk_sensor_phase) == "inactive" + } + /// The sensor's phase (`inactive`, `active` or `cooldown`). + pub fn sculk_sensor_active(&self, state: BlockStateId) -> bool { + self.table.text(state, self.props.sculk_sensor_phase) == "active" + } + /// `SculkSensorBlock.activate` (the state, its ticks and the redstone + /// update); the caller sends the tendril and resonance events. + pub fn sculk_sensor_activate( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + power: i32, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + let active_ticks = if self.block(state) == self.named.calibrated_sculk_sensor { + CALIBRATED_ACTIVE_TICKS + } else { + SENSOR_ACTIVE_TICKS + }; + sim.sculk_sensor_activate(pos, state, power, active_ticks); + } + /// The click sound after an activation. + pub fn sculk_sensor_click( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + sim.sculk_sensor_click(pos, state); + } + /// `CalibratedSculkSensorBlockEntity.VibrationUser.getBackSignal`. + pub fn calibrated_back_signal( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> i32 { + let sim = self.sim(level, ticks); + let state = sim.state(pos); + let direction = self.facing(state).opposite(); + sim.signal(rel(pos, direction), direction) + } + /// `SculkCatalystBlockEntity.CatalystListener.bloom`'s block half. + pub fn sculk_catalyst_bloom( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + if self.block(state) != self.named.sculk_catalyst { + return; + } + let next = self.table.set_bool(state, self.props.bloom, true); + sim.set_block_and_update(pos, next); + let block = self.block(state); + sim.schedule_tick(pos, block, PULSE_TICKS); + } + /// `SculkShriekerBlockEntity.shriek`'s block half: `shrieking` for 90 ticks. + pub fn sculk_shrieker_shriek( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + if self.block(state) != self.named.sculk_shrieker { + return; + } + let next = self.table.set_bool(state, self.props.shrieking, true); + sim.set_block(pos, next, 2); + let block = self.block(state); + sim.schedule_tick(pos, block, SHRIEKING_TICKS); + sim.level_event(3007, pos, 0); + } + /// `SculkSpreader.updateCursors` for a catalyst at `origin`. + pub fn sculk_update_cursors( + &self, + level: &mut L, + ticks: &mut Ticks, + spreader: &mut SculkSpreader, + origin: BlockPos, + spread_veins: bool, + ) { + self.sim(level, ticks) + .sculk_update_cursors(spreader, origin, spread_veins); + } +} diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index c1ffce5a1..74534e46f 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -917,3 +917,138 @@ fn dripstone_fills_cauldrons() { } assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]"); } + +#[test] +fn sculk_sensor_phases_and_signal() { + let mut w = world!(); + w.floor(0, 6, "stone"); + let pos = BlockPos::new(0, 1, 0); + let sensor = w.id("sculk_sensor", &[]); + w.set(pos, sensor); + assert!(w.b().sculk_sensor_can_activate(w.get(pos))); + w.f.behaviours + .sculk_sensor_activate(&mut w.level, &mut w.ticks, pos, 11); + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active"); + assert_eq!(w.prop(pos, "power"), "11"); + // The sensor powers the block below it from the top. + let below = BlockPos::new(0, 0, 0); + assert_eq!( + w.f.behaviours + .best_neighbor_signal(&mut w.level, &mut w.ticks, below), + 11, + "the block under an active sensor receives its power" + ); + for _ in 0..29 { + w.tick(); + } + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active"); + w.tick(); + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "cooldown"); + assert_eq!(w.prop(pos, "power"), "0"); + for _ in 0..10 { + w.tick(); + } + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "inactive"); +} + +#[test] +fn calibrated_sensor_is_active_for_ten_ticks() { + let mut w = world!(); + w.floor(0, 6, "stone"); + let pos = BlockPos::new(0, 1, 0); + let sensor = w.id("calibrated_sculk_sensor", &[("facing", "north")]); + w.set(pos, sensor); + w.f.behaviours + .sculk_sensor_activate(&mut w.level, &mut w.ticks, pos, 4); + for _ in 0..9 { + w.tick(); + } + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active"); + w.tick(); + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "cooldown"); + // The block behind (south) feeds the calibration signal. + let source = w.id("redstone_block", &[]); + w.set(BlockPos::new(0, 1, 1), source); + assert_eq!( + w.f.behaviours + .calibrated_back_signal(&mut w.level, &mut w.ticks, pos), + 15 + ); +} + +#[test] +fn sculk_charge_spreads_veins_and_sculk() { + let mut w = world!(); + w.floor(0, 12, "stone"); + w.floor(-1, 12, "stone"); + let origin = BlockPos::new(0, 1, 0); + let catalyst = w.id("sculk_catalyst", &[]); + w.put(origin, catalyst); + let mut spreader = sculk::SculkSpreader::default(); + spreader.add_cursors(BlockPos::new(2, 1, 0), 40); + assert_eq!(spreader.cursors.len(), 1); + for _ in 0..80 { + w.f.behaviours.sculk_update_cursors( + &mut w.level, + &mut w.ticks, + &mut spreader, + origin, + true, + ); + } + let sculk = w.id("sculk", &[]); + let found = (-12..=12) + .flat_map(|x| (-12..=12).map(move |z| BlockPos::new(x, 0, z))) + .filter(|p| w.get(*p) == sculk) + .count(); + assert!(found > 0, "the charge turned stone into sculk"); + assert!( + w.level + .events + .iter() + .any(|e| matches!(e, LevelEvent::LevelEvent { id: 3006, .. })), + "charge particles are reported" + ); +} + +#[test] +fn shrieker_responds_when_the_shriek_ends() { + let mut w = world!(); + w.floor(0, 6, "stone"); + let pos = BlockPos::new(0, 1, 0); + let shrieker = w.id("sculk_shrieker", &[("can_summon", "true")]); + w.set(pos, shrieker); + w.f.behaviours + .sculk_shrieker_shriek(&mut w.level, &mut w.ticks, pos); + assert_eq!(w.prop(pos, "shrieking"), "true"); + for _ in 0..89 { + w.tick(); + } + assert_eq!(w.prop(pos, "shrieking"), "true"); + w.tick(); + assert_eq!(w.prop(pos, "shrieking"), "false"); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::BlockEvent { + kind: "shrieker_respond", + .. + } + ))); +} + +#[test] +fn catalyst_bloom_lasts_eight_ticks() { + let mut w = world!(); + let pos = BlockPos::new(0, 1, 0); + let catalyst = w.id("sculk_catalyst", &[]); + w.set(pos, catalyst); + w.f.behaviours + .sculk_catalyst_bloom(&mut w.level, &mut w.ticks, pos); + assert_eq!(w.prop(pos, "bloom"), "true"); + for _ in 0..7 { + w.tick(); + } + assert_eq!(w.prop(pos, "bloom"), "true"); + w.tick(); + assert_eq!(w.prop(pos, "bloom"), "false"); +} diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 0723af984..917a96bc9 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -150,6 +150,9 @@ impl Sim<'_, L> { Class::RedstoneLamp => self.lamp_tick(pos, state), Class::RedstoneTorch => self.torch_tick(pos, state), Class::Scaffolding => self.scaffolding_tick(pos, state), + Class::SculkSensor => self.sculk_sensor_tick(pos, state), + Class::SculkShrieker => self.sculk_shrieker_tick(pos, state), + Class::SculkCatalyst => self.sculk_catalyst_tick(pos, state), Class::Speleothem => { let tip = b.table.dir(state, p.vertical_direction); if tip == Some(Direction::Up) && !self.can_survive(state, pos) { From 19336564d2bd782186b62674d55c04d343835cf0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:40:31 +0200 Subject: [PATCH 02/16] Add the loom and banner patterns The loom now opens its menu: a banner, a dye and an optional pattern item go in, the 32 plain patterns (or the one the pattern item provides) show in a scrolling 4x4 grid with hover names, picking one previews the result banner and the result slot gives a banner with one more layer, using up one banner and one dye. Banners with six layers show the error state and give nothing. Shift-click routes banners, dyes and pattern items to the right slots. Banner layers are stored in the banner_patterns item component, in a new banner block entity (saved to chunks), and carry over when a banner is placed or dropped. Placed banners draw all their pattern layers, banner and shield icons are drawn as the vanilla 3D models with their patterns, a held banner is shown in the first-person hand, and tooltips list the layers. Banner duplication and shield decoration crafting recipes work, and crafting now returns item remainders such as buckets. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/banner.rs | 313 +++++++++++++ .../horizon-client/src/block_entity_render.rs | 17 +- crates/horizon-client/src/containers.rs | 24 +- crates/horizon-client/src/crafting.rs | 197 +++++++++ crates/horizon-client/src/game.rs | 54 ++- crates/horizon-client/src/game/banners.rs | 222 ++++++++++ crates/horizon-client/src/game/loom.rs | 415 ++++++++++++++++++ crates/horizon-client/src/game/minecarts.rs | 1 + crates/horizon-client/src/game/shield.rs | 76 +++- crates/horizon-client/src/game/stations.rs | 50 ++- crates/horizon-client/src/game/storage.rs | 4 + crates/horizon-client/src/item_data.rs | 33 ++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/save.rs | 41 +- crates/horizon-client/src/stations.rs | 2 + 15 files changed, 1411 insertions(+), 39 deletions(-) create mode 100644 crates/horizon-client/src/banner.rs create mode 100644 crates/horizon-client/src/game/banners.rs create mode 100644 crates/horizon-client/src/game/loom.rs diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs new file mode 100644 index 000000000..d2bc33fba --- /dev/null +++ b/crates/horizon-client/src/banner.rs @@ -0,0 +1,313 @@ +//! Banner patterns: the `banner_pattern` registry and its tags, the +//! `banner_patterns` layers carried by banner items, shields and placed +//! banners, and the loom rules of `LoomMenu` (selectable patterns, the +//! six-layer limit and the result stack). +use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path, sync::Arc}; + +/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BannerLayer { + pub pattern: Arc, + pub color: Arc, +} +impl BannerLayer { + pub fn new(pattern: &str, color: &str) -> Self { + Self { + pattern: Arc::from(pattern), + color: Arc::from(color), + } + } +} + +/// Layers a loom may stack on a banner (`LoomMenu`'s `hasMaxPatterns`). +pub const MAX_LAYERS: usize = 6; + +/// One `banner_pattern` registry entry. +#[derive(Clone, Debug)] +pub struct Pattern { + pub id: Arc, + /// `asset_id` path, the texture under `entity/banner` and `entity/shield`. + pub asset: String, + pub translation_key: String, +} + +/// The pattern registry, its tags and the item components the loom reads. +#[derive(Default)] +pub struct Banners { + patterns: Vec, + /// `#minecraft:no_item_required`, in tag order. + no_item_required: Vec>, + /// Item -> `dye` component. + dyes: HashMap, Arc>, + /// Item -> `provides_banner_patterns`, in tag order. + provided: HashMap, Vec>>, +} + +fn read_tag(root: &Path, name: &str, depth: u32) -> Vec> { + if depth > 8 { + return Vec::new(); + } + let path = root.join(format!( + "data/minecraft/tags/banner_pattern/{}.json", + name.trim_start_matches("minecraft:") + )); + let Some(v) = fs::read(path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + return Vec::new(); + }; + let mut out = Vec::new(); + for value in v["values"].as_array().into_iter().flatten() { + let Some(s) = value.as_str().or_else(|| value["id"].as_str()) else { + continue; + }; + match s.strip_prefix('#') { + Some(tag) => out.extend(read_tag(root, tag, depth + 1)), + None => out.push(Arc::from(s)), + } + } + out +} + +impl Banners { + pub fn load(root: &Path) -> Self { + let mut banners = Self::default(); + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/banner_pattern")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + files.sort(); + for path in files { + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + let Some(v) = fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + continue; + }; + let asset = v["asset_id"] + .as_str() + .unwrap_or(stem) + .trim_start_matches("minecraft:") + .to_owned(); + banners.patterns.push(Pattern { + id: Arc::from(format!("minecraft:{stem}").as_str()), + asset, + translation_key: v["translation_key"].as_str().unwrap_or_default().to_owned(), + }); + } + banners.no_item_required = read_tag(root, "no_item_required", 0); + if let Some(raw) = fs::read(root.join("items.json")).ok().and_then(|b| { + serde_json::from_slice::>(&b).ok() + }) { + for (item, c) in raw { + let id: Arc = Arc::from(item.as_str()); + if let Some(dye) = c["minecraft:dye"].as_str() { + banners.dyes.insert(id.clone(), Arc::from(dye)); + } + match &c["minecraft:provides_banner_patterns"] { + Value::String(tag) if tag.starts_with('#') => { + banners.provided.insert(id, read_tag(root, &tag[1..], 0)); + } + Value::String(single) => { + banners + .provided + .insert(id, vec![Arc::from(single.as_str())]); + } + _ => {} + } + } + } + banners + } + pub fn pattern(&self, id: &str) -> Option<&Pattern> { + self.patterns.iter().find(|p| &*p.id == id) + } + /// `Sheets.getBannerSprite` texture name of a pattern. + pub fn banner_texture(&self, id: &str) -> String { + match self.pattern(id) { + Some(p) => format!("entity/banner/{}", p.asset), + None => format!("entity/banner/{}", id.trim_start_matches("minecraft:")), + } + } + /// `Sheets.getShieldSprite` texture name of a pattern. + pub fn shield_texture(&self, id: &str) -> String { + match self.pattern(id) { + Some(p) => format!("entity/shield/{}", p.asset), + None => format!("entity/shield/{}", id.trim_start_matches("minecraft:")), + } + } + /// `BannerPatternLayers.Layer.description` translation key. + pub fn layer_key(&self, layer: &BannerLayer) -> String { + let base = self.pattern(&layer.pattern).map_or_else( + || { + format!( + "block.minecraft.banner.{}", + layer.pattern.trim_start_matches("minecraft:") + ) + }, + |p| p.translation_key.clone(), + ); + format!("{base}.{}", layer.color) + } + /// `LoomMenu.isDyeItem`: the dye colour of a loom dye. + pub fn loom_dye(&self, items: &Items, stack: &ItemStack) -> Option> { + let tagged = items + .item_tags + .get("minecraft:loom_dyes") + .is_some_and(|t| t.contains(&*stack.item)); + tagged + .then(|| self.dyes.get(&stack.item).cloned()) + .flatten() + } + /// `LoomMenu.isPatternItem`. + pub fn is_pattern_item(&self, items: &Items, stack: &ItemStack) -> bool { + items + .item_tags + .get("minecraft:loom_patterns") + .is_some_and(|t| t.contains(&*stack.item)) + && self.provided.contains_key(&stack.item) + } + /// `LoomMenu.getSelectablePatterns`. + pub fn selectable(&self, pattern_item: Option<&ItemStack>) -> Vec> { + match pattern_item { + None => self.no_item_required.clone(), + Some(stack) => self.provided.get(&stack.item).cloned().unwrap_or_default(), + } + } +} + +/// `BannerItem`: a banner's dye colour from its item id. +pub fn banner_color(item: &str) -> Option<&'static str> { + let name = item.strip_prefix("minecraft:")?.strip_suffix("_banner")?; + DYES.iter().map(|d| d.0).find(|d| *d == name) +} +/// `DyeColor.getTextureDiffuseColor` (RGB) by dye name. +pub fn dye_rgb(name: &str) -> u32 { + DYES.iter().find(|d| d.0 == name).map_or(0xFFFFFF, |d| d.1) +} +/// The layers of a banner or shield stack. +pub fn layers(stack: &ItemStack) -> &[BannerLayer] { + stack.data().map_or(&[], |d| &d.banner_patterns) +} +/// `LoomMenu.setupResultSlot`: one banner with the pattern added in the dye colour. +pub fn loom_result(banner: &ItemStack, dye: &str, pattern: &str) -> ItemStack { + let mut result = ItemStack { + count: 1, + ..banner.clone() + }; + result + .data_mut() + .banner_patterns + .push(BannerLayer::new(pattern, dye)); + result +} +/// Whether the banner already carries the loom's limit. +pub fn has_max_layers(banner: &ItemStack) -> bool { + layers(banner).len() >= MAX_LAYERS +} + +/// The `banner_patterns` NBT list of layers. +pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag { + Tag::List( + layers + .iter() + .map(|l| { + Tag::compound([ + ("pattern", Tag::String((&*l.pattern).into())), + ("color", Tag::String((&*l.color).into())), + ]) + }) + .collect(), + ) +} +pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { + let Some(Tag::List(list)) = tag else { + return Vec::new(); + }; + list.iter() + .filter_map(|e| { + let text = |k: &str| match e.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + let pattern = text("pattern")?; + let color = text("color")?; + Some(BannerLayer::new( + &if pattern.contains(':') { + pattern + } else { + format!("minecraft:{pattern}") + }, + &color, + )) + }) + .collect() +} +/// Keeps `item_data` linked: the `StackData` fields the banner code reads. +pub fn set_layers(stack: &mut ItemStack, layers: Vec) { + let data: &mut item_data::StackData = stack.data_mut(); + data.banner_patterns = layers; + stack.tidy(); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn banners() -> Banners { + let mut b = Banners { + no_item_required: vec![Arc::from("minecraft:stripe_top")], + ..Default::default() + }; + b.provided.insert( + Arc::from("minecraft:flower_banner_pattern"), + vec![Arc::from("minecraft:flower")], + ); + b + } + #[test] + fn selectable_follow_the_pattern_item() { + let b = banners(); + assert_eq!(b.selectable(None).len(), 1); + let item = ItemStack::new("minecraft:flower_banner_pattern", 1); + assert_eq!(&*b.selectable(Some(&item))[0], "minecraft:flower"); + } + #[test] + fn banner_colour_comes_from_the_item() { + assert_eq!( + banner_color("minecraft:light_gray_banner"), + Some("light_gray") + ); + assert_eq!(banner_color("minecraft:white_banner"), Some("white")); + assert_eq!(banner_color("minecraft:white_wool"), None); + } + #[test] + fn loom_adds_a_layer_up_to_the_limit() { + let mut banner = ItemStack::new("minecraft:white_banner", 3); + for i in 0..MAX_LAYERS { + assert!(!has_max_layers(&banner)); + banner = loom_result(&banner, "red", "minecraft:cross"); + assert_eq!(banner.count, 1); + assert_eq!(layers(&banner).len(), i + 1); + } + assert!(has_max_layers(&banner)); + } + #[test] + fn layers_round_trip_through_nbt() { + let l = vec![ + BannerLayer::new("minecraft:flower", "red"), + BannerLayer::new("minecraft:border", "black"), + ]; + assert_eq!(layers_from_nbt(Some(&layers_to_nbt(&l))), l); + } +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 5869f6de0..8114542b0 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -700,6 +700,8 @@ pub struct Scene<'a> { pub lid: &'a dyn Fn([i32; 3]) -> f32, /// Sign block-entity data at a position. pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>, + /// Banner layers at a position: pattern texture and RGB tint, bottom first. + pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>, /// Font glyph cell and advance. pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>, } @@ -773,6 +775,13 @@ impl BlockEntityRenderer { random: LegacyRandom::new(0x5EED_B00C), } } + /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). + pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> { + Some(( + self.models.get("standing_banner")?, + self.models.get("standing_banner_flag")?, + )) + } fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } @@ -993,10 +1002,16 @@ impl BlockEntityRenderer { draw_part(main, "root", m, &none, paint, out); draw_part(flag, "root", m, &wave, paint, out); } - // BannerRenderer.submitPatterns: the base pattern layer in the dye colour. + // BannerRenderer.submitPatterns: the base pattern layer in the dye colour, + // then up to 16 pattern layers in order. if let Some(paint) = paint("entity/banner/base", *color, packed) { draw_part(flag, "root", m, &wave, paint, out); } + for (texture, tint) in (scene.banner)(pos).iter().take(16) { + if let Some(paint) = paint(texture, *tint, packed) { + draw_part(flag, "root", m, &wave, paint, out); + } + } } Kind::Skull { kind, diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6d999c9a8..431eac25f 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -58,6 +58,13 @@ pub enum BlockEntity { Beacon(Box), /// `LecternBlockEntity`: the book and the open page. Lectern(Lectern), + /// `BannerBlockEntity`: the pattern layers. + Banner(Banner), +} +#[derive(Clone, Debug, Default)] +pub struct Banner { + pub layers: Vec, + pub name: Option, } #[derive(Clone, Debug, Default)] pub struct Lectern { @@ -104,6 +111,9 @@ impl BlockEntity { if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } + if name.ends_with("_banner") { + return Some(Self::Banner(Banner::default())); + } if name == "minecraft:beacon" { return Some(Self::Beacon(Box::new(Beacon { last_check_y: i32::MIN / 2, @@ -155,6 +165,7 @@ impl BlockEntity { Self::Jukebox(_) => "minecraft:jukebox", Self::Beacon(_) => "minecraft:beacon", Self::Lectern(_) => "minecraft:lectern", + Self::Banner(_) => "minecraft:banner", } } pub fn contents(&self) -> Vec { @@ -166,6 +177,7 @@ impl BlockEntity { Self::Jukebox(j) => j.record.iter().cloned().collect(), Self::Beacon(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), + Self::Banner(_) => Vec::new(), } } pub fn slots(&self) -> &[Option] { @@ -173,7 +185,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &f.items, Self::Brewing(b) => &b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::Banner(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -181,7 +197,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, Self::Brewing(b) => &mut b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::Banner(_) => &mut [], } } } diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index ecf8f9bd6..7994d0bd7 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -53,6 +53,96 @@ pub enum Recipe { ingredients: Vec, result: ItemStack, }, + /// `BannerDuplicateRecipe` and `ShieldDecorationRecipe`. + Special(Special), +} +/// The banner-copying custom recipes. +#[derive(Clone, Debug)] +pub enum Special { + /// A patterned banner and a blank one of the same colour copy the patterns. + BannerDuplicate { banner: Ingredient, result: String }, + /// A banner decorates an undecorated shield. + ShieldDecoration { + banner: Ingredient, + target: Ingredient, + result: String, + }, +} +impl Special { + /// `matches` + `assemble` over the non-empty stacks of the grid. + fn assemble(&self, stacks: &[&ItemStack]) -> Option { + use crate::banner; + if stacks.len() != 2 { + return None; + } + match self { + Self::BannerDuplicate { + banner: ing, + result, + } => { + let color = banner::banner_color(&stacks[0].item)?; + let mut source = None; + let mut target = false; + for s in stacks { + if !ing.test(s) || banner::banner_color(&s.item)? != color { + return None; + } + let layers = banner::layers(s).len(); + if layers > banner::MAX_LAYERS { + return None; + } + if layers > 0 { + if source.is_some() { + return None; + } + source = Some(*s); + } else { + if target { + return None; + } + target = true; + } + } + let source = source.filter(|_| target)?; + // TransmuteRecipe.createWithOriginalComponents: the source's components. + Some(ItemStack { + item: Arc::from(result.as_str()), + count: 1, + ..(*source).clone() + }) + } + Self::ShieldDecoration { + banner: ing, + target: tgt, + result, + } => { + let (mut patterned, mut clear) = (None, None); + for s in stacks { + if ing.test(s) && banner::banner_color(&s.item).is_some() { + if patterned.is_some() { + return None; + } + patterned = Some(*s); + } else { + if !tgt.test(s) || clear.is_some() || !banner::layers(s).is_empty() { + return None; + } + clear = Some(*s); + } + } + let (banner_stack, shield) = (patterned?, clear?); + let mut out = ItemStack { + item: Arc::from(result.as_str()), + count: 1, + ..shield.clone() + }; + let data = out.data_mut(); + data.banner_patterns = banner::layers(banner_stack).to_vec(); + data.base_color = banner::banner_color(&banner_stack.item).map(Arc::from); + Some(out) + } + } + } } #[derive(Clone, Debug)] pub struct Cooking { @@ -145,6 +235,36 @@ impl Recipes { )); } } + "minecraft:crafting_special_bannerduplicate" => { + if let (Some(banner), Some(id)) = ( + Ingredient::parse(&v["banner"], items), + v["result"]["id"].as_str(), + ) { + crafting.push(( + name, + Recipe::Special(Special::BannerDuplicate { + banner, + result: id.to_owned(), + }), + )); + } + } + "minecraft:crafting_special_shielddecoration" => { + if let (Some(banner), Some(target), Some(id)) = ( + Ingredient::parse(&v["banner"], items), + Ingredient::parse(&v["target"], items), + v["result"]["id"].as_str(), + ) { + crafting.push(( + name, + Recipe::Special(Special::ShieldDecoration { + banner, + target, + result: id.to_owned(), + }), + )); + } + } kind @ ("minecraft:smelting" | "minecraft:blasting" | "minecraft:smoking" @@ -189,6 +309,12 @@ impl Recipes { let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref(); for (_, recipe) in &self.crafting { match recipe { + Recipe::Special(special) => { + let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); + if let Some(result) = special.assemble(&stacks) { + return Some(result); + } + } Recipe::Shaped { width, height, @@ -242,9 +368,80 @@ impl Recipes { } None } + /// `Recipe.getRemainingItems` per grid cell: an item's crafting remainder + /// (buckets, bottles), and the patterned banner a duplicate keeps. + pub fn remainders( + &self, + items: &Items, + grid: &[Option], + result: &ItemStack, + ) -> Vec> { + grid.iter() + .map(|cell| { + let s = cell.as_ref()?; + if let Some(rem) = items.get(&s.item).and_then(|i| i.remainder.as_deref()) { + return Some(ItemStack::new(rem, 1)); + } + (result.item.ends_with("_banner") && !crate::banner::layers(s).is_empty()).then( + || ItemStack { + count: 1, + ..s.clone() + }, + ) + }) + .collect() + } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking .iter() .find(|c| c.kind == kind && c.ingredient.test(input)) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::banner::BannerLayer; + + fn ingredient(items: &[&str]) -> Ingredient { + Ingredient(items.iter().map(|s| (*s).to_owned()).collect()) + } + fn patterned(item: &str) -> ItemStack { + let mut s = ItemStack::new(item, 1); + s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; + s + } + #[test] + fn banner_duplicate_copies_the_patterns_of_the_same_colour() { + let recipe = Special::BannerDuplicate { + banner: ingredient(&["minecraft:white_banner"]), + result: "minecraft:white_banner".into(), + }; + let source = patterned("minecraft:white_banner"); + let blank = ItemStack::new("minecraft:white_banner", 1); + let out = recipe.assemble(&[&source, &blank]).expect("copy"); + assert_eq!(out.data().unwrap().banner_patterns.len(), 1); + // Two blanks, or two patterned banners, do not match. + assert!(recipe.assemble(&[&blank, &blank]).is_none()); + assert!(recipe.assemble(&[&source, &source]).is_none()); + // Another colour is not in the recipe's ingredient. + let other = ItemStack::new("minecraft:red_banner", 1); + assert!(recipe.assemble(&[&source, &other]).is_none()); + } + #[test] + fn shield_decoration_needs_a_bare_shield() { + let recipe = Special::ShieldDecoration { + banner: ingredient(&["minecraft:red_banner"]), + target: ingredient(&["minecraft:shield"]), + result: "minecraft:shield".into(), + }; + let banner = patterned("minecraft:red_banner"); + let shield = ItemStack::new("minecraft:shield", 1); + let out = recipe.assemble(&[&banner, &shield]).expect("decorated"); + let data = out.data().unwrap(); + assert_eq!(data.base_color.as_deref(), Some("red")); + assert_eq!(data.banner_patterns.len(), 1); + // A shield that already has patterns cannot be decorated again. + assert!(recipe.assemble(&[&banner, &out]).is_none()); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 66925932c..d5e5a8de4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4,6 +4,7 @@ mod advancements; mod advancements_screen; mod allays; mod armor_stands; +mod banners; mod beacon; mod blockctl; mod boats; @@ -28,6 +29,7 @@ mod game_mode; mod growth; mod jukebox; mod lightning; +mod loom; mod machines; mod maps; mod minecarts; @@ -607,6 +609,8 @@ struct Game<'a> { ender_open: Option<(i32, i32, i32)>, /// Contents of broken shulker boxes waiting for their dropped item. pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>, + /// Layers of broken banners waiting for their dropped item. + pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>, /// The player's fishing hook. hook: Option, tridents: Vec, @@ -977,6 +981,7 @@ impl Game<'_> { /// Block.popResource fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) { self.attach_shulker_contents(pos, &mut stack); + self.attach_banner_layers(pos, &mut stack); let r = &mut self.world.random; let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25; let p = [ @@ -1808,6 +1813,7 @@ impl Game<'_> { .block_entities .insert((target[0], target[1], target[2]), entity); self.fill_placed_box(target, &stack); + self.fill_placed_banner(target, &stack); if sign { self.open_sign_editor((target[0], target[1], target[2]), true); } @@ -2653,13 +2659,18 @@ impl Game<'_> { .map(|t| Icon::Flat(t.trim_start_matches("minecraft:").to_owned())) } fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { - if &*stack.item == "minecraft:shield" { - shield::draw_shield_icon(batch, &self.res.atlas, x, y); - return; - } - let icon = self.icon(&stack.item); + // Special-model items: the shield and banners draw their own 3D icon. + let banner = if &*stack.item == "minecraft:shield" { + let passes = shield::shield_passes(&self.res.stations.banners, stack); + shield::draw_shield_icon(batch, &self.res.atlas, x, y, &passes); + true + } else { + self.draw_banner_icon(batch, stack, x, y) + }; + let icon = if banner { None } else { self.icon(&stack.item) }; let atlas = &self.res.atlas; match icon { + None if banner => {} Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX), Some(Icon::Cube { top, @@ -3040,7 +3051,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3265,7 +3277,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_), ) => {} None => { let texture = if self.craft_size == 3 { @@ -3453,6 +3466,12 @@ impl Game<'_> { let mut crafted = 0; while let Some(result) = self.craft_result() { let made = (result.item.clone(), result.count); + let cells = self.craft_size * self.craft_size; + let remainders = self.res.recipes.remainders( + &self.res.items, + &self.craft_grid[..cells], + &result, + ); if shift { if self.give(result).is_some() { break; @@ -3477,6 +3496,14 @@ impl Game<'_> { } } } + for (i, rest) in remainders.into_iter().enumerate() { + let Some(rest) = rest else { continue }; + match &mut self.craft_grid[i] { + cell @ None => *cell = Some(rest), + Some(c) if c.same_item_same_components(&rest) => c.count += rest.count, + _ => self.give_or_drop(rest), + } + } crafted += 1; self.stats.add("crafted", &made.0, made.1 as i32); if !shift || crafted >= 64 { @@ -3867,6 +3894,7 @@ impl Game<'_> { Some(BlockEntity::Sign(sign)) => Some(sign), _ => None, }, + banner: &|p| self.banner_layers_at(p), glyph: &|c| self.res.atlas.glyph(c), }; self.res @@ -5760,6 +5788,10 @@ impl Game<'_> { } first(&d["model"]) }); + if item.ends_with("_banner") { + // The banner item model is a special renderer over this base model. + current = Some("minecraft:item/template_banner".to_owned()); + } for _ in 0..16 { let Some(m) = current.take() else { break }; let path = m.trim_start_matches("minecraft:").to_owned(); @@ -5906,6 +5938,9 @@ impl Game<'_> { * glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, deg(rot[0]), deg(rot[1]), deg(rot[2]))) * glam::Mat4::from_scale(glam::Vec3::from(scale)) * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); + if self.held_banner_geometry(m, &stack, packed, &mut out) { + return out; + } let atlas = &self.res.atlas; let quad = |corners: [glam::Vec3; 4], name: &str, @@ -7033,6 +7068,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Advancements { self.advancements_drag(); } + if self.screen == Screen::Inventory { + self.loom_drag(); + } if self.dragging && self.screen == Screen::Options { let _ = b; self.options_drag()?; @@ -7164,6 +7202,7 @@ impl ApplicationHandler for Game<'_> { self.container_changed(key); } } + Screen::Inventory => self.loom_release(), Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(), Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); @@ -7665,6 +7704,7 @@ pub fn run() -> Result<()> { ender_items: vec![None; 27], ender_open: None, pending_shulker: HashMap::new(), + pending_banner: HashMap::new(), hook: None, tridents: Vec::new(), rockets: Vec::new(), diff --git a/crates/horizon-client/src/game/banners.rs b/crates/horizon-client/src/game/banners.rs new file mode 100644 index 000000000..b9f701a0c --- /dev/null +++ b/crates/horizon-client/src/game/banners.rs @@ -0,0 +1,222 @@ +//! Placed banners (`BannerBlockEntity`): the pattern layers move from the +//! banner item to the block when placed and back to the dropped item when +//! broken (`copy_components` in the banner loot tables). +use super::Game; +use glam::{EulerRot, Mat4, Quat, Vec3}; +use horizon_client::{ + banner::{self, BannerLayer}, + block_entity_render::{Paint, draw_part}, + containers::{Banner, BlockEntity}, + hud::{HudBatch, rgba}, + items::ItemStack, + mesher::Vertex, +}; + +impl Game<'_> { + /// The pattern textures and tints of the banner at `pos`, bottom first. + pub(super) fn banner_layers_at(&self, pos: [i32; 3]) -> Vec<(String, u32)> { + let Some(BlockEntity::Banner(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + else { + return Vec::new(); + }; + layer_textures(&self.res.stations.banners, &b.layers) + } + /// A placed banner takes the item's layers and name. + pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) { + self.pending_banner.remove(&pos); + if !stack.item.ends_with("_banner") { + return; + } + if let Some(BlockEntity::Banner(b)) = + self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2])) + { + b.layers = banner::layers(stack).to_vec(); + b.name = stack.custom_name().map(str::to_owned); + } + } + /// A banner in a slot: `item/template_banner`'s `gui` transform on the + /// banner model (pole, bar and flag with every layer), flat-lit and + /// depth-sorted. False when the stack is not a banner. + pub(super) fn draw_banner_icon( + &self, + batch: &mut HudBatch, + stack: &ItemStack, + x: f32, + y: f32, + ) -> bool { + let Some(base) = banner::banner_color(&stack.item) else { + return false; + }; + let Some((main, flag)) = self.res.block_entity_render.banner_models() else { + return true; + }; + let banners = &self.res.stations.banners; + let sprites = &self.res.atlas.sprites; + // display.gui, then the item's special transformation (a banner is + // modelled upside down and 2/3 size around the block centre). + let m = Mat4::from_translation(Vec3::new(0.0, -3.25 / 16.0, 0.0)) + * Mat4::from_quat(Quat::from_euler( + EulerRot::XYZ, + 30f32.to_radians(), + 20f32.to_radians(), + 0.0, + )) + * Mat4::from_scale(Vec3::splat(0.5325)) + * Mat4::from_translation(Vec3::new(0.0, -0.5, 0.0)) + * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); + let wave = |name: &str, p: &mut [f32; 9]| { + if name == "flag" { + p[3] = (-0.0125 + 0.01) * std::f32::consts::PI; + } + }; + let none = |_: &str, _: &mut [f32; 9]| {}; + let mut passes: Vec<(&str, u32, bool, String)> = vec![ + ("entity/banner/banner_base", 0xFFFFFF, true, String::new()), + ( + "entity/banner/base", + banner::dye_rgb(base), + false, + String::new(), + ), + ]; + for layer in banner::layers(stack).iter().take(16) { + passes.push(( + "", + banner::dye_rgb(&layer.color), + false, + banners.banner_texture(&layer.pattern), + )); + } + // (depth, pass, screen corners, uv, colour) + let mut faces: Vec<(f32, usize, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); + for (index, (fixed, tint, with_pole, dynamic)) in passes.iter().enumerate() { + let name = if fixed.is_empty() { + dynamic.as_str() + } else { + fixed + }; + let Some(sprite) = sprites.get(name).copied() else { + continue; + }; + let paint = Paint { + sprite, + tint: 0xFFFFFF, + light: 0, + lights: (Vec3::ZERO, Vec3::ZERO), + }; + let mut verts: Vec = Vec::new(); + if *with_pole { + draw_part(main, "root", m, &none, paint, &mut verts); + } + draw_part(flag, "root", m, &wave, paint, &mut verts); + for quad in verts.as_chunks::<4>().0 { + let p = |i: usize| Vec3::from(quad[i].pos); + let normal = (p(1) - p(0)).cross(p(2) - p(0)).normalize_or_zero(); + // Faces turned away from the viewer are culled. + if normal.z <= 0.0 { + continue; + } + let depth = (0..4).map(|i| p(i).z).sum::() / 4.0; + let shade = (0.6 + 0.4 * normal.z).min(1.0); + let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8; + faces.push(( + depth, + index, + std::array::from_fn(|i| { + [ + x + 8.0 + quad[i].pos[0] * 16.0, + y + 8.0 - quad[i].pos[1] * 16.0, + ] + }), + std::array::from_fn(|i| quad[i].uv), + rgba(c(16), c(8), c(0), 255), + )); + } + } + faces.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + for (_, _, corners, uv, color) in faces { + batch.quad(corners, uv, color); + } + true + } + /// A banner in the first-person hand: the standing banner model under the + /// item's `firstperson_righthand` transform (`m`) and its special + /// transformation. False when the stack is not a banner. + pub(super) fn held_banner_geometry( + &self, + m: Mat4, + stack: &ItemStack, + packed: u32, + out: &mut Vec, + ) -> bool { + let Some(base) = banner::banner_color(&stack.item) else { + return false; + }; + let Some((main, flag)) = self.res.block_entity_render.banner_models() else { + return true; + }; + let m = m + * Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5)) + * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); + let wave = |name: &str, p: &mut [f32; 9]| { + if name == "flag" { + p[3] = (-0.0125 + 0.01) * std::f32::consts::PI; + } + }; + let none = |_: &str, _: &mut [f32; 9]| {}; + let lights = horizon_client::block_entity_render::diffuse_lights(false); + let sprites = &self.res.atlas.sprites; + let paint = |name: &str, tint: u32| { + sprites.get(name).map(|&sprite| Paint { + sprite, + tint, + light: packed, + lights, + }) + }; + if let Some(p) = paint("entity/banner/banner_base", 0xFFFFFF) { + draw_part(main, "root", m, &none, p, out); + draw_part(flag, "root", m, &wave, p, out); + } + if let Some(p) = paint("entity/banner/base", banner::dye_rgb(base)) { + draw_part(flag, "root", m, &wave, p, out); + } + for layer in banner::layers(stack).iter().take(16) { + let texture = self.res.stations.banners.banner_texture(&layer.pattern); + if let Some(p) = paint(&texture, banner::dye_rgb(&layer.color)) { + draw_part(flag, "root", m, &wave, p, out); + } + } + true + } + /// The layers a banner dropped at `pos` carries. + pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) { + if !stack.item.ends_with("_banner") { + return; + } + if let Some(Banner { layers, name }) = self.pending_banner.remove(&pos) { + let data = stack.data_mut(); + data.banner_patterns = layers; + if name.is_some() { + data.custom_name = name; + } + stack.tidy(); + } + } +} + +/// Texture names and tints of banner layers (`Sheets.getBannerSprite`). +pub(super) fn layer_textures( + banners: &banner::Banners, + layers: &[BannerLayer], +) -> Vec<(String, u32)> { + layers + .iter() + .map(|l| { + ( + banners.banner_texture(&l.pattern), + banner::dye_rgb(&l.color), + ) + }) + .collect() +} diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs new file mode 100644 index 000000000..39663c298 --- /dev/null +++ b/crates/horizon-client/src/game/loom.rs @@ -0,0 +1,415 @@ +//! The loom (`LoomMenu`, `LoomScreen`): stacking banner patterns onto a +//! banner with a dye (and a pattern item for the special patterns), the +//! six-layer limit, the scrolling pattern list and the banner preview. +use super::{ + Game, + stations::{INPUT, Station}, +}; +use horizon_client::{ + banner::{self, BannerLayer}, + hud::{HudBatch, Rect, rgba}, + items::ItemStack, +}; +use std::sync::Arc; + +/// Per-menu loom state: `selectablePatterns`, the selected index and the +/// screen's scroller. +#[derive(Default)] +pub(super) struct LoomState { + pub(super) patterns: Vec>, + pub(super) selected: Option, + /// `displayPatterns`: the pattern buttons are shown. + pub(super) display: bool, + pub(super) has_max: bool, + pub(super) scroll: f32, + pub(super) start_row: usize, + pub(super) scrolling: bool, +} +impl LoomState { + fn total_rows(&self) -> usize { + self.patterns.len().div_ceil(4) + } + fn offscreen_rows(&self) -> i32 { + self.total_rows() as i32 - 4 + } + fn scroll_active(&self) -> bool { + self.display && self.patterns.len() > 16 + } + /// `startRow` for a scroller position. + fn row_for(&self, offs: f32) -> usize { + ((offs * self.offscreen_rows() as f32 + 0.5) as i32).max(0) as usize + } +} + +const BUTTON: f32 = 14.0; + +fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool { + p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h +} +/// A sub-rectangle of a sprite given in texels. +fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect { + let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); + Rect { + u0: r.u0 + x * du, + v0: r.v0 + y * dv, + u1: r.u0 + (x + w) * du, + v1: r.v0 + (y + h) * dv, + w: w as u32, + h: h as u32, + } +} +/// A dye's tint as a HUD vertex colour. +pub(super) fn dye_color(name: &str) -> u32 { + let c = banner::dye_rgb(name); + rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, 255) +} + +impl Game<'_> { + /// `LoomMenu.slotsChanged` and the screen's `containerChanged`. + pub(super) fn loom_changed(&self, s: &mut Station) { + let banners = &self.res.stations.banners; + let items = &self.res.items; + let (banner_in, dye_in) = (s.inputs[0].as_ref(), s.inputs[1].as_ref()); + let l = &mut s.loom; + let mut result = None; + if let (Some(banner_stack), Some(dye_stack)) = (banner_in, dye_in) { + let valid = l.selected.is_some_and(|i| i < l.patterns.len()); + let previous = std::mem::take(&mut l.patterns); + l.patterns = banners.selectable(s.inputs[2].as_ref()); + let shown = if l.patterns.len() == 1 { + l.selected = Some(0); + Some(l.patterns[0].clone()) + } else if !valid { + l.selected = None; + None + } else { + let value = previous[l.selected.unwrap_or(0)].clone(); + match l.patterns.iter().position(|p| *p == value) { + Some(i) => { + l.selected = Some(i); + Some(value) + } + None => { + l.selected = None; + None + } + } + }; + l.has_max = banner::has_max_layers(banner_stack); + if let Some(pattern) = shown { + if l.has_max { + l.selected = None; + } else if let Some(dye) = banners.loom_dye(items, dye_stack) { + result = Some(banner::loom_result(banner_stack, &dye, &pattern)); + } + } + l.display = !l.has_max && !l.patterns.is_empty(); + } else { + l.patterns.clear(); + l.selected = None; + l.has_max = banner_in.is_some_and(banner::has_max_layers); + l.display = false; + } + if l.start_row >= l.total_rows() { + l.start_row = 0; + l.scroll = 0.0; + } + s.result = result; + } + /// The loom slots' `mayPlace`. + pub(super) fn loom_slot_rules(&self, input: usize, stack: &ItemStack) -> (bool, u32) { + let banners = &self.res.stations.banners; + let ok = match input { + 0 => stack.item.ends_with("_banner"), + 1 => banners.loom_dye(&self.res.items, stack).is_some(), + _ => banners.is_pattern_item(&self.res.items, stack), + }; + (ok, 64) + } + /// The result slot's `onTake`: one banner and one dye are used up. + pub(super) fn loom_taken(&mut self, s: &mut Station) { + for slot in &mut s.inputs[..2] { + if let Some(x) = slot.as_mut() { + x.count -= 1; + if x.count == 0 { + *slot = None; + } + } + } + if s.inputs[0].is_none() || s.inputs[1].is_none() { + s.loom.selected = None; + } + if s.last_sound != self.ticks { + s.last_sound = self.ticks; + let pos = s.pos; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio + .play("minecraft:ui.loom.take_result", Some(at), 1.0, 1.0); + } + } + /// `LoomMenu.quickMoveStack` from an inventory slot. + pub(super) fn loom_quick_move(&mut self, slot: usize, stack: &mut ItemStack) -> bool { + let banners = &self.res.stations.banners; + let items = &self.res.items; + let target = if stack.item.ends_with("_banner") { + Some(INPUT) + } else if banners.loom_dye(items, stack).is_some() { + Some(INPUT + 1) + } else if banners.is_pattern_item(items, stack) { + Some(INPUT + 2) + } else { + None + }; + match target { + Some(t) => self.move_to(stack, &[t], false), + None if (9..36).contains(&slot) => { + let hotbar: Vec = (0..9).collect(); + self.move_to(stack, &hotbar, false) + } + None if slot < 9 => { + let main: Vec = (9..36).collect(); + self.move_to(stack, &main, false) + } + None => false, + } + } + /// A left click inside the loom's pattern grid or scroller. + pub(super) fn loom_click(&mut self, local: (f32, f32)) -> bool { + let Some(s) = self.station.as_ref() else { + return false; + }; + let l = &s.loom; + if !l.display { + return false; + } + for row in 0..4 { + for column in 0..4 { + let index = (row + l.start_row) * 4 + column; + let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); + if index < l.patterns.len() && inside(local, x, y, BUTTON, BUTTON) { + if let Some(s) = self.station.as_mut() { + s.loom.selected = Some(index); + } + self.audio + .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); + self.station_changed(); + return true; + } + } + } + if inside(local, 119.0, 9.0, 12.0, 56.0) + && let Some(s) = self.station.as_mut() + { + s.loom.scrolling = true; + return true; + } + false + } + /// `LoomScreen.mouseDragged` on the scroller. + pub(super) fn loom_drag(&mut self) { + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return; + }; + let (_, oy) = self.inventory_origin(&HudBatch::new(size)); + let cursor_y = self.cursor.1; + let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else { + return; + }; + if l.scrolling && l.display && l.offscreen_rows() > 0 { + let top = oy + 13.0; + l.scroll = ((cursor_y - top - 7.5) / (56.0 - 15.0)).clamp(0.0, 1.0); + l.start_row = l.row_for(l.scroll); + } + } + pub(super) fn loom_release(&mut self) { + if let Some(s) = self.station.as_mut() { + s.loom.scrolling = false; + } + } + /// `LoomScreen.mouseScrolled`. + pub(super) fn loom_scroll(&mut self, d: f32) { + let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else { + return; + }; + let offscreen = l.offscreen_rows(); + if l.display && offscreen > 0 { + l.scroll = (l.scroll - d / offscreen as f32).clamp(0.0, 1.0); + l.start_row = l.row_for(l.scroll); + } + } + /// A banner flag's front face (`BannerFlagModel`, 20x40 texels at (1, 1)) + /// drawn flat: the cloth, the base colour and every layer. + pub(super) fn draw_flag( + &self, + batch: &mut HudBatch, + rect: [f32; 4], + base: &str, + layers: &[BannerLayer], + ) { + let banners = &self.res.stations.banners; + let mut paint = |name: &str, color: u32| { + if let Some(r) = self.res.atlas.sprites.get(name).copied() { + let uv = sub_rect(r, [1.0, 1.0, 20.0, 40.0]); + batch.rect_uv(rect[0], rect[1], rect[2], rect[3], uv, color); + } + }; + paint("entity/banner/banner_base", u32::MAX); + paint("entity/banner/base", dye_color(base)); + for layer in layers.iter().take(16) { + paint( + &banners.banner_texture(&layer.pattern), + dye_color(&layer.color), + ); + } + } + /// `LoomScreen.extractBackground` after the background; returns the + /// pattern name tooltip of the hovered button. + pub(super) fn draw_loom( + &mut self, + batch: &mut HudBatch, + ox: f32, + oy: f32, + local: (f32, f32), + ) -> Option> { + let s = self.station.as_ref()?; + let l = &s.loom; + let atlas = &self.res.atlas; + for (i, icon) in ["banner", "dye", "banner_pattern"].iter().enumerate() { + if s.inputs[i].is_none() { + let pos = [(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)][i]; + batch.sprite( + atlas, + &format!("gui/sprites/container/slot/{icon}"), + ox + pos.0, + oy + pos.1, + ); + } + } + let scroller = if l.scroll_active() { + "scroller" + } else { + "scroller_disabled" + }; + batch.sprite( + atlas, + &format!("gui/sprites/container/loom/{scroller}"), + ox + 119.0, + oy + 13.0 + (41.0 * l.scroll).floor(), + ); + let result = s.result.clone(); + let (display, has_max, start_row, selected) = + (l.display, l.has_max, l.start_row, l.selected); + let patterns = l.patterns.clone(); + let dye = s.inputs[1] + .as_ref() + .and_then(|d| self.res.stations.banners.loom_dye(&self.res.items, d)) + .unwrap_or_else(|| Arc::from("white")); + if let Some(result) = result.filter(|_| !has_max) + && let Some(base) = banner::banner_color(&result.item) + { + self.draw_flag( + batch, + [ox + 141.0, oy + 8.0, 20.0, 40.0], + base, + banner::layers(&result), + ); + } else if has_max { + batch.sprite( + &self.res.atlas, + "gui/sprites/container/loom/error", + ox + 138.0, + oy + 52.0, + ); + } + let mut tooltip = None; + if display { + let atlas = &self.res.atlas; + for row in 0..4 { + for column in 0..4 { + let index = (row + start_row) * 4 + column; + let Some(pattern) = patterns.get(index) else { + return tooltip; + }; + let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); + let hover = inside(local, x, y, BUTTON, BUTTON); + let sprite = if selected == Some(index) { + "pattern_selected" + } else if hover { + let key = self + .res + .stations + .banners + .layer_key(&BannerLayer::new(pattern, &dye)); + tooltip = Some(vec![(self.translate(&key, &key), u32::MAX)]); + "pattern_highlighted" + } else { + "pattern" + }; + batch.sprite( + atlas, + &format!("gui/sprites/container/loom/{sprite}"), + ox + x, + oy + y, + ); + // extractBannerOnButton: a 5x10 grey cloth with the pattern. + batch.fill( + atlas, + ox + x + 4.0, + oy + y + 2.0, + 5.0, + 10.0, + dye_color("gray"), + ); + let texture = self.res.stations.banners.banner_texture(pattern); + if let Some(r) = atlas.sprites.get(&texture).copied() { + let uv = sub_rect(r, [0.0, 1.0, 21.0, 40.0]); + batch.rect_uv(ox + x + 4.0, oy + y + 2.0, 5.0, 10.0, uv, u32::MAX); + } + } + } + } + tooltip + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scroller_rows_follow_the_offset() { + let l = LoomState { + patterns: (0..40) + .map(|i| Arc::from(format!("p{i}").as_str())) + .collect(), + display: true, + ..Default::default() + }; + // 40 patterns = 10 rows, 6 off screen. + assert_eq!(l.offscreen_rows(), 6); + assert!(l.scroll_active()); + assert_eq!(l.row_for(0.0), 0); + assert_eq!(l.row_for(1.0), 6); + assert_eq!(l.row_for(0.5), 3); + } + #[test] + fn few_patterns_do_not_scroll() { + let l = LoomState { + patterns: (0..16) + .map(|i| Arc::from(format!("p{i}").as_str())) + .collect(), + display: true, + ..Default::default() + }; + assert!(!l.scroll_active()); + assert_eq!(l.offscreen_rows(), 0); + } +} diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 259758994..9f201dc8a 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1238,6 +1238,7 @@ impl Game<'_> { nether: self.dim == super::Dim::Nether, lid: &lid, sign: &|_| None, + banner: &|_| Vec::new(), glyph: &|c| self.res.atlas.glyph(c), }; self.res diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index eade37109..7857c047e 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -252,14 +252,8 @@ pub(super) fn draw_shield_icon( atlas: &horizon_client::hud::HudAtlas, x: f32, y: f32, + passes: &[(String, u32)], ) { - let Some(r) = atlas - .sprites - .get("entity/shield/shield_base_nopattern") - .copied() - else { - return; - }; // display.gui: rotation [15, -25, -5], translation [2, 3, 0], scale 0.65. let (sx, cx) = 15f32.to_radians().sin_cos(); let (sy, cy) = (-25f32).to_radians().sin_cos(); @@ -282,15 +276,9 @@ pub(super) fn draw_shield_icon( qz, ] }; - let tex = |u: f32, v: f32| { - [ - r.u0 + (r.u1 - r.u0) * u / 64.0, - r.v0 + (r.v1 - r.v0) * v / 64.0, - ] - }; // ShieldModel: plate texOffs(0, 0) box(-6, -11, -2, 12, 22, 1) and // handle texOffs(26, 0) box(-1, -3, -1, 2, 6, 6). - let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); + let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], f32)> = Vec::new(); for (tu, tv, from, size) in [ (0.0, 0.0, [-6.0, -11.0, -2.0], [12.0, 22.0, 1.0]), (26.0, 0.0, [-1.0, -3.0, -1.0], [2.0, 6.0, 6.0]), @@ -324,16 +312,64 @@ pub(super) fn draw_shield_icon( } let p = verts.map(place); let depth = p.iter().map(|q| q[2]).sum::() / 4.0; - let uv = [tex(c, b), tex(a, b), tex(a, e), tex(c, e)]; + let texels = [[c, b], [a, b], [a, e], [c, e]]; // Flat item lighting: faces toward the viewer are brightest. let shade = (0.6 + 0.4 * normal[2]).min(1.0); - let s = (shade * 255.0) as u8; - let color = horizon_client::hud::rgba(s, s, s, 255); - faces.push((depth, p.map(|q| [q[0], q[1]]), uv, color)); + faces.push((depth, p.map(|q| [q[0], q[1]]), texels, shade)); } } - faces.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, p, uv, color) in faces { + // Every pass redraws the same boxes; equal depths keep the pass order. + let mut quads = Vec::new(); + for (index, (name, tint)) in passes.iter().enumerate() { + let Some(r) = atlas.sprites.get(name).copied() else { + continue; + }; + for (depth, p, texels, shade) in &faces { + let uv = texels.map(|[u, v]| { + [ + r.u0 + (r.u1 - r.u0) * u / 64.0, + r.v0 + (r.v1 - r.v0) * v / 64.0, + ] + }); + let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8; + quads.push(( + *depth, + index, + *p, + uv, + horizon_client::hud::rgba(c(16), c(8), c(0), 255), + )); + } + } + quads.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + for (_, _, p, uv, color) in quads { batch.quad(p, uv, color); } } +/// The textures a shield draws: the plain or patterned base, then the +/// banner layers (`ShieldSpecialRenderer.submit`). +pub(super) fn shield_passes( + banners: &horizon_client::banner::Banners, + stack: &ItemStack, +) -> Vec<(String, u32)> { + let data = stack.data(); + let layers = data.map_or(&[][..], |d| &d.banner_patterns[..]); + let base = data.and_then(|d| d.base_color.as_deref()); + if layers.is_empty() && base.is_none() { + return vec![("entity/shield/shield_base_nopattern".into(), 0xFFFFFF)]; + } + let mut passes = vec![ + ("entity/shield/shield_base".into(), 0xFFFFFF), + ( + "entity/shield/base".into(), + horizon_client::banner::dye_rgb(base.unwrap_or("white")), + ), + ]; + for layer in layers.iter().take(16) { + passes.push(( + banners.shield_texture(&layer.pattern), + horizon_client::banner::dye_rgb(&layer.color), + )); + } + passes +} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index eb6f8c24d..e2771daba 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -32,6 +32,8 @@ pub(super) enum Kind { Beacon, /// The cartography table (game/cartography.rs). Cartography, + /// The loom (game/loom.rs). + Loom, } impl Kind { fn from_block(name: &str) -> Option { @@ -45,12 +47,13 @@ impl Kind { "minecraft:stonecutter" => Self::Stonecutter, "minecraft:beacon" => Self::Beacon, "minecraft:cartography_table" => Self::Cartography, + "minecraft:loom" => Self::Loom, _ => return None, }) } fn inputs(self) -> usize { match self { - Self::Smithing => 3, + Self::Smithing | Self::Loom => 3, Self::Stonecutter | Self::Beacon => 1, _ => 2, } @@ -65,6 +68,7 @@ impl Kind { Self::Merchant => "gui/container/villager", Self::Beacon => "gui/container/beacon", Self::Cartography => "gui/container/cartography_table", + Self::Loom => "gui/container/loom", } } fn title_key(self) -> &'static str { @@ -77,6 +81,7 @@ impl Kind { Self::Merchant => "merchant.trades", Self::Beacon => "container.beacon", Self::Cartography => "container.cartography_table", + Self::Loom => "container.loom", } } /// (titleLabelX, titleLabelY). @@ -85,7 +90,7 @@ impl Kind { Self::Anvil => (60.0, 6.0), Self::Smithing => (44.0, 15.0), Self::Stonecutter => (8.0, 5.0), - Self::Cartography => (8.0, 4.0), + Self::Cartography | Self::Loom => (8.0, 4.0), _ => (8.0, 6.0), } } @@ -99,6 +104,7 @@ impl Kind { Self::Merchant => &[(86.0, 37.0), (112.0, 37.0)], Self::Beacon => &[(109.0, 110.0)], Self::Cartography => &[(15.0, 15.0), (15.0, 52.0)], + Self::Loom => &[(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)], }; table[i.min(table.len() - 1)] } @@ -112,6 +118,7 @@ impl Kind { Self::Merchant => Some((170.0, 37.0)), Self::Beacon => None, Self::Cartography => Some((145.0, 39.0)), + Self::Loom => Some((143.0, 57.0)), } } } @@ -133,11 +140,13 @@ pub(super) struct Station { input_item: Option>, /// Anvil: the input the rename box was last filled from. anvil_last: Option, - last_sound: u64, + pub(super) last_sound: u64, /// Villager trading state. pub(super) merchant: Option>, /// Beacon menu: the selected primary and secondary power (EFFECTS index). pub(super) beacon: [Option; 2], + /// The loom's patterns, selection and scroller (game/loom.rs). + pub(super) loom: super::loom::LoomState, } impl Station { fn new(kind: Kind, pos: [i32; 3]) -> Self { @@ -158,6 +167,7 @@ impl Station { last_sound: 0, merchant: None, beacon: [None; 2], + loom: Default::default(), } } pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self { @@ -437,6 +447,7 @@ impl Game<'_> { Kind::Merchant => super::trading::update(&mut s, items), Kind::Beacon => {} Kind::Cartography => s.result = self.cartography_result(&s), + Kind::Loom => self.loom_changed(&mut s), Kind::Stonecutter => { let item = s.inputs[0].as_ref().map(|i| i.item.clone()); if item != s.input_item { @@ -498,6 +509,7 @@ impl Game<'_> { match s.kind { Kind::Enchanting if i == 0 => (true, 1), Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), + Kind::Loom => self.loom_slot_rules(i, stack), Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), Kind::Cartography => ( matches!( @@ -565,7 +577,12 @@ impl Game<'_> { self.carried = new_carried; } /// `moveItemStackTo` over `targets` (menu order), merging first, then empty slots. - fn move_to(&mut self, stack: &mut ItemStack, targets: &[usize], reverse: bool) -> bool { + pub(super) fn move_to( + &mut self, + stack: &mut ItemStack, + targets: &[usize], + reverse: bool, + ) -> bool { let order: Vec = if reverse { targets.iter().rev().copied().collect() } else { @@ -614,8 +631,12 @@ impl Game<'_> { return false; }; let player = Self::player_slots(); + let loom = self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom); let moved = if (300..305).contains(&slot) || slot >= INPUT { - self.move_to(&mut stack, &player, true) + // LoomMenu moves into the inventory front to back, the others back to front. + self.move_to(&mut stack, &player, !loom) + } else if loom { + self.loom_quick_move(slot, &mut stack) } else if self.brewing_open() { // BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half. let data = self.data(); @@ -673,7 +694,7 @@ impl Game<'_> { moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false); } } - Some(Kind::Merchant) => {} + Some(Kind::Merchant | Kind::Loom) => {} Some(Kind::Beacon) => { // BeaconMenu.quickMoveStack: one payment item into the empty slot. if super::beacon::is_payment(&stack.item) { @@ -713,7 +734,7 @@ impl Game<'_> { ]; self.audio.play(sound, Some(at), volume, pitch); } - fn give_or_drop(&mut self, stack: ItemStack) { + pub(super) fn give_or_drop(&mut self, stack: ItemStack) { if let Some(rest) = self.give(stack) && let Some(eye) = self.eye_position() { @@ -860,6 +881,7 @@ impl Game<'_> { self.cartography_taken(pos); } } + Kind::Loom => self.loom_taken(&mut s), Kind::Enchanting => {} } self.station = Some(s); @@ -991,6 +1013,9 @@ impl Game<'_> { if kind == Kind::Merchant && !right && self.merchant_click(local) { return true; } + if kind == Kind::Loom && !right && self.loom_click(local) { + return true; + } if kind == Kind::Beacon && !right && self.beacon_click(local) { return true; } @@ -1065,6 +1090,7 @@ impl Game<'_> { } pub(super) fn station_scroll(&mut self, d: f32) { self.merchant_scroll(d); + self.loom_scroll(d); let Some(s) = self.station.as_mut() else { return; }; @@ -1308,6 +1334,9 @@ impl Game<'_> { if kind == Kind::Cartography { self.draw_cartography(batch, ox, oy); } + if kind == Kind::Loom { + tooltip = self.draw_loom(batch, ox, oy, local); + } let atlas = &self.res.atlas; let s = self.station.as_ref().expect("open station"); let has_input = s.inputs.iter().any(Option::is_some); @@ -1598,7 +1627,7 @@ impl Game<'_> { } } } - Kind::Merchant | Kind::Beacon | Kind::Cartography => {} + Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {} Kind::Stonecutter => { let display = s.inputs[0].is_some() && !s.recipes.is_empty(); let active = display && s.recipes.len() > 12; @@ -1799,6 +1828,11 @@ impl Game<'_> { }, )); } + // BannerPatternLayers.addToTooltip: up to six layer names. + for layer in horizon_client::banner::layers(stack).iter().take(6) { + let key = self.res.stations.banners.layer_key(layer); + lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); + } if let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 && stack.damage > 0 diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 4d161514f..78c002d1a 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -11,6 +11,10 @@ impl Game<'_> { /// Block-entity contents on removal: shulker boxes keep theirs for the /// dropped box (`copy_components`), other containers spill them. pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) { + if let BlockEntity::Banner(banner) = entity { + self.pending_banner.insert(pos, banner); + return; + } if is_shulker_box(block) { if let BlockEntity::Chest(items) = entity { let kept = items diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index d7643d3dd..792373e7a 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -35,6 +35,10 @@ pub struct StackData { pub writable_pages: Vec, /// `minecraft:written_book_content`. pub written: Option, + /// `minecraft:banner_patterns` (banners and shields). + pub banner_patterns: Vec, + /// `minecraft:base_color` (a shield's dye). + pub base_color: Option>, } /// `WrittenBookContent` with the pages as plain text. #[derive(Clone, Debug, Default, PartialEq)] @@ -267,6 +271,15 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { if let Some(id) = d.map_id { entries.push(("minecraft:map_id", Tag::Int(id))); } + if !d.banner_patterns.is_empty() { + entries.push(( + "minecraft:banner_patterns", + crate::banner::layers_to_nbt(&d.banner_patterns), + )); + } + if let Some(color) = &d.base_color { + entries.push(("minecraft:base_color", Tag::String((&**color).into()))); + } // Filterable values are saved as {raw: ..}. let raw = |t: Tag| Tag::compound([("raw", t)]); if !d.writable_pages.is_empty() { @@ -371,6 +384,11 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option { + if !b.layers.is_empty() { + entries.push(("patterns", crate::banner::layers_to_nbt(&b.layers))); + } + if let Some(name) = &b.name { + entries.push(("CustomName", string(name))); + } + } } Tag::compound(entries) } @@ -428,6 +436,15 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; return Some((pos, BlockEntity::Lectern(lectern))); } + if id == "minecraft:banner" { + return Some(( + pos, + BlockEntity::Banner(crate::containers::Banner { + layers: crate::banner::layers_from_nbt(tag.get("patterns")), + name: text(tag.get("CustomName")), + }), + )); + } if id == "minecraft:beacon" { let beacon = crate::containers::Beacon { levels: int("Levels").unwrap_or(0), @@ -474,7 +491,10 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; } BlockEntity::Sign(sign) => sign.decode(tag), - BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) => {} + BlockEntity::Jukebox(_) + | BlockEntity::Beacon(_) + | BlockEntity::Lectern(_) + | BlockEntity::Banner(_) => {} } Some((pos, entity)) } @@ -1993,6 +2013,25 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn banner_block_entity_round_trips() { + let banner = crate::containers::Banner { + layers: vec![crate::banner::BannerLayer::new("minecraft:creeper", "lime")], + name: Some("Flag".into()), + }; + let tag = encode_block_entity( + (1, 2, 3), + &crate::containers::BlockEntity::Banner(banner.clone()), + "minecraft:red_banner", + ); + let (pos, back) = decode_block_entity(&tag).expect("banner"); + assert_eq!(pos, (1, 2, 3)); + let crate::containers::BlockEntity::Banner(back) = back else { + panic!("not a banner"); + }; + assert_eq!(back.layers, banner.layers); + assert_eq!(back.name, banner.name); + } use super::*; #[test] diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 8fd6f85d7..eee0a7442 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -18,6 +18,7 @@ pub struct StationData { pub recipes: StationRecipes, pub brewing: crate::brewing::Brewing, pub trades: crate::merchant::Trades, + pub banners: crate::banner::Banners, } impl StationData { pub fn load(root: &Path, items: &Items) -> Self { @@ -26,6 +27,7 @@ impl StationData { recipes: StationRecipes::load(root, items), brewing: crate::brewing::Brewing::load(root, items), trades: crate::merchant::Trades::load(root), + banners: crate::banner::Banners::load(root), } } } From ef6f41b12c34e5cec584360ac3ccb8283664b930 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:42:27 +0200 Subject: [PATCH 03/16] Add scoreboards and teams Scoreboards now work like vanilla: objectives with every criteria kind (dummy, trigger, health, food, xp, level, armor, deathCount, kill counts, per-colour team kills and any statistic such as minecraft.mined:minecraft.stone), the full /scoreboard command (objectives add, remove, list, modify and setdisplay; players set, add, remove, reset, get, list, enable, operation and display name or number format), /trigger, and /team with colour, prefix, suffix, friendly fire, invisibility, nametag, death message and collision options. Scores, teams and display slots are saved as vanilla NBT in data/minecraft/scoreboard.dat. The sidebar draws with the objective title, team colour slots, number formats and the vanilla layout, and target selectors accept scores={...}, team= and tag=. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/command/args.rs | 272 +++- crates/horizon-client/src/command/mod.rs | 1 + .../src/command/tree_scoreboard.rs | 214 ++++ crates/horizon-client/src/command/vanilla.rs | 1 + crates/horizon-client/src/game.rs | 8 + crates/horizon-client/src/game/commands.rs | 21 +- crates/horizon-client/src/game/creatures.rs | 2 + crates/horizon-client/src/game/persist.rs | 6 +- crates/horizon-client/src/game/scoreboard.rs | 510 ++++++++ crates/horizon-client/src/game/stats.rs | 7 + crates/horizon-client/src/lib.rs | 2 + crates/horizon-client/src/save.rs | 4 +- crates/horizon-client/src/scoreboard.rs | 1115 ++++++++++++++++ crates/horizon-client/src/scoreboard_cmd.rs | 1124 +++++++++++++++++ .../src/scoreboard_cmd_tests.rs | 295 +++++ 15 files changed, 3568 insertions(+), 14 deletions(-) create mode 100644 crates/horizon-client/src/command/tree_scoreboard.rs create mode 100644 crates/horizon-client/src/game/scoreboard.rs create mode 100644 crates/horizon-client/src/scoreboard.rs create mode 100644 crates/horizon-client/src/scoreboard_cmd.rs create mode 100644 crates/horizon-client/src/scoreboard_cmd_tests.rs diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index bfe79244d..a98c30816 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -29,6 +29,13 @@ pub struct Registries { /// Game rule name -> integer-valued. pub game_rules: Vec<(String, bool)>, pub players: Vec, + /// Scoreboard objective names, team names and tracked score holders. + pub objectives: Vec, + pub teams: Vec, + pub tracked: Vec, + /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). + pub functions: Vec, + pub function_tags: Vec, /// The block the source is looking at (relevant coordinates). pub target_block: Option<[i32; 3]>, } @@ -116,6 +123,24 @@ pub enum ArgType { Component, /// CompoundTagArgument (kept as SNBT text). Nbt, + /// ScoreHolderArgument. + ScoreHolder { + multiple: bool, + }, + /// ObjectiveArgument (checked when the command runs). + Objective, + /// TeamArgument (checked when the command runs). + Team, + /// ObjectiveCriteriaArgument. + Criteria, + /// ScoreboardSlotArgument. + ScoreboardSlot, + /// OperationArgument. + Operation, + /// TeamColorArgument. + TeamColor, + /// RangeArgument.Ints (`1`, `1..`, `..5`, `1..5`). + IntRange, } pub fn integer(min: i32) -> ArgType { ArgType::Integer { min, max: i32::MAX } @@ -227,6 +252,29 @@ pub struct Selector { pub y_rotation: Option, pub pos: [Option; 3], pub delta: [Option; 3], + /// `scores={objective=range,...}`. + pub scores: Vec<(String, IntRange)>, + /// `team=` (an empty name matches entities without a team). + pub teams: Vec<(String, bool)>, + /// `nbt=` compounds (SNBT text). + pub nbt: Vec<(String, bool)>, + /// `advancements={id=true|{criterion=true}}`. + pub advancements: Vec<(String, AdvCondition)>, + /// `predicate=` ids. + pub predicates: Vec<(String, bool)>, +} +/// An `advancements=` entry: all done or not, or per-criterion states. +#[derive(Clone, Debug, PartialEq)] +pub enum AdvCondition { + Done(bool), + Criteria(Vec<(String, bool)>), +} +/// A `ScoreHolderArgument` value. +#[derive(Clone, Debug, PartialEq)] +pub enum ScoreHolderArg { + Wildcard, + Name(String), + Selector(Selector), } impl Selector { pub fn is_self(&self) -> bool { @@ -293,6 +341,8 @@ pub enum Arg { GameMode(GameMode), /// `eyes` (true) or `feet`. Anchor(bool), + ScoreHolder(ScoreHolderArg), + IntRange(IntRange), } fn is_id_char(c: char) -> bool { @@ -563,6 +613,7 @@ fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries) { } } +pub const OPERATIONS: [&str; 9] = ["=", "+=", "-=", "*=", "/=", "%=", "<", ">", "><"]; const SELECTORS: [(&str, &str); 6] = [ ("@a", "argument.entity.selector.allPlayers"), ("@e", "argument.entity.selector.allEntities"), @@ -571,7 +622,7 @@ const SELECTORS: [(&str, &str); 6] = [ ("@r", "argument.entity.selector.randomPlayer"), ("@s", "argument.entity.selector.self"), ]; -const OPTIONS: [&str; 16] = [ +const OPTIONS: [&str; 21] = [ "name", "distance", "level", @@ -588,7 +639,22 @@ const OPTIONS: [&str; 16] = [ "gamemode", "tag", "type", + "scores", + "team", + "nbt", + "advancements", + "predicate", ]; +/// StringReader.expect. +fn expect_symbol(reader: &mut Reader, c: char) -> CmdResult<()> { + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == c { + reader.skip(); + Ok(()) + } else { + Err(CommandError::tr_at("parsing.expected", &[&c], reader)) + } +} fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult { let start = reader.cursor; if !(reader.can_read() && reader.peek() == '@') { @@ -791,6 +857,81 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult let v = reader.read_unquoted_string().to_owned(); s.tags.push((v, neg)); } + "team" => { + let neg = negated(reader); + let v = reader.read_unquoted_string().to_owned(); + s.teams.push((v, neg)); + } + "nbt" => { + let neg = negated(reader); + if !reader.can_read() || reader.peek() != '{' { + return Err(CommandError::tr_at( + "argument.nbt.expected.compound", + &[], + reader, + )); + } + s.nbt.push((read_braced(reader, '{', '}')?, neg)); + } + "predicate" => { + let neg = negated(reader); + s.predicates.push((read_id(reader)?, neg)); + } + "scores" => { + expect_symbol(reader, '{')?; + reader.skip_whitespace(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let name = reader.read_unquoted_string().to_owned(); + expect_symbol(reader, '=')?; + let range = range_int(reader)?; + s.scores.push((name, range)); + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + } + "advancements" => { + expect_symbol(reader, '{')?; + reader.skip_whitespace(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let id = read_id(reader)?; + expect_symbol(reader, '=')?; + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == '{' { + reader.skip(); + reader.skip_whitespace(); + let mut criteria = Vec::new(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let c = reader.read_unquoted_string().to_owned(); + expect_symbol(reader, '=')?; + criteria.push((c, reader.read_boolean()?)); + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + s.advancements.push((id, AdvCondition::Criteria(criteria))); + } else { + s.advancements + .push((id, AdvCondition::Done(reader.read_boolean()?))); + } + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + s.include_entities = false; + } "type" => { let neg = negated(reader); let at = reader.cursor; @@ -1436,6 +1577,91 @@ impl ArgType { } Arg::Str(axes) } + ArgType::ScoreHolder { multiple } => { + if reader.can_read() && reader.peek() == '@' { + let sel = parse_selector(reader, reg)?; + if !*multiple && sel.limit > 1 { + reader.cursor = start; + return Err(CommandError::tr_at("argument.entity.toomany", &[], reader)); + } + Arg::ScoreHolder(ScoreHolderArg::Selector(sel)) + } else { + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let text = &reader.string[start..reader.cursor]; + if text == "*" { + Arg::ScoreHolder(ScoreHolderArg::Wildcard) + } else { + Arg::ScoreHolder(ScoreHolderArg::Name(text.to_owned())) + } + } + } + ArgType::Objective | ArgType::Team => { + Arg::Str(reader.read_unquoted_string().to_owned()) + } + ArgType::Criteria => { + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let id = &reader.string[start..reader.cursor]; + if !crate::scoreboard::criteria_exists(id, reg) { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.criteria.invalid", + &[&id], + reader, + )); + } + Arg::Str(id.to_owned()) + } + ArgType::ScoreboardSlot => { + let name = reader.read_unquoted_string(); + if !crate::scoreboard::display_slot_valid(name) { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.scoreboardDisplaySlot.invalid", + &[&name], + reader, + )); + } + Arg::Str(name.to_owned()) + } + ArgType::Operation => { + if !reader.can_read() { + return Err(CommandError::tr_at( + "arguments.operation.invalid", + &[], + reader, + )); + } + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let op = &reader.string[start..reader.cursor]; + if !OPERATIONS.contains(&op) { + reader.cursor = start; + return Err(CommandError::tr_at( + "arguments.operation.invalid", + &[], + reader, + )); + } + Arg::Str(op.to_owned()) + } + ArgType::TeamColor => { + let name = reader.read_unquoted_string(); + if crate::scoreboard::team_color_rgb(name).is_none() { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.color.invalid", + &[&name], + reader, + )); + } + Arg::Str(name.to_owned()) + } + ArgType::IntRange => Arg::IntRange(range_int(reader)?), ArgType::Anchor => { let name = reader.read_unquoted_string(); match name { @@ -1511,6 +1737,50 @@ impl ArgType { } } ArgType::GameMode => builder.suggest_matching(GameMode::ALL.map(GameMode::name)), + ArgType::ScoreHolder { .. } => { + suggest_selector(builder, reg); + let names: Vec = reg + .players + .iter() + .chain(reg.tracked.iter()) + .cloned() + .collect(); + builder.suggest_matching(names.iter().map(String::as_str)); + } + ArgType::Objective => { + builder.suggest_matching(reg.objectives.iter().map(String::as_str)) + } + ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)), + ArgType::Criteria => { + let mut ids: Vec = crate::scoreboard::CUSTOM_CRITERIA + .iter() + .map(|s| (*s).to_owned()) + .collect(); + for c in crate::scoreboard::team_colors() { + ids.push(format!("teamkill.{c}")); + ids.push(format!("killedByTeam.{c}")); + } + let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key); + ids.extend(reg.blocks.keys().map(|b| stat("mined", b))); + for ty in ["crafted", "used", "broken", "picked_up", "dropped"] { + ids.extend(reg.items.iter().map(|i| stat(ty, i))); + } + for ty in ["killed", "killed_by"] { + ids.extend(reg.entity_types.iter().map(|e| stat(ty, e))); + } + ids.extend( + crate::scoreboard::CUSTOM_STATS + .iter() + .map(|c| stat("custom", &format!("minecraft:{c}"))), + ); + builder.suggest_matching(ids.iter().map(String::as_str)); + } + ArgType::ScoreboardSlot => { + let slots = crate::scoreboard::display_slots(); + builder.suggest_matching(slots.iter().map(String::as_str)); + } + ArgType::Operation => builder.suggest_matching(OPERATIONS), + ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Swizzle | ArgType::Component => {} ArgType::Message => { diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 7e8090d6b..d1ca22799 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -4,6 +4,7 @@ //! usage text and the vanilla error messages. Argument types live in //! [`args`]; the vanilla command tree in [`vanilla`]. pub mod args; +pub mod tree_scoreboard; pub mod vanilla; use crate::text::Text; diff --git a/crates/horizon-client/src/command/tree_scoreboard.rs b/crates/horizon-client/src/command/tree_scoreboard.rs new file mode 100644 index 000000000..4493ca8f1 --- /dev/null +++ b/crates/horizon-client/src/command/tree_scoreboard.rs @@ -0,0 +1,214 @@ +//! The `/scoreboard`, `/team` and `/trigger` command trees +//! (ScoreboardCommand, TeamCommand, TriggerCommand). +use super::{Dispatcher, args::ArgType, vanilla::GAMEMASTERS}; + +const HOLDERS: ArgType = ArgType::ScoreHolder { multiple: true }; +const HOLDER: ArgType = ArgType::ScoreHolder { multiple: false }; + +/// `addNumberFormats`: blank | fixed | styled