From 95149579ff3a21501ecdb02b26e63a9db8b6afca Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 03:21:40 +0200 Subject: [PATCH] Add minecarts, jukeboxes, name tags and outline-shape picking Minecarts follow OldMinecartBehavior: rails and slopes, powered and activator rails, coming off the track, the rider's push, players and carts pushing each other, placement, breaking and saving, with chest and hopper containers, furnace fuel and push, and TNT priming and explosions. They render on the rail between the front and back points with their display block. Jukeboxes take jukebox_playable discs, play the song with the rainbow Now Playing overlay and note particles, emit 15 while playing, drive comparators, eject the disc and save it. Name tags name mobs (saved as CustomName); the name shows above the head on a translucent background when targeted or always visible, and Dinnerbone and Grumm render upside down. Blocks are now picked and outlined with their vanilla outline shapes (exported per state with the edges LevelRenderer draws), so rails, slabs, torches and plants no longer act as full cubes. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/block_entity_render.rs | 15 + crates/horizon-client/src/blocks.rs | 55 + crates/horizon-client/src/containers.rs | 15 +- crates/horizon-client/src/entity_nbt.rs | 40 + crates/horizon-client/src/game.rs | 153 +- crates/horizon-client/src/game/boats.rs | 3 + crates/horizon-client/src/game/control.rs | 2 + crates/horizon-client/src/game/creatures.rs | 3 + crates/horizon-client/src/game/jukebox.rs | 250 ++++ crates/horizon-client/src/game/machines.rs | 7 + crates/horizon-client/src/game/minecarts.rs | 1314 +++++++++++++++++ crates/horizon-client/src/game/names.rs | 112 ++ crates/horizon-client/src/game/persist.rs | 28 + crates/horizon-client/src/game/titles.rs | 29 +- crates/horizon-client/src/gfx.rs | 71 +- crates/horizon-client/src/items.rs | 53 + crates/horizon-client/src/mobs.rs | 5 + crates/horizon-client/src/mobs/render.rs | 4 + crates/horizon-client/src/save.rs | 20 + crates/horizon-world/src/level/redstone.rs | 4 +- .../parity/VanillaGameplayFactsExporter.java | 18 + 21 files changed, 2141 insertions(+), 60 deletions(-) create mode 100644 crates/horizon-client/src/game/jukebox.rs create mode 100644 crates/horizon-client/src/game/minecarts.rs create mode 100644 crates/horizon-client/src/game/names.rs diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 038c60af2..5869f6de0 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -822,6 +822,21 @@ impl BlockEntityRenderer { self.render_one(scene, *pos, kind, base, packed, lights, out); } } + /// One block entity of `state` drawn under `base` (minecart contents). + pub fn render_state( + &self, + scene: &Scene, + state: u32, + base: Mat4, + packed: u8, + out: &mut Vec, + ) { + let kind = self.kind(state); + if !matches!(kind, Kind::None) { + let lights = diffuse_lights(scene.nether); + self.render_one(scene, [i32::MAX; 3], kind, base, packed, lights, out); + } + } #[allow(clippy::too_many_arguments)] fn render_one( &self, diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index 85a774f88..e62f2baca 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -60,6 +60,26 @@ pub struct StateFacts { pub sturdy_full: u8, /// The block's class chain (`TransparentBlock`, `LeavesBlock`, ...), most specific first. pub classes: Arc<[Arc]>, + /// `getShape` (the outline used for picking) as boxes in block space, + /// without the random offset; and its edges as LevelRenderer draws them. + pub outline: Arc<[[f32; 6]]>, + pub outline_edges: Arc<[[f32; 6]]>, +} +/// The 12 edges of the unit cube (outline data predating the export). +fn cube_edges() -> Vec<[f32; 6]> { + let mut edges = Vec::new(); + for a in 0..3 { + for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] { + let mut from = [0.0f32; 3]; + let (b, c) = ((a + 1) % 3, (a + 2) % 3); + from[b] = u; + from[c] = v; + let mut to = from; + to[a] = 1.0; + edges.push([from[0], from[1], from[2], to[0], to[1], to[2]]); + } + } + edges } impl StateFacts { pub fn has_class(&self, name: &str) -> bool { @@ -115,6 +135,25 @@ impl BlockFacts { .or_insert_with(|| Arc::from(s)) .clone() }; + let mut shapes: HashMap> = HashMap::new(); + let mut shape = |v: &Value, fallback: &dyn Fn() -> Vec<[f32; 6]>| -> Arc<[[f32; 6]]> { + let Some(list) = v.as_array() else { + return fallback().into(); + }; + shapes + .entry(v.to_string()) + .or_insert_with(|| { + list.iter() + .filter_map(|b| { + let b = b.as_array()?; + let n = + |i: usize| b.get(i).and_then(Value::as_f64).unwrap_or(0.0) as f32; + Some([n(0), n(1), n(2), n(3), n(4), n(5)]) + }) + .collect() + }) + .clone() + }; let mut states = Vec::with_capacity(entries.len()); for (index, entry) in entries.iter().enumerate() { let id = BlockStateId(index as u32); @@ -152,7 +191,23 @@ impl BlockFacts { _ if prop("waterlogged") == Some("true") => (Fluid::Water, 8, false), _ => (Fluid::None, 0, false), }; + let air = matches!( + state.name.as_str(), + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ); + let cube = move || { + if air { + Vec::new() + } else { + vec![[0.0, 0.0, 0.0, 1.0, 1.0, 1.0]] + } + }; + let edges = move || if air { Vec::new() } else { cube_edges() }; + let outline = shape(&entry["outline"], &cube); + let outline_edges = shape(&entry["outline_edges"], &edges); states.push(StateFacts { + outline, + outline_edges, name: intern(&state.name), emission: num("emission") as u8, dampening: num("dampening") as u8, diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 4281385df..c4fa3d8c5 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -52,6 +52,15 @@ pub enum BlockEntity { Brewing(Box), /// Signs and hanging signs (`SignBlockEntity`). Sign(crate::signs::SignData), + /// `JukeboxBlockEntity`: the record and its `JukeboxSongPlayer`. + Jukebox(Jukebox), +} +#[derive(Clone, Debug, Default)] +pub struct Jukebox { + pub record: Option, + /// `ticks_since_song_started`, while a song plays. + pub ticks: i64, + pub playing: bool, } impl BlockEntity { pub fn for_block(name: &str) -> Option { @@ -114,6 +123,7 @@ impl BlockEntity { }, Self::Brewing(_) => "minecraft:brewing_stand", Self::Sign(s) => s.id(), + Self::Jukebox(_) => "minecraft:jukebox", } } pub fn contents(&self) -> Vec { @@ -122,6 +132,7 @@ impl BlockEntity { Self::Furnace(f) => f.items.iter().flatten().cloned().collect(), Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), Self::Sign(_) => Vec::new(), + Self::Jukebox(j) => j.record.iter().cloned().collect(), } } pub fn slots(&self) -> &[Option] { @@ -129,7 +140,7 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &f.items, Self::Brewing(b) => &b.items, - Self::Sign(_) => &[], + Self::Sign(_) | Self::Jukebox(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -137,7 +148,7 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, Self::Brewing(b) => &mut b.items, - Self::Sign(_) => &mut [], + Self::Sign(_) | Self::Jukebox(_) => &mut [], } } } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 3f87d4f9f..3f1d69ba5 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -108,9 +108,16 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { Tag::Short(m.death_time.clamp(0, i32::from(i16::MAX)) as i16), ), ("PersistenceRequired", Tag::Byte(i8::from(m.persistent))), + ("CustomNameVisible", Tag::Byte(i8::from(m.name_visible))), ] { put(&mut tag, key, value); } + // A styled name from the save stays unless the name changed. + if custom_name(&tag) != m.custom_name + && let Some(name) = &m.custom_name + { + put(&mut tag, "CustomName", Tag::String(name.as_str().into())); + } let Tag::Compound(map) = &mut tag else { return tag; }; @@ -177,6 +184,17 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } tag } +/// `CustomName`: a text component saved as a string or a `{text: ..}` compound. +fn custom_name(tag: &Tag) -> Option { + match tag.get("CustomName")? { + Tag::String(s) => Some(s.to_string_lossy()), + t @ Tag::Compound(_) => match t.get("text") { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }, + _ => None, + } +} pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option { let kind = types.get(&self::kind(tag)?)?.clone(); let position = position(tag)?; @@ -192,6 +210,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32; m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32; m.persistent = flag(tag, "PersistenceRequired"); + m.custom_name = custom_name(tag); + m.name_visible = flag(tag, "CustomNameVisible"); // A mob saved mid-death finishes dying; one saved dead is dropped. if m.health <= 0.0 && m.death_time == 0 { return None; @@ -546,6 +566,26 @@ pub fn boat_to_nbt( } .tag(raw) } +/// A vehicle's base entity tag (boats and minecarts). +pub fn vehicle_to_nbt( + id: &str, + position: Vec3, + motion: Vec3, + yaw: f32, + uuid: [i32; 4], + raw: Option<&Tag>, +) -> Tag { + Base { + id, + uuid, + position, + motion, + rotation: [yaw, 0.0], + on_ground: false, + fall_distance: 0.0, + } + .tag(raw) +} pub fn boat_from_nbt(tag: &Tag) -> Option<(Vec3, Vec3, f32)> { Some((position(tag)?, motion(tag), rotation(tag)[0])) } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5ea1d95a6..12da8300a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -16,8 +16,11 @@ mod fishing; mod fov; mod frames; mod growth; +mod jukebox; mod machines; +mod minecarts; mod music; +mod names; mod options; mod packs; mod paintings; @@ -276,8 +279,19 @@ impl LevelAccess for GameLevel<'_> { _state: BlockStateId, _direction: Direction, ) -> i32 { + if let Some((_, comparator)) = jukebox::jukebox_signals(self.world, self.items, pos) { + return comparator; + } machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos) } + fn block_entity_signal( + &self, + pos: BlockPos, + _state: BlockStateId, + _direction: Direction, + ) -> i32 { + jukebox::jukebox_signals(self.world, self.items, pos).map_or(0, |(signal, _)| signal) + } fn biome_name(&self, pos: BlockPos) -> Option<&str> { let chunk = self.world.chunks.get(&(pos.x >> 4, pos.z >> 4))?; Some(&self.biomes.get(chunk.biome(pos.x, pos.y, pos.z)).name) @@ -535,6 +549,10 @@ struct Game<'a> { armor_stand_assets: armor_stands::ArmorStandAssets, boats: Vec, boat_models: boats::BoatModels, + carts: Vec, + /// Songs playing from jukeboxes (tracked sound handles). + jukebox_sounds: HashMap<(i32, i32, i32), u64>, + cart_models: minecarts::CartModels, /// The boat the player rides. riding: Option, /// The ender inventory (27 slots) and the ender chest showing it. @@ -608,7 +626,31 @@ impl Game<'_> { fn reach(&self) -> f64 { if self.creative { 5.0 } else { 4.5 } } - /// Voxel traversal against non-air, non-fluid blocks (outline = full cube). + /// A block's outline boxes in world space (`getShape` plus the random offset). + fn outline_boxes(&self, pos: [i32; 3]) -> Vec<[f64; 6]> { + let state = self.world.block(pos[0], pos[1], pos[2]); + let f = self.res.facts.get(state); + let o = if f.random_offset { + self.res + .context + .tables + .offset(state, pos[0], pos[2]) + .unwrap_or([0.0; 3]) + } else { + [0.0; 3] + }; + let base = [ + f64::from(pos[0]) + o[0], + f64::from(pos[1]) + o[1], + f64::from(pos[2]) + o[2], + ]; + f.outline + .iter() + .map(|b| std::array::from_fn(|i| base[i % 3] + f64::from(b[i]))) + .collect() + } + /// Voxel traversal against non-air, non-fluid blocks, clipped against + /// each block's outline shape (`BlockGetter.clip` with `ClipContext.Block.OUTLINE`). fn pick(&self) -> Option { let origin = self.eye_position()?; let dir = view_vector(self.yaw, self.pitch); @@ -650,15 +692,49 @@ impl Game<'_> { "minecraft:water" | "minecraft:lava" | "minecraft:bubble_column" ) { - return Some(Hit { - pos, - face, - point: [ - origin[0] + dir[0] * t, - origin[1] + dir[1] * t, - origin[2] + dir[2] * t, - ], - }); + // The nearest entry into one of the outline's boxes (slab method). + let mut best: Option<(f64, [i32; 3])> = None; + for b in self.outline_boxes(pos) { + let (mut t0, mut t1, mut axis_in, mut sign) = (0.0f64, f64::INFINITY, None, 0); + let mut miss = false; + for a in 0..3 { + if dir[a] == 0.0 { + miss |= origin[a] < b[a] || origin[a] > b[a + 3]; + continue; + } + let (lo, hi) = + ((b[a] - origin[a]) / dir[a], (b[a + 3] - origin[a]) / dir[a]); + let (near, far) = if lo < hi { (lo, hi) } else { (hi, lo) }; + if near > t0 { + t0 = near; + axis_in = Some(a); + sign = if dir[a] > 0.0 { -1 } else { 1 }; + } + t1 = t1.min(far); + } + if miss || t0 > t1 || t0 > reach { + continue; + } + let mut normal = face; + if let Some(a) = axis_in { + normal = [0; 3]; + normal[a] = sign; + } + if best.is_none_or(|(bt, _)| t0 < bt) { + best = Some((t0, normal)); + } + } + if let Some((t, face)) = best { + return Some(Hit { + pos, + face, + point: [ + origin[0] + dir[0] * t, + origin[1] + dir[1] * t, + origin[2] + dir[2] * t, + ], + }); + } } let axis = if t_max[0] < t_max[1] { if t_max[0] < t_max[2] { 0 } else { 2 } @@ -1117,6 +1193,7 @@ impl Game<'_> { self.audio.play(&name, Some(c), volume, pitch); } LevelEvent::DropResources { pos, state } => { + self.jukebox_removed([pos.x, pos.y, pos.z]); if let Some(entity) = self.world.block_entities.remove(&(pos.x, pos.y, pos.z)) { let name = self.res.facts.get(state).name.clone(); self.release_contents([pos.x, pos.y, pos.z], entity, &name); @@ -1429,6 +1506,7 @@ impl Game<'_> { if self.interact_frame() || self.interact_armor_stand() || self.interact_boat() + || self.interact_cart() || self.interact_mob()? { return Ok(()); @@ -1438,6 +1516,11 @@ impl Game<'_> { if !(sneaking && self.held().is_some()) && let Some(hit) = self.pick() { + let held = self.held().cloned(); + if self.use_jukebox(hit.pos, held.as_ref()) { + self.swing_arm(); + return Ok(()); + } let face = match hit.face { [0, 1, 0] => Direction::Up, [0, -1, 0] => Direction::Down, @@ -1524,6 +1607,7 @@ impl Game<'_> { } if let Some(hit) = self.pick() && (self.launch_firework(&hit, &stack) + || self.place_minecart(&hit, &stack) || self.place_painting(&hit, &stack) || self.place_item_frame(&hit, &stack) || self.place_armor_stand(&hit, &stack)) @@ -2160,6 +2244,7 @@ impl Game<'_> { self.tick_item_frames(); self.tick_armor_stands(); self.tick_boats(); + self.tick_carts(); self.tick_fishing(); self.tick_tridents(); self.tick_rockets(); @@ -2734,7 +2819,7 @@ impl Game<'_> { Some(BlockEntity::Chest(items)) => v.extend((0..items.len()).map(|i| 300 + i)), Some(BlockEntity::Furnace(_)) => v.extend(300..303), Some(BlockEntity::Brewing(_)) => v.extend(300..305), - Some(BlockEntity::Sign(_)) => {} + Some(BlockEntity::Sign(_) | BlockEntity::Jukebox(_)) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); v.push(200); @@ -2898,7 +2983,9 @@ impl Game<'_> { .container .map(|k| self.world.block(k.0, k.1, k.2)) .map(|s| self.res.facts.get(s).name.clone()); - let title = if name.as_deref() == Some("minecraft:barrel") { + let title = if self.open_cart_kind().is_some() { + "Minecart with Chest" + } else if name.as_deref() == Some("minecraft:barrel") { "Barrel" } else { "Chest" @@ -2952,7 +3039,7 @@ impl Game<'_> { } } Some(BlockEntity::Brewing(_)) => {} - Some(BlockEntity::Sign(_)) => {} + Some(BlockEntity::Sign(_) | BlockEntity::Jukebox(_)) => {} None => { let texture = if self.craft_size == 3 { "gui/container/crafting_table" @@ -3071,6 +3158,7 @@ impl Game<'_> { self.world.modified.insert((key.0 >> 4, key.2 >> 4)); } self.close_ender_chest(); + self.close_cart_container(); } fn click_inventory(&mut self, right: bool) { if self.station_click(right) { @@ -3397,6 +3485,7 @@ impl Game<'_> { } // Mobs and their projectiles. self.mob_geometry(camera, alpha, &mut out); + self.name_tag_geometry(camera, alpha, &mut out); // Arrows: two crossed quads along the flight direction. if let Some(r) = self .res @@ -3634,6 +3723,7 @@ impl Game<'_> { self.frame_geometry(camera, &mut out); self.armor_stand_geometry(camera, alpha, &mut out); self.boat_geometry(camera, alpha, &mut out); + self.cart_geometry(camera, alpha, &mut out); self.fishing_geometry(camera, alpha, &mut out); self.trident_geometry(camera, alpha, &mut out); self.rocket_geometry(camera, alpha, &mut out); @@ -3799,7 +3889,11 @@ impl Game<'_> { .held() .and_then(|h| self.res.items.get(&h.item)) .map_or(0.0, |i| i.attack_damage); - if self.attack_frame() || self.attack_armor_stand() || self.attack_boat(hand_damage) { + if self.attack_frame() + || self.attack_armor_stand() + || self.attack_boat(hand_damage) + || self.attack_cart(hand_damage) + { return true; } let Some((index, distance)) = self.mob_hit() else { @@ -3931,6 +4025,7 @@ impl Game<'_> { } fn tick_block_entities(&mut self) -> Result<()> { self.tick_hoppers()?; + self.tick_jukeboxes(); // ChestLidController: 0.1 per tick towards open/closed. if let Some(key) = self.container { self.chest_open.entry(key).or_insert((0.0, 0.0)); @@ -6257,13 +6352,30 @@ impl Game<'_> { sky.sky_color = [0.9, 0.9, 1.0]; sky.sky_light_factor = 1.0; } + // LevelRenderer.renderHitOutline: the outline shape's edges. let outline = if self.screen == Screen::Playing { - self.pick().map(|h| { - let p = h.pos.map(f64::from); - [p[0], p[1], p[2], p[0] + 1.0, p[1] + 1.0, p[2] + 1.0] - }) + self.pick() + .map(|h| { + let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]); + let f = self.res.facts.get(state); + let o = if f.random_offset { + self.res + .context + .tables + .offset(state, h.pos[0], h.pos[2]) + .unwrap_or([0.0; 3]) + } else { + [0.0; 3] + }; + let p = h.pos.map(f64::from); + f.outline_edges + .iter() + .map(|e| std::array::from_fn(|i| p[i % 3] + o[i % 3] + f64::from(e[i]))) + .collect() + }) + .unwrap_or_default() } else { - None + Vec::new() }; let hud = self.hud(size); let title = self.title.is_some(); @@ -7173,6 +7285,9 @@ pub fn run() -> Result<()> { armor_stand_assets: armor_stands::ArmorStandAssets::load(&root), boats: Vec::new(), boat_models: boats::BoatModels::load(&root), + carts: Vec::new(), + jukebox_sounds: HashMap::new(), + cart_models: minecarts::CartModels::load(&root), riding: None, ender_items: vec![None; 27], ender_open: None, diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index d1f97c822..f426fa059 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -399,6 +399,9 @@ impl Game<'_> { /// The player's tick while riding: steer, tick the boat, sit in it. pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> { let Some(i) = self.boats.iter().position(|b| Some(b.id) == self.riding) else { + if self.tick_cart_riding(keys) { + return Ok(()); + } self.riding = None; return Ok(()); }; diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index b134e1ee5..be74c0e88 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -476,6 +476,8 @@ impl Game<'_> { "fishing": self.hook_status(), "tridents": self.tridents.len(), "rockets": self.rockets.len(), + "carts": self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::>(), + "riding": self.riding, "using": self.using, "render_distance": self.streaming.radius, "chunks": self.world.chunks.len(), diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 87539700f..7a7543daf 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1225,6 +1225,9 @@ impl Game<'_> { return Ok(false); } } + if self.name_mob(index) { + return Ok(true); + } let held = self.held().cloned(); let item = held .as_ref() diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs new file mode 100644 index 000000000..e321a599b --- /dev/null +++ b/crates/horizon-client/src/game/jukebox.rs @@ -0,0 +1,250 @@ +//! Jukeboxes (`JukeboxBlock`, `JukeboxBlockEntity`, `JukeboxSongPlayer`): +//! inserting a `jukebox_playable` disc, ejecting it, the song with its +//! "Now Playing" overlay, note particles every second, the redstone +//! signal while playing, the comparator output, and saving. +use super::Game; +use horizon_client::{ + containers::{BlockEntity, Jukebox}, + items::ItemStack, + particles::{ParticleOptions, ParticleType}, + text::Text, +}; +use horizon_core::{position::BlockPos, random::RandomSource}; +use horizon_world::level::flags as level_flags; + +/// Linear attenuation range of a song (`SimpleSoundInstance.forJukeboxSong`: volume 4). +const RANGE: f64 = 64.0; + +impl Game<'_> { + fn jukebox(&self, pos: [i32; 3]) -> Option<&Jukebox> { + match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { + Some(BlockEntity::Jukebox(j)) => Some(j), + _ => None, + } + } + fn set_has_record(&mut self, pos: [i32; 3], has: bool) { + let state = self.world.block(pos[0], pos[1], pos[2]); + let registry = self.res.assets.registry; + let Some(mut s) = registry.state(state).cloned() else { + return; + }; + s.properties.insert( + "has_record".into(), + if has { "true" } else { "false" }.into(), + ); + if let Some(new) = registry.id(&s) { + let p = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| { + b.set_block(level, ticks, p, new, level_flags::UPDATE_CLIENTS) + }); + } + } + /// `onSongChanged`: neighbours (the signal) and comparators. + fn jukebox_changed(&mut self, pos: [i32; 3]) { + let p = BlockPos::new(pos[0], pos[1], pos[2]); + let state = self.world.block(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| { + let block = b.block(state); + b.update_neighbors_at(level, ticks, p, block); + }); + self.container_changed((pos[0], pos[1], pos[2])); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + } + /// `JukeboxBlock.useItemOn` / `useWithoutItem` on the jukebox at `pos`. + pub(super) fn use_jukebox(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { + if &*self + .res + .facts + .get(self.world.block(pos[0], pos[1], pos[2])) + .name + != "minecraft:jukebox" + { + return false; + } + if self.jukebox(pos).is_some_and(|j| j.record.is_some()) { + self.eject_record(pos); + return true; + } + let Some(stack) = held else { return false }; + let Some(song) = self + .res + .items + .get(&stack.item) + .and_then(|i| i.jukebox_song.clone()) + else { + return false; + }; + // JukeboxPlayable.tryInsertIntoJukebox + let record = ItemStack { + count: 1, + ..stack.clone() + }; + if !self.creative { + self.consume_held(); + } + self.world.block_entities.insert( + (pos[0], pos[1], pos[2]), + BlockEntity::Jukebox(Jukebox { + record: Some(record), + ticks: 0, + playing: true, + }), + ); + self.set_has_record(pos, true); + self.start_song(pos, &song); + self.jukebox_changed(pos); + true + } + /// Level event 1010: the song from the jukebox, and the "Now Playing" overlay. + fn start_song(&mut self, pos: [i32; 3], song: &str) { + self.stop_song(pos); + let Some(s) = self.res.items.songs.get(song).cloned() else { + return; + }; + if let Some(id) = self.audio.play_tracked(&s.sound, 0.0, false) { + self.jukebox_sounds.insert((pos[0], pos[1], pos[2]), id); + } + let description = + horizon_client::component::to_text(&s.description, &mut |k| Text::literal(k)); + self.titles + .set_overlay(Text::translate("record.nowPlaying", &[description])); + self.titles.overlay_animated = true; + self.update_song_volumes(); + } + fn stop_song(&mut self, pos: [i32; 3]) { + if let Some(id) = self.jukebox_sounds.remove(&(pos[0], pos[1], pos[2])) { + self.audio.stop_tracked(id); + } + } + /// `popOutTheItem`: the disc above the jukebox, and the song stops. + fn eject_record(&mut self, pos: [i32; 3]) { + let key = (pos[0], pos[1], pos[2]); + let record = match self.world.block_entities.get_mut(&key) { + Some(BlockEntity::Jukebox(j)) => { + j.playing = false; + j.ticks = 0; + j.record.take() + } + _ => None, + }; + self.stop_song(pos); + if let Some(record) = record { + let r = &mut self.world.random; + // offsetRandomXZ(random, 0.7) + let dx = f64::from(r.next_float() * 2.0 - 1.0) * 0.7 / 2.0; + let dz = f64::from(r.next_float() * 2.0 - 1.0) * 0.7 / 2.0; + let at = [ + f64::from(pos[0]) + 0.5 + dx, + f64::from(pos[1]) + 1.01, + f64::from(pos[2]) + 0.5 + dz, + ]; + self.spawn_item(record, at, [0.0, 0.0, 0.0], 10); + } + self.set_has_record(pos, false); + self.jukebox_changed(pos); + } + /// A broken jukebox stops its song (its disc drops with the contents). + pub(super) fn jukebox_removed(&mut self, pos: [i32; 3]) { + self.stop_song(pos); + } + /// `JukeboxSongPlayer.tick` for every playing jukebox. + pub(super) fn tick_jukeboxes(&mut self) { + let playing: Vec<((i32, i32, i32), String, i64)> = self + .world + .block_entities + .iter() + .filter_map(|(k, e)| match e { + BlockEntity::Jukebox(j) if j.playing => { + let song = self + .res + .items + .get(&j.record.as_ref()?.item)? + .jukebox_song + .clone()?; + Some((*k, song, j.ticks)) + } + _ => None, + }) + .collect(); + for (key, song, ticks) in playing { + let pos = [key.0, key.1, key.2]; + let Some(s) = self.res.items.songs.get(&song).cloned() else { + continue; + }; + if s.finished(ticks) { + if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) { + j.playing = false; + j.ticks = 0; + } + self.stop_song(pos); + self.jukebox_changed(pos); + continue; + } + if !self.jukebox_sounds.contains_key(&key) && ticks == 0 { + self.start_song(pos, &song); + } + if ticks % 20 == 0 { + let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 1.2, + f64::from(pos[2]) + 0.5, + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::Note), + at, + [color, 0.0, 0.0], + ); + } + if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) { + j.ticks += 1; + } + } + self.update_song_volumes(); + } + /// Linear distance attenuation of each song at the listener. + fn update_song_volumes(&mut self) { + let Some(eye) = self.eye_position() else { + return; + }; + let sounds: Vec<_> = self + .jukebox_sounds + .iter() + .map(|(k, id)| (*k, *id)) + .collect(); + for (k, id) in sounds { + if !self.audio.tracked_active(id) + || !matches!(self.world.block_entities.get(&k), Some(BlockEntity::Jukebox(j)) if j.playing) + { + self.audio.stop_tracked(id); + self.jukebox_sounds.remove(&k); + continue; + } + let d = ((f64::from(k.0) + 0.5 - eye[0]).powi(2) + + (f64::from(k.1) + 0.5 - eye[1]).powi(2) + + (f64::from(k.2) + 0.5 - eye[2]).powi(2)) + .sqrt(); + self.audio + .set_tracked_volume(id, (1.0 - d / RANGE).clamp(0.0, 1.0) as f32); + } + } +} +/// The jukebox's redstone signal (15 while a song plays) and comparator output. +pub(super) fn jukebox_signals( + world: &horizon_client::world::World, + items: &horizon_client::items::Items, + pos: BlockPos, +) -> Option<(i32, i32)> { + match world.block_entities.get(&(pos.x, pos.y, pos.z)) { + Some(BlockEntity::Jukebox(j)) => { + let comparator = j + .record + .as_ref() + .and_then(|r| items.get(&r.item)?.jukebox_song.as_ref()) + .and_then(|s| items.songs.get(s)) + .map_or(0, |s| s.comparator); + Some((if j.playing { 15 } else { 0 }, comparator)) + } + _ => None, + } +} diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 02a36ffd5..2299bc87a 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -301,6 +301,9 @@ impl Game<'_> { } /// `BlockEntity.setChanged` at `pos`: comparators re-read the container. pub(super) fn container_changed(&mut self, pos: Pos) { + if pos.1 == super::minecarts::CART_KEY_Y { + return; + } self.world.modified.insert((pos.0 >> 4, pos.2 >> 4)); self.with_level(|b, level, ticks| { b.container_changed(level, ticks, BlockPos::new(pos.0, pos.1, pos.2)) @@ -1011,6 +1014,10 @@ enum Screen { impl Game<'_> { fn machine_screen(&self) -> Option { let key = self.container?; + if key.1 == super::minecarts::CART_KEY_Y { + return (self.open_cart_kind() == Some(super::minecarts::CartKind::Hopper)) + .then_some(Screen::Hopper); + } let state = self.world.block(key.0, key.1, key.2); match &*self.res.facts.get(state).name { "minecraft:hopper" => Some(Screen::Hopper), diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs new file mode 100644 index 000000000..fe9cd28d2 --- /dev/null +++ b/crates/horizon-client/src/game/minecarts.rs @@ -0,0 +1,1314 @@ +//! Minecarts (`AbstractMinecart` with `OldMinecartBehavior`): following +//! rails and slopes, powered and activator rails, coming off the track, +//! riding with the rider's push, pushing by players and other carts, +//! `MinecartItem` placement, `VehicleEntity` breaking, the chest, hopper, +//! furnace and TNT variants, saving, and `AbstractMinecartRenderer`'s old +//! rail-following render with the display block. +use super::{Game, Hit, Keys, explosion::BlockInteraction, view_vector}; +use horizon_client::{ + blocks::Fluid, + collisions::SceneCollisions, + containers::BlockEntity, + items::ItemStack, + mesher::Vertex, + mobs::{Part, anim::Poses}, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; +use horizon_world::registry::BlockStateId; +use std::{collections::HashMap, sync::Arc}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum CartKind { + Rideable, + Chest, + Hopper, + Furnace, + Tnt, +} +impl CartKind { + pub fn from_id(id: &str) -> Option { + Some(match id.strip_prefix("minecraft:")? { + "minecart" => Self::Rideable, + "chest_minecart" => Self::Chest, + "hopper_minecart" => Self::Hopper, + "furnace_minecart" => Self::Furnace, + "tnt_minecart" => Self::Tnt, + _ => return None, + }) + } + pub fn id(self) -> &'static str { + match self { + Self::Rideable => "minecraft:minecart", + Self::Chest => "minecraft:chest_minecart", + Self::Hopper => "minecraft:hopper_minecart", + Self::Furnace => "minecraft:furnace_minecart", + Self::Tnt => "minecraft:tnt_minecart", + } + } + fn slots(self) -> usize { + match self { + Self::Chest => 27, + Self::Hopper => 5, + _ => 0, + } + } +} +#[derive(Clone, Debug)] +pub(super) struct Minecart { + pub id: u32, + pub kind: CartKind, + pub position: Vec3, + pub previous: Vec3, + pub velocity: Vec3, + pub yaw: f32, + pub previous_yaw: f32, + pub flipped: bool, + on_ground: bool, + horizontal_collision: bool, + fall_distance: f64, + pub hurt_time: i32, + pub hurt_dir: i32, + pub damage: f32, + pub items: Vec>, + /// Furnace minecarts: fuel ticks and the push direction. + pub fuel: i32, + pub push: [f64; 2], + /// TNT minecarts: ticks until the explosion, -1 when not primed. + pub fuse: i32, + /// Hopper minecarts: an unpowered activator rail enables them. + pub enabled: bool, +} +const WIDTH: f64 = 0.98; +const HEIGHT: f64 = 0.7; +/// The minecart's passenger attachment minus Player.DEFAULT_VEHICLE_ATTACHMENT. +const SEAT: f64 = 0.1875 - 0.6; +/// The placeholder container key under which an open cart's items live. +pub(super) const CART_KEY_Y: i32 = -100_000; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Shape { + NorthSouth, + EastWest, + AscendingEast, + AscendingWest, + AscendingNorth, + AscendingSouth, + SouthEast, + SouthWest, + NorthWest, + NorthEast, +} +impl Shape { + fn parse(s: &str) -> Self { + match s { + "east_west" => Self::EastWest, + "ascending_east" => Self::AscendingEast, + "ascending_west" => Self::AscendingWest, + "ascending_north" => Self::AscendingNorth, + "ascending_south" => Self::AscendingSouth, + "south_east" => Self::SouthEast, + "south_west" => Self::SouthWest, + "north_west" => Self::NorthWest, + "north_east" => Self::NorthEast, + _ => Self::NorthSouth, + } + } + fn is_slope(self) -> bool { + matches!( + self, + Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth + ) + } + /// `AbstractMinecart.EXITS`. + fn exits(self) -> ([i32; 3], [i32; 3]) { + let (w, e, n, s) = ([-1, 0, 0], [1, 0, 0], [0, 0, -1], [0, 0, 1]); + let below = |v: [i32; 3]| [v[0], -1, v[2]]; + match self { + Self::NorthSouth => (n, s), + Self::EastWest => (w, e), + Self::AscendingEast => (below(w), e), + Self::AscendingWest => (w, below(e)), + Self::AscendingNorth => (n, below(s)), + Self::AscendingSouth => (below(n), s), + Self::SouthEast => (s, e), + Self::SouthWest => (s, w), + Self::NorthWest => (n, w), + Self::NorthEast => (n, e), + } + } +} +struct Rail { + name: Arc, + shape: Shape, + powered: bool, +} +impl Minecart { + pub fn new(id: u32, kind: CartKind, position: Vec3) -> Self { + Self { + id, + kind, + position, + previous: position, + velocity: Vec3::ZERO, + yaw: 0.0, + previous_yaw: 0.0, + flipped: false, + on_ground: false, + horizontal_collision: false, + fall_distance: 0.0, + hurt_time: 0, + hurt_dir: 1, + damage: 0.0, + items: vec![None; kind.slots()], + fuel: 0, + push: [0.0; 2], + fuse: -1, + enabled: true, + } + } + pub fn bounds(&self) -> Aabb { + let (w, p) = (WIDTH / 2.0, self.position); + Aabb::new( + Vec3::new(p.x - w, p.y, p.z - w), + Vec3::new(p.x + w, p.y + HEIGHT, p.z + w), + ) + } + fn horizontal(&self) -> f64 { + self.velocity.x.hypot(self.velocity.z) + } +} +pub(super) struct CartModels { + pub models: HashMap, +} +impl CartModels { + pub fn load(root: &std::path::Path) -> Self { + let kinds = [ + CartKind::Rideable, + CartKind::Chest, + CartKind::Hopper, + CartKind::Furnace, + CartKind::Tnt, + ]; + let models = kinds + .into_iter() + .filter_map(|k| { + horizon_client::mobs::load_model(root, &format!("{}#main", k.id())).map(|m| (k, m)) + }) + .collect(); + Self { models } + } +} +impl Game<'_> { + fn rail(&self, x: i32, y: i32, z: i32) -> Option { + let state = self.world.block(x, y, z); + let name = self.res.facts.get(state).name.clone(); + if !matches!( + &*name, + "minecraft:rail" + | "minecraft:powered_rail" + | "minecraft:detector_rail" + | "minecraft:activator_rail" + ) { + return None; + } + let s = self.res.assets.registry.state(state)?; + let shape = Shape::parse(s.properties.get("shape").map_or("", String::as_str)); + let powered = s.properties.get("powered").is_some_and(|v| v == "true"); + Some(Rail { + name, + shape, + powered, + }) + } + /// `getCurrentBlockPosOrRailBelow`. + fn rail_block(&self, p: Vec3) -> [i32; 3] { + let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + if self.rail(x, y - 1, z).is_some() { + [x, y - 1, z] + } else { + [x, y, z] + } + } + fn conductor(&self, x: i32, y: i32, z: i32) -> bool { + self.res.facts.get(self.world.block(x, y, z)).full_collision + } + fn cart_in_water(&self, c: &Minecart) -> bool { + let p = c.position; + let f = self.res.facts.get(self.world.block( + p.x.floor() as i32, + (p.y + 0.1).floor() as i32, + p.z.floor() as i32, + )); + f.fluid == Fluid::Water + } + /// `OldMinecartBehavior.getPos`: the point on the rail under (x, y, z). + fn rail_pos(&self, x: f64, y: f64, z: f64) -> Option<[f64; 3]> { + let [xt, yt, zt] = self.rail_block(Vec3::new(x, y, z)); + let rail = self.rail(xt, yt, zt)?; + let (e0, e1) = rail.shape.exits(); + let (fx, fy, fz) = (f64::from(xt), f64::from(yt), f64::from(zt)); + let x0 = fx + 0.5 + f64::from(e0[0]) * 0.5; + let y0 = fy + 0.0625 + f64::from(e0[1]) * 0.5; + let z0 = fz + 0.5 + f64::from(e0[2]) * 0.5; + let x1 = fx + 0.5 + f64::from(e1[0]) * 0.5; + let y1 = fy + 0.0625 + f64::from(e1[1]) * 0.5; + let z1 = fz + 0.5 + f64::from(e1[2]) * 0.5; + let (xd, yd, zd) = (x1 - x0, (y1 - y0) * 2.0, z1 - z0); + let progress = if xd == 0.0 { + z - fz + } else if zd == 0.0 { + x - fx + } else { + ((x - x0) * xd + (z - z0) * zd) * 2.0 + }; + let mut out = [x0 + xd * progress, y0 + yd * progress, z0 + zd * progress]; + if yd < 0.0 { + out[1] += 1.0; + } else if yd > 0.0 { + out[1] += 0.5; + } + Some(out) + } + /// `OldMinecartBehavior.getPosOffs`. + fn rail_pos_offs(&self, mut x: f64, y: f64, mut z: f64, offs: f64) -> Option<[f64; 3]> { + let [xt, yt, zt] = self.rail_block(Vec3::new(x, y, z)); + let rail = self.rail(xt, yt, zt)?; + let mut y = f64::from(yt) + if rail.shape.is_slope() { 1.0 } else { 0.0 }; + let (e0, e1) = rail.shape.exits(); + let (mut xd, mut zd) = (f64::from(e1[0] - e0[0]), f64::from(e1[2] - e0[2])); + let dd = xd.hypot(zd); + xd /= dd; + zd /= dd; + x += xd * offs; + z += zd * offs; + let at = |e: [i32; 3]| x.floor() as i32 - xt == e[0] && z.floor() as i32 - zt == e[2]; + if e0[1] != 0 && at(e0) { + y += f64::from(e0[1]); + } else if e1[1] != 0 && at(e1) { + y += f64::from(e1[1]); + } + self.rail_pos(x, y, z) + } + /// Entity.move for a cart: collisions zero the blocked components. + fn move_cart(&self, c: &mut Minecart, delta: Vec3) { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + }; + if let Ok(moved) = scene.resolve(c.bounds(), delta, 0.0, c.on_ground) { + c.position = Vec3::new( + c.position.x + moved.x, + c.position.y + moved.y, + c.position.z + moved.z, + ); + c.on_ground = delta.y < 0.0 && moved.y > delta.y; + c.horizontal_collision = + (moved.x - delta.x).abs() > 1.0e-7 || (moved.z - delta.z).abs() > 1.0e-7; + if (moved.x - delta.x).abs() > 1.0e-7 { + c.velocity.x = 0.0; + } + if (moved.z - delta.z).abs() > 1.0e-7 { + c.velocity.z = 0.0; + } + if (moved.y - delta.y).abs() > 1.0e-7 { + c.velocity.y = 0.0; + } + if c.on_ground || moved.y >= 0.0 { + c.fall_distance = 0.0; + } else { + c.fall_distance -= moved.y; + } + } + } + fn max_speed(&self, c: &Minecart) -> f64 { + let base = if self.cart_in_water(c) { 0.2 } else { 0.4 }; + if c.kind == CartKind::Furnace { + base * if self.cart_in_water(c) { 0.75 } else { 0.5 } + } else { + base + } + } + /// `applyNaturalSlowdown` (with `MinecartFurnace`'s push). + fn natural_slowdown(&self, c: &mut Minecart, ridden: bool) -> Vec3 { + let mut v = c.velocity; + let water = self.cart_in_water(c); + if c.kind == CartKind::Furnace { + let push = c.push; + if push[0] * push[0] + push[1] * push[1] > 1.0e-7 { + // calculateNewPushAlong + let len = push[0].hypot(push[1]); + if len * len > 1.0e-4 && v.x * v.x + v.z * v.z > 0.001 { + let d = v.x * v.x + v.y * v.y + v.z * v.z; + let t = (push[0] * v.x + push[1] * v.z) / d; + let (px, py, pz) = (v.x * t, v.y * t, v.z * t); + let n = (px * px + py * py + pz * pz).sqrt(); + c.push = if n > 1.0e-4 { + [px / n * len, pz / n * len] + } else { + [0.0, 0.0] + }; + } + v = Vec3::new(v.x * 0.8 + c.push[0], 0.0, v.z * 0.8 + c.push[1]); + if water { + v = Vec3::new(v.x * 0.1, 0.0, v.z * 0.1); + } + } else { + v = Vec3::new(v.x * 0.98, 0.0, v.z * 0.98); + } + } + let f = if ridden { 0.997 } else { 0.96 }; + let mut out = Vec3::new(v.x * f, 0.0, v.z * f); + if water { + out = Vec3::new(out.x * 0.95, 0.0, out.z * 0.95); + } + out + } + /// `OldMinecartBehavior.moveAlongTrack`. + fn move_along_track(&mut self, c: &mut Minecart, pos: [i32; 3], rail: &Rail, intent: [f64; 2]) { + c.fall_distance = 0.0; + let ridden = Some(c.id) == self.riding; + let (x, z) = (c.position.x, c.position.z); + let old = self.rail_pos(x, c.position.y, z); + let mut y = f64::from(pos[1]); + let (mut power, mut halt) = (false, false); + if &*rail.name == "minecraft:powered_rail" { + power = rail.powered; + halt = !power; + } + let slide = if self.cart_in_water(c) { + 0.0078125 * 0.2 + } else { + 0.0078125 + }; + match rail.shape { + Shape::AscendingEast => c.velocity.x -= slide, + Shape::AscendingWest => c.velocity.x += slide, + Shape::AscendingNorth => c.velocity.z += slide, + Shape::AscendingSouth => c.velocity.z -= slide, + _ => {} + } + if rail.shape.is_slope() { + y += 1.0; + } + let (e0, e1) = rail.shape.exits(); + let (mut xd, mut zd) = (f64::from(e1[0] - e0[0]), f64::from(e1[2] - e0[2])); + let length = xd.hypot(zd); + if c.velocity.x * xd + c.velocity.z * zd < 0.0 { + xd = -xd; + zd = -zd; + } + let pow = c.horizontal().min(2.0); + c.velocity = Vec3::new(pow * xd / length, c.velocity.y, pow * zd / length); + if ridden + && (intent[0] != 0.0 || intent[1] != 0.0) + && c.velocity.x.powi(2) + c.velocity.z.powi(2) < 0.01 + { + c.velocity.x += intent[0] * 0.001; + c.velocity.z += intent[1] * 0.001; + halt = false; + } + if halt { + if c.horizontal() < 0.03 { + c.velocity = Vec3::ZERO; + } else { + c.velocity = Vec3::new(c.velocity.x * 0.5, 0.0, c.velocity.z * 0.5); + } + } + let (fx, fz) = (f64::from(pos[0]), f64::from(pos[2])); + let x0 = fx + 0.5 + f64::from(e0[0]) * 0.5; + let z0 = fz + 0.5 + f64::from(e0[2]) * 0.5; + let x1 = fx + 0.5 + f64::from(e1[0]) * 0.5; + let z1 = fz + 0.5 + f64::from(e1[2]) * 0.5; + let (xd, zd) = (x1 - x0, z1 - z0); + let progress = if xd == 0.0 { + z - fz + } else if zd == 0.0 { + x - fx + } else { + ((x - x0) * xd + (z - z0) * zd) * 2.0 + }; + c.position = Vec3::new(x0 + xd * progress, y, z0 + zd * progress); + let scale = if ridden { 0.75 } else { 1.0 }; + let max = self.max_speed(c); + let delta = Vec3::new( + (scale * c.velocity.x).clamp(-max, max), + 0.0, + (scale * c.velocity.z).clamp(-max, max), + ); + self.move_cart(c, delta); + let at = |e: [i32; 3], c: &Minecart| { + c.position.x.floor() as i32 - pos[0] == e[0] + && c.position.z.floor() as i32 - pos[2] == e[2] + }; + if e0[1] != 0 && at(e0, c) { + c.position.y += f64::from(e0[1]); + } else if e1[1] != 0 && at(e1, c) { + c.position.y += f64::from(e1[1]); + } + c.velocity = self.natural_slowdown(c, ridden); + if let (Some(new), Some(old)) = + (self.rail_pos(c.position.x, c.position.y, c.position.z), old) + { + let speed = (old[1] - new[1]) * 0.05; + let h = c.horizontal(); + if h > 0.0 { + c.velocity.x *= (h + speed) / h; + c.velocity.z *= (h + speed) / h; + } + c.position.y = new[1]; + } + let (xn, zn) = (c.position.x.floor() as i32, c.position.z.floor() as i32); + if xn != pos[0] || zn != pos[2] { + let h = c.horizontal(); + c.velocity = Vec3::new( + h * f64::from(xn - pos[0]), + c.velocity.y, + h * f64::from(zn - pos[2]), + ); + } + if power { + let h = c.horizontal(); + if h > 0.01 { + c.velocity.x += c.velocity.x / h * 0.06; + c.velocity.z += c.velocity.z / h * 0.06; + } else if rail.shape == Shape::EastWest { + if self.conductor(pos[0] - 1, pos[1], pos[2]) { + c.velocity.x = 0.02; + } else if self.conductor(pos[0] + 1, pos[1], pos[2]) { + c.velocity.x = -0.02; + } + } else if rail.shape == Shape::NorthSouth { + if self.conductor(pos[0], pos[1], pos[2] - 1) { + c.velocity.z = 0.02; + } else if self.conductor(pos[0], pos[1], pos[2] + 1) { + c.velocity.z = -0.02; + } + } + } + } + /// `comeOffTrack`. + fn come_off_track(&self, c: &mut Minecart) { + let max = self.max_speed(c); + c.velocity.x = c.velocity.x.clamp(-max, max); + c.velocity.z = c.velocity.z.clamp(-max, max); + if c.on_ground { + c.velocity = Vec3::new(c.velocity.x * 0.5, c.velocity.y * 0.5, c.velocity.z * 0.5); + } + let v = c.velocity; + let fall = c.fall_distance; + self.move_cart(c, v); + if !c.on_ground { + c.velocity = Vec3::new( + c.velocity.x * 0.95, + c.velocity.y * 0.95, + c.velocity.z * 0.95, + ); + } else if c.kind == CartKind::Tnt && fall >= 3.0 { + // MinecartTNT.causeFallDamage + c.fuse = 0; + c.velocity = Vec3::new(c.velocity.x, fall / 10.0, c.velocity.z); + } + } + /// `AbstractMinecart.tick` for one cart; returns false once it is gone. + fn tick_cart(&mut self, c: &mut Minecart, intent: [f64; 2]) -> bool { + c.previous = c.position; + c.previous_yaw = c.yaw; + c.hurt_time = (c.hurt_time - 1).max(0); + c.damage = (c.damage - 1.0).max(0.0); + // applyGravity + c.velocity.y -= if self.cart_in_water(c) { 0.005 } else { 0.04 }; + let pos = self.rail_block(c.position); + let fall_speed = c.velocity; + if let Some(rail) = self.rail(pos[0], pos[1], pos[2]) { + self.move_along_track(c, pos, &rail, intent); + if &*rail.name == "minecraft:activator_rail" { + self.activate_cart(c, rail.powered); + } + } else { + self.come_off_track(c); + } + // Yaw from the movement, flipped when it turns around. + let (xd, zd) = (c.previous.x - c.position.x, c.previous.z - c.position.z); + if xd * xd + zd * zd > 0.001 { + c.yaw = zd.atan2(xd).to_degrees() as f32; + if c.flipped { + c.yaw += 180.0; + } + } + let diff = (c.yaw - c.previous_yaw + 180.0).rem_euclid(360.0) - 180.0; + if !(-170.0..170.0).contains(&diff) { + c.yaw += 180.0; + c.flipped = !c.flipped; + } + c.yaw %= 360.0; + // Variants. + match c.kind { + CartKind::Furnace => { + if c.fuel > 0 { + c.fuel -= 1; + } + if c.fuel <= 0 { + c.push = [0.0; 2]; + } + if c.fuel > 0 && self.world.random.next_int_bound(4).unwrap_or(1) == 0 { + let at = [c.position.x, c.position.y + 0.8, c.position.z]; + self.particles.add( + &ParticleOptions::simple(ParticleType::LargeSmoke), + at, + [0.0; 3], + ); + } + } + CartKind::Tnt => { + let speed = fall_speed.x * fall_speed.x + fall_speed.z * fall_speed.z; + if c.fuse > 0 { + c.fuse -= 1; + let at = [c.position.x, c.position.y + 0.5, c.position.z]; + self.particles + .add(&ParticleOptions::simple(ParticleType::Smoke), at, [0.0; 3]); + } else if c.fuse == 0 || (c.horizontal_collision && speed >= 0.01) { + let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; + let speed = if c.fuse == 0 && c.velocity.y > 0.0 { + c.velocity.y * c.velocity.y + } else { + speed + }; + self.explode_cart(c, speed); + return false; + } + } + _ => {} + } + true + } + /// `activateMinecart` on an activator rail. + fn activate_cart(&mut self, c: &mut Minecart, powered: bool) { + match c.kind { + CartKind::Rideable if powered => { + if self.riding == Some(c.id) { + self.riding = None; + } + if c.hurt_time == 0 { + c.hurt_dir = -c.hurt_dir; + c.hurt_time = 10; + c.damage = 50.0; + } + } + CartKind::Tnt if powered && c.fuse < 0 => self.prime_cart(c), + CartKind::Hopper => c.enabled = !powered, + _ => {} + } + } + fn prime_cart(&mut self, c: &mut Minecart) { + if !self.ui.rules.bool("tnt_explodes") { + return; + } + c.fuse = 80; + let at = [c.position.x, c.position.y, c.position.z]; + self.audio + .play("minecraft:entity.tnt.primed", Some(at), 1.0, 1.0); + } + fn explode_cart(&mut self, c: &Minecart, speed_sqr: f64) { + if !self.ui.rules.bool("tnt_explodes") { + return; + } + let speed = speed_sqr.sqrt().min(5.0); + let r = self.world.random.next_double(); + let power = (4.0 + r * 1.5 * speed) as f32; + let at = [c.position.x, c.position.y, c.position.z]; + let _ = self.server_explode(at, power, BlockInteraction::Destroy, false); + } + /// `MinecartHopper.suckInItems`: items above, into the five slots. + fn hopper_cart_pickup(&mut self, c: &mut Minecart) { + if !c.enabled { + return; + } + let p = c.position; + let zone = Aabb::new( + Vec3::new(p.x - 0.5, p.y - 0.5 + 0.0, p.z - 0.5), + Vec3::new(p.x + 0.5, p.y + 1.5, p.z + 0.5), + ); + let mut i = 0; + while i < self.dropped.len() { + let e = &self.dropped[i]; + if e.pickup_delay > 0 || !zone.contains(e.position) { + i += 1; + continue; + } + let mut stack = e.stack.clone(); + for slot in c.items.iter_mut() { + match slot { + None => { + *slot = Some(stack.clone()); + stack.count = 0; + } + Some(s) if s.same_item_same_components(&stack) => { + let max = self.res.items.get(&s.item).map_or(64, |i| i.max_stack); + let moved = stack.count.min(max.saturating_sub(s.count)); + s.count += moved; + stack.count -= moved; + } + _ => {} + } + if stack.count == 0 { + break; + } + } + if stack.count == 0 { + self.dropped.remove(i); + } else { + self.dropped[i].stack = stack; + i += 1; + } + } + } + /// `AbstractMinecart.push(player)` when the player walks into a cart, + /// and carts pushing each other (`pushOtherMinecart`). + fn push_carts(&mut self) { + let player = self.player.as_ref().map(|p| p.position); + let riding = self.riding; + for i in 0..self.carts.len() { + if Some(self.carts[i].id) == riding { + continue; + } + if let Some(pp) = player { + let bb = self.carts[i].bounds(); + let (lo, hi) = (bb.min_position(), bb.max_position()); + let touching = pp.x + 0.3 > lo.x + && pp.x - 0.3 < hi.x + && pp.z + 0.3 > lo.z + && pp.z - 0.3 < hi.z + && pp.y + 1.8 > lo.y + && pp.y < hi.y; + if touching && riding.is_none() { + let c = &mut self.carts[i]; + let (mut xa, mut za) = (pp.x - c.position.x, pp.z - c.position.z); + let dd = xa * xa + za * za; + if dd >= 1.0e-4 { + let d = dd.sqrt(); + let pow = (1.0 / d).min(1.0); + xa = xa / d * pow * f64::from(0.1f32) * 0.5; + za = za / d * pow * f64::from(0.1f32) * 0.5; + c.velocity.x -= xa; + c.velocity.z -= za; + if let Some(p) = self.player.as_mut() { + p.velocity.x += xa / 4.0; + p.velocity.z += za / 4.0; + } + } + } + } + for j in i + 1..self.carts.len() { + let (a, b) = (&self.carts[i], &self.carts[j]); + if !a + .bounds() + .inflate(Vec3::new(0.2, 0.0, 0.2)) + .intersects(b.bounds()) + { + continue; + } + let (mut xa, mut za) = (b.position.x - a.position.x, b.position.z - a.position.z); + let dd = xa * xa + za * za; + if dd < 1.0e-4 { + continue; + } + let d = dd.sqrt(); + let pow = (1.0 / d).min(1.0); + xa = xa / d * pow * f64::from(0.1f32) * 0.5; + za = za / d * pow * f64::from(0.1f32) * 0.5; + let dir = + glam::DVec2::new(b.position.x - a.position.x, b.position.z - a.position.z) + .normalize_or_zero(); + let r = a.yaw.to_radians(); + let facing = + glam::DVec2::new(f64::from(r.cos()), f64::from(r.sin())).normalize_or_zero(); + if dir.dot(facing).abs() < f64::from(0.8f32) { + continue; + } + let (ma, mb) = (a.velocity, b.velocity); + let (fa, fb) = (a.kind == CartKind::Furnace, b.kind == CartKind::Furnace); + let (na, nb) = if fb && !fa { + ( + Vec3::new(ma.x * 0.2 + mb.x - xa, ma.y, ma.z * 0.2 + mb.z - za), + Vec3::new(mb.x * 0.95, mb.y, mb.z * 0.95), + ) + } else if fa && !fb { + ( + Vec3::new(ma.x * 0.95, ma.y, ma.z * 0.95), + Vec3::new(mb.x * 0.2 + ma.x + xa, mb.y, mb.z * 0.2 + ma.z + za), + ) + } else { + let (xdd, zdd) = ((mb.x + ma.x) / 2.0, (mb.z + ma.z) / 2.0); + ( + Vec3::new(ma.x * 0.2 + xdd - xa, ma.y, ma.z * 0.2 + zdd - za), + Vec3::new(mb.x * 0.2 + xdd + xa, mb.y, mb.z * 0.2 + zdd + za), + ) + }; + self.carts[i].velocity = na; + self.carts[j].velocity = nb; + } + } + } + /// Every cart but the ridden one (which ticks with its rider). + pub(super) fn tick_carts(&mut self) { + self.push_carts(); + let mut i = 0; + while i < self.carts.len() { + if Some(self.carts[i].id) == self.riding { + i += 1; + continue; + } + let mut c = self.carts[i].clone(); + let alive = self.tick_cart(&mut c, [0.0; 2]); + if c.kind == CartKind::Hopper { + self.hopper_cart_pickup(&mut c); + } + if alive { + self.carts[i] = c; + i += 1; + } else { + self.carts.remove(i); + } + } + } + /// The rider's tick: the cart moves with the rider's input as its push. + pub(super) fn tick_cart_riding(&mut self, keys: Keys) -> bool { + let Some(i) = self.carts.iter().position(|c| Some(c.id) == self.riding) else { + return false; + }; + if keys.shift { + self.dismount_cart(i); + return true; + } + // ServerPlayer.getLastClientMoveIntent: getInputVector((left, 0, forward), 1, yRot). + let left = f64::from(i8::from(keys.left) - i8::from(keys.right)); + let forward = f64::from(i8::from(keys.forward) - i8::from(keys.backward)); + let len = left.hypot(forward); + let (left, forward) = if len > 1.0 { + (left / len, forward / len) + } else { + (left, forward) + }; + let r = self.yaw.to_radians(); + let (s, co) = (f64::from(r.sin()), f64::from(r.cos())); + let intent = [left * co - forward * s, forward * co + left * s]; + let mut c = self.carts[i].clone(); + let alive = self.tick_cart(&mut c, intent); + if let Some(p) = self.player.as_mut() { + self.previous_position = p.position; + p.position = Vec3::new(c.position.x, c.position.y + SEAT, c.position.z); + p.velocity = Vec3::ZERO; + p.fall_distance = 0.0; + } + if alive { + self.carts[i] = c; + } else { + self.carts.remove(i); + self.riding = None; + } + true + } + /// `getDismountLocationForPassenger`: beside the cart (across its motion), else on top. + fn dismount_cart(&mut self, i: usize) { + self.riding = None; + let c = &self.carts[i]; + let (bx, by, bz) = ( + c.position.x.floor() as i32, + c.position.y.floor() as i32, + c.position.z.floor() as i32, + ); + let mut target = None; + 'search: for dy in [0, 1, -1] { + for (dx, dz) in [ + (1, 0), + (-1, 0), + (0, 1), + (0, -1), + (1, 1), + (-1, -1), + (1, -1), + (-1, 1), + ] { + let (x, y, z) = (bx + dx, by + dy, bz + dz); + let below = self.res.facts.get(self.world.block(x, y - 1, z)); + let here = self.res.facts.get(self.world.block(x, y, z)); + let head = self.res.facts.get(self.world.block(x, y + 1, z)); + if (below.full_collision || below.legacy_solid) + && !here.full_collision + && !head.full_collision + && here.fluid == Fluid::None + { + target = Some(Vec3::new( + f64::from(x) + 0.5, + f64::from(y), + f64::from(z) + 0.5, + )); + break 'search; + } + } + } + let top = c.bounds().max_position().y; + let target = target.unwrap_or(Vec3::new(c.position.x, top, c.position.z)); + if let Some(p) = self.player.as_mut() { + p.position = target; + p.velocity = Vec3::ZERO; + } + } + /// `MinecartItem.useOn`: a cart on the clicked rail. + pub(super) fn place_minecart(&mut self, hit: &Hit, stack: &ItemStack) -> bool { + let Some(kind) = CartKind::from_id(&stack.item) else { + return false; + }; + let Some(rail) = self.rail(hit.pos[0], hit.pos[1], hit.pos[2]) else { + return false; + }; + let offset = if rail.shape.is_slope() { 0.5 } else { 0.0 }; + let at = Vec3::new( + f64::from(hit.pos[0]) + 0.5, + f64::from(hit.pos[1]) + 0.0625 + offset, + f64::from(hit.pos[2]) + 0.5, + ); + self.next_entity += 1; + let cart = Minecart::new(self.next_entity, kind, at); + self.world + .modified + .insert((hit.pos[0] >> 4, hit.pos[2] >> 4)); + self.carts.push(cart); + if !self.creative { + self.consume_held(); + } + self.swing_arm(); + true + } + fn cart_hit(&self) -> Option<(usize, f64)> { + let eye = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach: f64 = if self.creative { 5.0 } else { 3.0 }; + let mut best: Option<(usize, f64)> = None; + for (i, c) in self.carts.iter().enumerate() { + if Some(c.id) == self.riding { + continue; + } + let bb = c.bounds(); + let (lo, hi) = (bb.min_position(), bb.max_position()); + let (lo, hi) = ([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]); + let (mut t0, mut t1) = (0.0f64, reach); + let mut hit = true; + for a in 0..3 { + if dir[a].abs() < 1e-9 { + hit &= eye[a] >= lo[a] && eye[a] <= hi[a]; + continue; + } + let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]); + if ta > tb { + std::mem::swap(&mut ta, &mut tb); + } + t0 = t0.max(ta); + t1 = t1.min(tb); + } + if hit && t0 <= t1 && best.is_none_or(|b| t0 < b.1) { + best = Some((i, t0)); + } + } + best + } + /// `interact`: ride, open, fuel or ignite the cart under the crosshair. + pub(super) fn interact_cart(&mut self) -> bool { + let Some((i, d)) = self.cart_hit() else { + return false; + }; + if !self.before_block(d) { + return false; + } + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); + let held = self.held().cloned(); + match self.carts[i].kind { + CartKind::Rideable => { + if sneaking || self.riding.is_some() { + return false; + } + self.riding = Some(self.carts[i].id); + } + CartKind::Chest | CartKind::Hopper => { + if sneaking { + return false; + } + let c = self.carts[i].clone(); + let key = (i32::MAX - 15, CART_KEY_Y, c.id as i32); + self.world + .block_entities + .insert(key, BlockEntity::Chest(c.items.clone())); + self.container = Some(key); + self.screen = super::Screen::Inventory; + self.capture(false); + self.right = false; + if c.kind == CartKind::Chest { + let at = [c.position.x, c.position.y, c.position.z]; + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio + .play("minecraft:block.chest.open", Some(at), 0.5, pitch); + } + } + CartKind::Furnace => { + let fuel = held + .as_ref() + .is_some_and(|s| matches!(&*s.item, "minecraft:coal" | "minecraft:charcoal")); + let c = &mut self.carts[i]; + if fuel && c.fuel + 3600 <= 32000 { + c.fuel += 3600; + let p = self.player.as_ref().map_or(c.position, |p| p.position); + c.push = [c.position.x - p.x, c.position.z - p.z]; + if !self.creative { + self.consume_held(); + } + } + } + CartKind::Tnt => { + let lighter = held.as_ref().is_some_and(|s| { + matches!( + &*s.item, + "minecraft:flint_and_steel" | "minecraft:fire_charge" + ) + }); + if !lighter || self.carts[i].fuse >= 0 { + return false; + } + let mut c = self.carts[i].clone(); + self.prime_cart(&mut c); + self.carts[i] = c; + } + } + self.swing_arm(); + true + } + /// Closing a cart's container copies the items back. + pub(super) fn close_cart_container(&mut self) { + let Some(key) = self.container.filter(|k| k.1 == CART_KEY_Y) else { + return; + }; + if let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) + && let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) + { + c.items = items; + let at = [c.position.x, c.position.y, c.position.z]; + if c.kind == CartKind::Chest { + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio + .play("minecraft:block.chest.close", Some(at), 0.5, pitch); + } + } + } + /// The open cart's kind when a cart container is shown. + pub(super) fn open_cart_kind(&self) -> Option { + let key = self.container.filter(|k| k.1 == CART_KEY_Y)?; + self.carts + .iter() + .find(|c| c.id as i32 == key.2) + .map(|c| c.kind) + } + /// `VehicleEntity.hurtServer` from the player's attack. + pub(super) fn attack_cart(&mut self, damage: f32) -> bool { + let Some((i, d)) = self.cart_hit() else { + return false; + }; + if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) { + return false; + } + let c = &mut self.carts[i]; + c.hurt_dir = -c.hurt_dir; + c.hurt_time = 10; + c.damage += damage * 10.0; + let destroyed = self.creative || c.damage > 40.0; + if destroyed { + let mut c = self.carts.remove(i); + let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; + let burning = self + .held() + .is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0); + if c.kind == CartKind::Tnt && (burning || speed >= 0.01) { + // MinecartTNT.destroy: prime instead of breaking. + if c.fuse < 0 { + self.prime_cart(&mut c); + let r = &mut self.world.random; + c.fuse = r.next_int_bound(20).unwrap_or(0) + r.next_int_bound(20).unwrap_or(0); + } + self.carts.insert(i, c); + } else { + let at = [c.position.x, c.position.y, c.position.z]; + if self.ui.rules.bool("entity_drops") { + for s in c.items.iter().flatten() { + self.spawn_item(s.clone(), at, [0.0, 0.1, 0.0], 10); + } + if !self.creative { + self.spawn_item(ItemStack::new(c.kind.id(), 1), at, [0.0, 0.1, 0.0], 10); + } + } + } + } + self.swing_arm(); + true + } + /// A block model's faces under `m` (block space 0..1), lit flat. + fn block_model_vertices( + &self, + state: BlockStateId, + m: glam::Mat4, + light: u32, + out: &mut Vec, + ) { + let Ok(models) = self + .res + .assets + .model_catalog + .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) + else { + return; + }; + for (_, model) in &models { + for face in &model.faces { + let Some(s) = self + .res + .layer_names + .get(&face.layer) + .and_then(|n| self.res.atlas.sprites.get(n)) + else { + continue; + }; + use horizon_assets::model::Direction as D; + let shade: u32 = match face.quad.facing { + D::Up => 255, + D::Down => 127, + D::North | D::South => 204, + D::West | D::East => 153, + }; + let color = 0xFF00_0000 | shade << 16 | shade << 8 | shade; + for k in 0..4 { + let p = face.quad.positions[k]; + let uv = face.quad.uv[k]; + out.push(Vertex { + pos: m.transform_point3(glam::Vec3::from_array(p)).to_array(), + uv: [s.u0 + uv[0] * (s.u1 - s.u0), s.v0 + uv[1] * (s.v1 - s.v0)], + layer: 0, + color, + light, + }); + } + } + } + } + fn display_state(&self, c: &Minecart) -> Option { + let registry = &self.res.assets.registry; + let with = |name: &str, props: &[(&str, &str)]| { + let mut s = registry.state(registry.default_state(name)?)?.clone(); + for (k, v) in props { + s.properties.insert((*k).to_owned(), (*v).to_owned()); + } + registry.id(&s) + }; + match c.kind { + CartKind::Rideable => None, + CartKind::Chest => with("minecraft:chest", &[("facing", "north")]), + CartKind::Hopper => registry.default_state("minecraft:hopper"), + CartKind::Furnace => with( + "minecraft:furnace", + &[ + ("facing", "north"), + ("lit", if c.fuel > 0 { "true" } else { "false" }), + ], + ), + CartKind::Tnt => registry.default_state("minecraft:tnt"), + } + } + /// `AbstractMinecartRenderer` (old render): on the rail between the + /// front and back points, pitched on slopes, with the display block. + pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { + let a = alpha as f32; + for c in &self.carts { + let Some(model) = self.cart_models.models.get(&c.kind) else { + continue; + }; + let Some(uv) = self + .res + .atlas + .sprites + .get("entity/minecart/minecart") + .map(|r| [r.u0, r.v0, r.u1, r.v1]) + else { + continue; + }; + let (x, y, z) = ( + c.previous.x + (c.position.x - c.previous.x) * alpha, + c.previous.y + (c.position.y - c.previous.y) * alpha, + c.previous.z + (c.position.z - c.previous.z) * alpha, + ); + let mut yaw = + c.previous_yaw + ((c.yaw - c.previous_yaw + 180.0).rem_euclid(360.0) - 180.0) * a; + let mut pitch = 0.0f32; + let mut offset = glam::DVec3::ZERO; + if let Some(on) = self.rail_pos(x, y, z) { + let front = self.rail_pos_offs(x, y, z, 0.3).unwrap_or(on); + let back = self.rail_pos_offs(x, y, z, -0.3).unwrap_or(on); + offset = glam::DVec3::new(on[0] - x, (front[1] + back[1]) / 2.0 - y, on[2] - z); + let d = + glam::DVec3::new(back[0] - front[0], back[1] - front[1], back[2] - front[2]); + if d.length() != 0.0 { + let d = d.normalize(); + yaw = d.z.atan2(d.x).to_degrees() as f32; + pitch = (d.y.atan() * 73.0) as f32; + } + } + // The per-entity jitter (offsetSeed) that keeps stacked carts from z-fighting. + let seed = i64::from(c.id).wrapping_mul(493_286_711); + let seed = seed + .wrapping_mul(seed) + .wrapping_mul(4_392_167_121) + .wrapping_add(seed.wrapping_mul(98_761)); + let jitter = |shift: i64| (((seed >> shift & 7) as f32 + 0.5) / 8.0 - 0.5) * 0.004; + let p = glam::DVec3::new(x, y, z) + offset - camera; + let mut base = glam::Mat4::from_translation( + p.as_vec3() + glam::Vec3::new(jitter(16), jitter(20) + 0.375, jitter(24)), + ) * glam::Mat4::from_rotation_y((180.0 - yaw).to_radians()) + * glam::Mat4::from_rotation_z((-pitch).to_radians()); + let hurt = c.hurt_time as f32 - a; + if hurt > 0.0 { + let damage = (c.damage - a).max(0.0); + base *= glam::Mat4::from_rotation_x( + (hurt.sin() * hurt * damage / 10.0 * c.hurt_dir as f32).to_radians(), + ); + } + let l = self.world.light( + c.position.x.floor() as i32, + (c.position.y + 0.35).floor() as i32, + c.position.z.floor() as i32, + ); + let packed = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8); + if let Some(state) = self.display_state(c) { + let display = base + * glam::Mat4::from_scale(glam::Vec3::splat(0.75)) + * glam::Mat4::from_translation(glam::Vec3::new(-0.5, (6.0 - 8.0) / 16.0, 0.5)) + * glam::Mat4::from_rotation_y(90f32.to_radians()); + if c.kind == CartKind::Chest { + self.cart_chest(state, display, l, out); + } else { + // TNT minecarts flash white as the fuse runs out (TntMinecartRenderer). + let swell = if c.kind == CartKind::Tnt && c.fuse > -1 { + let fuse = c.fuse as f32 - a + 1.0; + if fuse < 10.0 { + let g = (1.0 - fuse / 10.0).clamp(0.0, 1.0); + 1.0 + g * g * g * g * 0.3 + } else { + 1.0 + } + } else { + 1.0 + }; + let m = display + * glam::Mat4::from_translation(glam::Vec3::splat(0.5)) + * glam::Mat4::from_scale(glam::Vec3::splat(swell)) + * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); + let flash = c.kind == CartKind::Tnt && c.fuse > -1 && (c.fuse / 5) % 2 == 0; + let start = out.len(); + self.block_model_vertices(state, m, packed, out); + if flash { + for v in &mut out[start..] { + v.color = 0xFFFF_FFFF; + v.light = 240 | 240 << 8; + } + } + } + } + let m = base * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); + let poses = Poses::new(model); + horizon_client::mobs::render::draw(model, m, &poses, uv, 0xFFFF_FFFF, packed, 0, out); + } + } + /// The chest inside a chest minecart, drawn by the chest block-entity renderer. + fn cart_chest(&self, state: BlockStateId, m: glam::Mat4, light: u8, out: &mut Vec) { + let lid = |_: [i32; 3]| 0.0; + let scene = horizon_client::block_entity_render::Scene { + camera: glam::DVec3::ZERO, + partial: 0.0, + game_time: self.world.game_time, + world: &self.world, + sprites: &self.res.atlas.sprites, + nether: self.dim == super::Dim::Nether, + lid: &lid, + sign: &|_| None, + glyph: &|c| self.res.atlas.glyph(c), + }; + self.res + .block_entity_render + .render_state(&scene, state.0, m, light, out); + } +} +/// Saving and loading. +impl Minecart { + pub fn to_nbt( + &self, + uuid: [i32; 4], + raw: Option<&horizon_world::nbt::Tag>, + ) -> horizon_world::nbt::Tag { + use horizon_world::nbt::{JavaString, Tag}; + let mut tag = horizon_client::entity_nbt::vehicle_to_nbt( + self.kind.id(), + self.position, + self.velocity, + self.yaw, + uuid, + raw, + ); + if let Tag::Compound(map) = &mut tag { + let mut put = |k: &str, v: Tag| { + map.insert(JavaString::from(k), v); + }; + put("FlippedRotation", Tag::Byte(i8::from(self.flipped))); + match self.kind { + CartKind::Chest | CartKind::Hopper => { + put("Items", horizon_client::save::encode_items(&self.items)); + if self.kind == CartKind::Hopper { + put("Enabled", Tag::Byte(i8::from(self.enabled))); + } + } + CartKind::Furnace => { + put("PushX", Tag::Double(self.push[0].to_bits())); + put("PushZ", Tag::Double(self.push[1].to_bits())); + put("Fuel", Tag::Short(self.fuel as i16)); + } + CartKind::Tnt => put("fuse", Tag::Int(self.fuse)), + CartKind::Rideable => {} + } + } + tag + } + pub fn from_nbt(tag: &horizon_world::nbt::Tag, id: u32, kind: CartKind) -> Option { + use horizon_world::nbt::Tag; + let (position, velocity, yaw) = horizon_client::entity_nbt::boat_from_nbt(tag)?; + let mut c = Self::new(id, kind, position); + c.velocity = velocity; + c.yaw = yaw; + c.previous_yaw = yaw; + let int = |k: &str| match tag.get(k) { + Some(Tag::Byte(v)) => Some(i32::from(*v)), + Some(Tag::Short(v)) => Some(i32::from(*v)), + Some(Tag::Int(v)) => Some(*v), + _ => None, + }; + let double = |k: &str| match tag.get(k) { + Some(Tag::Double(v)) => f64::from_bits(*v), + _ => 0.0, + }; + c.flipped = int("FlippedRotation").unwrap_or(0) != 0; + if kind.slots() > 0 { + c.items = horizon_client::save::decode_items(tag.get("Items"), kind.slots()); + } + c.enabled = int("Enabled").unwrap_or(1) != 0; + c.fuel = int("Fuel").unwrap_or(0); + c.push = [double("PushX"), double("PushZ")]; + c.fuse = int("fuse").unwrap_or(-1); + Some(c) + } +} diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs new file mode 100644 index 000000000..14a6220cf --- /dev/null +++ b/crates/horizon-client/src/game/names.rs @@ -0,0 +1,112 @@ +//! Custom names: `NameTagItem.interactLivingEntity` and the name tag +//! (`EntityRenderer.submitNameTag`): above the head, facing the camera, +//! on a translucent black background, shown when the name is visible or the +//! mob is under the crosshair within 64 blocks. +use super::{Game, view_vector}; +use horizon_client::mesher::Vertex; + +impl Game<'_> { + /// A named name tag names the mob under the crosshair. + pub(super) fn name_mob(&mut self, index: usize) -> bool { + let Some(name) = self + .held() + .filter(|h| &*h.item == "minecraft:name_tag") + .and_then(|h| h.custom_name().map(str::to_owned)) + else { + return false; + }; + let m = &mut self.mobs[index]; + if !m.alive() { + return false; + } + m.custom_name = Some(name); + m.persistent = true; + // itemStack.shrink(1), in creative too. + self.consume_held(); + self.swing_arm(); + true + } + pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { + let target = self.mob_hit().map(|(i, _)| self.mobs[i].id); + let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); + let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); + let up = right.cross(forward).normalize_or_zero(); + let white = self.res.atlas.font.white(); + for m in &self.mobs { + let Some(name) = m.custom_name.as_deref() else { + continue; + }; + if !(m.name_visible || Some(m.id) == target) || !m.alive() { + continue; + } + let p = glam::DVec3::new( + m.previous.x + (m.position.x - m.previous.x) * alpha, + m.previous.y + (m.position.y - m.previous.y) * alpha + f64::from(m.height()) + 0.5, + m.previous.z + (m.position.z - m.previous.z) * alpha, + ); + if p.distance_squared(camera) >= 64.0 * 64.0 { + continue; + } + let o = (p - camera).as_vec3(); + let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025); + // Text space: x right, y down (scale 0.025, -0.025). + let at = |x: f32, y: f32| o + r * x - u * y; + let width: f32 = name + .chars() + .map(|c| self.res.atlas.glyph(c).map_or(6.0, |g| g.1)) + .sum(); + let x0 = -(width / 2.0).trunc(); + let y0 = if name == "deadmau5" { -10.0 } else { 0.0 }; + let l = self.world.light( + m.position.x.floor() as i32, + (m.position.y + f64::from(m.height())).floor() as i32, + m.position.z.floor() as i32, + ); + let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8); + let away = forward.as_vec3() * 0.002; + // `background`: unlit (vertex colour only) and a hair behind the text. + let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, background: bool| { + let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])]; + let uvs = [ + [uv[0], uv[3]], + [uv[2], uv[3]], + [uv[2], uv[1]], + [uv[0], uv[1]], + ]; + for ((x, y), uv) in corners.into_iter().zip(uvs) { + out.push(Vertex { + pos: (at(x, y) + if background { away } else { glam::Vec3::ZERO }) + .to_array(), + uv, + layer: if background { 2 } else { 0 }, + color, + light, + }); + } + }; + // Background: Options.getBackgroundOpacity(0.25) black. + quad( + [x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0], + [white.u0, white.v0, white.u1, white.v1], + 0x40_00_00_00, + true, + ); + let mut x = x0; + for ch in name.chars() { + let Some((g, advance)) = self.res.atlas.glyph(ch) else { + x += 6.0; + continue; + }; + if ch != ' ' { + quad( + [x, y0, x + 8.0, y0 + 8.0], + [g.u0, g.v0, g.u1, g.v1], + 0xFFFF_FFFF, + false, + ); + } + x += advance; + } + } + } +} diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 798cb6949..1bb215903 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -147,6 +147,15 @@ impl Game<'_> { self.boats.push(b); } } + k if super::minecarts::CartKind::from_id(k).is_some() => { + let kind = super::minecarts::CartKind::from_id(k).unwrap(); + let id = self.next_entity + 1; + if let Some(c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) { + self.next_entity = id; + self.remember(id, uuid, tag); + self.carts.push(c); + } + } "minecraft:armor_stand" => { self.next_entity += 1; if let Some(a) = entity_nbt::armor_stand_from_nbt(&tag, self.next_entity) { @@ -317,6 +326,18 @@ impl Game<'_> { out.entry(chunk_of(b.position)).or_default().push(tag); } } + for c in &self.carts { + if keys.contains(&chunk_of(c.position)) { + let uuid = self + .persist + .uuids + .get(&c.id) + .copied() + .unwrap_or_else(random_uuid); + let tag = c.to_nbt(uuid, self.persist.raw.get(&c.id)); + out.entry(chunk_of(c.position)).or_default().push(tag); + } + } for a in &self.armor_stands { if keys.contains(&chunk_of(a.position)) { let uuid = self @@ -381,6 +402,13 @@ impl Game<'_> { } keep }); + self.carts.retain(|c| { + let keep = !gone(c.position) || Some(c.id) == riding; + if !keep { + removed.push(c.id); + } + keep + }); self.armor_stands.retain(|a| { let keep = !gone(a.position); if !keep { diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index 96df13067..57fe9dbd5 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -15,6 +15,8 @@ pub(super) struct Titles { pub fade_out: i32, pub overlay: Option, pub overlay_time: i32, + /// `animateOverlayMessageColor`: the "Now Playing" rainbow. + pub overlay_animated: bool, } impl Default for Titles { fn default() -> Self { @@ -27,6 +29,7 @@ impl Default for Titles { fade_out: 20, overlay: None, overlay_time: 0, + overlay_animated: false, } } } @@ -60,6 +63,7 @@ impl Titles { pub fn set_overlay(&mut self, text: Text) { self.overlay = Some(text); self.overlay_time = 60; + self.overlay_animated = false; } /// Gui.tick. pub fn tick(&mut self) { @@ -88,7 +92,12 @@ impl Game<'_> { let alpha = ((ticks * 255.0 / 20.0) as i32).min(255); if alpha > 0 { let width = atlas.font.width_text(text); - let color = rgba(255, 255, 255, alpha as u8); + let color = if t.overlay_animated { + let [r, g, b] = hsv_to_rgb(ticks / 50.0, 0.7, 0.6); + rgba(r, g, b, alpha as u8) + } else { + rgba(255, 255, 255, alpha as u8) + }; batch.text_posed( atlas, text, @@ -140,3 +149,21 @@ impl Game<'_> { } } } +/// `Mth.hsvToRgb`. +fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> [u8; 3] { + let h = (hue * 6.0) as i32 % 6; + let f = hue * 6.0 - (hue * 6.0).floor(); + let p = value * (1.0 - saturation); + let q = value * (1.0 - f * saturation); + let t = value * (1.0 - (1.0 - f) * saturation); + let (r, g, b) = match h { + 0 => (value, t, p), + 1 => (q, value, p), + 2 => (p, value, t), + 3 => (p, q, value), + 4 => (t, p, value), + _ => (value, p, q), + }; + let c = |v: f32| (v * 255.0).clamp(0.0, 255.0) as u8; + [c(r), c(g), c(b)] +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 1e2d907a8..336715c7a 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -33,6 +33,8 @@ struct SectionGpu { solid: u32, translucent: u32, } +/// Line segments the hit outline can hold. +const MAX_OUTLINE_EDGES: u64 = 256; pub struct Frame<'a> { pub camera: DVec3, pub yaw: f32, @@ -60,7 +62,8 @@ pub struct Frame<'a> { pub fog: Option, /// Camera eye below the horizon height and not under water (`shouldRenderDarkDisc`). pub dark_disc: bool, - pub outline: Option<[f64; 6]>, + /// The hit block outline as line segments (from, to) in world space. + pub outline: Vec<[f64; 6]>, pub hud: &'a HudBatch, /// Camera-relative entity geometry textured from the shared atlas. pub entities: &'a [Vertex], @@ -514,7 +517,7 @@ impl Renderer { }); let outline = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Outline"), - size: 24 * 12, + size: 24 * MAX_OUTLINE_EDGES, usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -1277,39 +1280,33 @@ impl Renderer { self.queue .write_buffer(&self.instances, 0, bytemuck::cast_slice(&origins)); } - if let Some(b) = frame.outline { - let o = [ - (b[0] - camera.x) as f32 - 0.002, - (b[1] - camera.y) as f32 - 0.002, - (b[2] - camera.z) as f32 - 0.002, - ]; - let e = [ - (b[3] - camera.x) as f32 + 0.002, - (b[4] - camera.y) as f32 + 0.002, - (b[5] - camera.z) as f32 + 0.002, - ]; - let c = |i: usize| -> [f32; 3] { - [ - if i & 1 == 0 { o[0] } else { e[0] }, - if i & 2 == 0 { o[1] } else { e[1] }, - if i & 4 == 0 { o[2] } else { e[2] }, - ] - }; - let edges = [ - (0, 1), - (2, 3), - (4, 5), - (6, 7), - (0, 2), - (1, 3), - (4, 6), - (5, 7), - (0, 4), - (1, 5), - (2, 6), - (3, 7), - ]; - let lines: Vec<[f32; 3]> = edges.iter().flat_map(|&(a, b)| [c(a), c(b)]).collect(); + let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize); + if outline_edges > 0 { + // A hair outside the block, like vanilla's line depth offset. + let lines: Vec<[f32; 3]> = frame.outline[..outline_edges] + .iter() + .flat_map(|e| { + let center = [ + (e[0] + e[3]) / 2.0, + (e[1] + e[4]) / 2.0, + (e[2] + e[5]) / 2.0, + ]; + let point = |i: usize| -> [f32; 3] { + std::array::from_fn(|a| { + let v = e[i + a]; + let grow = if v < center[a] { + -0.002 + } else if v > center[a] { + 0.002 + } else { + 0.0 + }; + (v - [camera.x, camera.y, camera.z][a]) as f32 + grow + }) + }; + [point(0), point(3)] + }) + .collect(); self.queue .write_buffer(&self.outline, 0, bytemuck::cast_slice(&lines)); } @@ -1440,10 +1437,10 @@ impl Renderer { pass.draw_indexed(0..entity_quads * 6, 0, 0..1); pass.set_bind_group(0, &self.group, &[]); } - if frame.outline.is_some() { + if outline_edges > 0 { pass.set_pipeline(&self.lines); pass.set_vertex_buffer(0, self.outline.slice(..)); - pass.draw(0..24, 0..1); + pass.draw(0..outline_edges as u32 * 2, 0..1); } pass.set_pipeline(&self.translucent); pass.set_vertex_buffer(1, self.instances.slice(..)); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 4494b8148..eff648db2 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -54,6 +54,8 @@ pub struct ItemInfo { /// `equippable.swappable` and `equip_sound`. pub swappable: bool, pub equip_sound: Option, + /// `jukebox_playable`: the jukebox song it plays. + pub jukebox_song: Option, } /// A reduction of `blocks_attacks.damage_reductions`. #[derive(Clone, Debug)] @@ -144,6 +146,53 @@ pub struct Items { pub block_tags: HashMap>, pub item_tags: HashMap>, loot: HashMap, + /// The `jukebox_song` registry. + pub songs: HashMap, +} +/// A `JukeboxSong`. +#[derive(Clone, Debug)] +pub struct Song { + pub sound: String, + pub length_ticks: i64, + pub comparator: i32, + pub description: Value, +} +impl Song { + /// `hasFinished`: the length plus one second. + pub fn finished(&self, ticks: i64) -> bool { + ticks >= self.length_ticks + 20 + } +} +fn load_songs(root: &Path) -> HashMap { + let mut songs = HashMap::new(); + let Ok(dir) = fs::read_dir(root.join("data/minecraft/jukebox_song")) else { + return songs; + }; + for entry in dir.flatten() { + let path = entry.path(); + let (Some(stem), Ok(bytes)) = (path.file_stem().and_then(|s| s.to_str()), fs::read(&path)) + else { + continue; + }; + let Ok(v) = serde_json::from_slice::(&bytes) else { + continue; + }; + let sound = match &v["sound_event"] { + Value::String(s) => s.clone(), + other => other["sound_id"].as_str().unwrap_or("").to_owned(), + }; + songs.insert( + format!("minecraft:{stem}"), + Song { + sound, + length_ticks: (v["length_in_seconds"].as_f64().unwrap_or(0.0) as f32 * 20.0).ceil() + as i64, + comparator: v["comparator_output"].as_i64().unwrap_or(0) as i32, + description: v["description"].clone(), + }, + ); + } + songs } pub(crate) fn load_tags(root: &Path, kind: &str) -> Result>> { let dir = root.join(format!("data/minecraft/tags/{kind}")); @@ -277,6 +326,7 @@ impl Items { equip_sound: c["minecraft:equippable"]["equip_sound"] .as_str() .map(str::to_owned), + jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), use_speed: c["minecraft:use_effects"]["speed_multiplier"] .as_f64() .unwrap_or(0.2) as f32, @@ -351,6 +401,7 @@ impl Items { block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, loot, + songs: load_songs(root), }) } pub fn get(&self, id: &str) -> Option<&ItemInfo> { @@ -364,6 +415,7 @@ impl Items { block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, loot: HashMap::new(), + songs: HashMap::new(), }) } /// An item table with only tags, for unit tests of item rules. @@ -375,6 +427,7 @@ impl Items { block_tags: HashMap::new(), item_tags, loot: HashMap::new(), + songs: HashMap::new(), } } fn block_matches(&self, spec: &str, block: &str) -> bool { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a8fea8b4d..4a9858798 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -462,6 +462,9 @@ pub struct Mob { pub ambient_timer: i32, pub fall_distance: f64, pub persistent: bool, + /// `CustomName` (plain text) and `CustomNameVisible`. + pub custom_name: Option, + pub name_visible: bool, pub random: LegacyRandom, pub ai: Box, pub extra: Extra, @@ -666,6 +669,8 @@ impl Mob { last_hurt: 0.0, last_damage: None, removed: false, + custom_name: None, + name_visible: false, anim: anim::AnimState::default(), attrs: Attrs { speed: kind.speed, diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index b9d4b7aef..868c8c45f 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -427,6 +427,10 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { .sqrt() .min(1.0); base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); + } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { + // isEntityUpsideDown + base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) + * glam::Mat4::from_rotation_z(PI); } base *= species_rotations(m, alpha); base *= glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index bf2e4b1dd..a0c1cde75 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -379,6 +379,12 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b entries.push(("speed_multiplier", Tag::Float(b.speed.to_bits()))); } BlockEntity::Sign(sign) => entries.extend(sign.encode()), + BlockEntity::Jukebox(j) => { + if let Some(record) = &j.record { + entries.push(("RecordItem", item_to_nbt(record))); + } + entries.push(("ticks_since_song_started", Tag::Long(j.ticks))); + } } Tag::compound(entries) } @@ -387,6 +393,19 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: let int = |k: &str| number(tag.get(k)).map(|v| v as i32); let id = text(tag.get("id"))?; let pos = (int("x")?, int("y")?, int("z")?); + if id == "minecraft:jukebox" { + let record = tag.get("RecordItem").and_then(item_from_nbt); + let ticks = number(tag.get("ticks_since_song_started")).unwrap_or(0); + let playing = record.is_some(); + return Some(( + pos, + BlockEntity::Jukebox(crate::containers::Jukebox { + record, + ticks, + playing, + }), + )); + } let mut entity = BlockEntity::for_block(&id)?; match &mut entity { BlockEntity::Chest(items) => *items = decode_items(tag.get("Items"), items.len()), @@ -423,6 +442,7 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; } BlockEntity::Sign(sign) => sign.decode(tag), + BlockEntity::Jukebox(_) => {} } Some((pos, entity)) } diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index ea3440842..87ebe8810 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -54,7 +54,9 @@ impl Sim<'_, L> { 0 } } - Class::TrappedChest => self.level.block_entity_signal(pos, state, direction), + Class::TrappedChest | Class::Jukebox => { + self.level.block_entity_signal(pos, state, direction) + } _ => Self::nibble(b.facts(state).weak, direction), } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java index 4dfb69c0d..b19a25705 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java @@ -49,6 +49,24 @@ public final class VanillaGameplayFactsExporter { o.addProperty("offset", state.hasOffsetFunction()); o.addProperty("full_collision", state.isCollisionShapeFullBlock(level, BlockPos.ZERO)); o.addProperty("map_color", state.getMapColor(level, BlockPos.ZERO).col); + // The outline (selection) shape without the random offset, as boxes + // for picking and as the edges LevelRenderer draws. + var offset = state.getOffset(BlockPos.ZERO); + var shape = state.getShape(level, BlockPos.ZERO).move(-offset.x, -offset.y, -offset.z); + var boxes = new JsonArray(); + for (var box : shape.toAabbs()) { + var b = new JsonArray(); + for (double v : new double[] {box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ}) b.add(v); + boxes.add(b); + } + o.add("outline", boxes); + var edges = new JsonArray(); + shape.forAllEdges((x0, y0, z0, x1, y1, z1) -> { + var e = new JsonArray(); + for (double v : new double[] {x0, y0, z0, x1, y1, z1}) e.add(v); + edges.add(e); + }); + o.add("outline_edges", edges); o.addProperty("friction", block.getFriction()); o.addProperty("speed_factor", block.getSpeedFactor()); o.addProperty("jump_factor", block.getJumpFactor());