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 <noreply@anthropic.com>
This commit is contained in:
@@ -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<Vertex>,
|
||||
) {
|
||||
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,
|
||||
|
||||
@@ -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<str>]>,
|
||||
/// `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<String, Arc<[[f32; 6]]>> = 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,
|
||||
|
||||
@@ -52,6 +52,15 @@ pub enum BlockEntity {
|
||||
Brewing(Box<crate::brewing::BrewingStand>),
|
||||
/// 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<ItemStack>,
|
||||
/// `ticks_since_song_started`, while a song plays.
|
||||
pub ticks: i64,
|
||||
pub playing: bool,
|
||||
}
|
||||
impl BlockEntity {
|
||||
pub fn for_block(name: &str) -> Option<Self> {
|
||||
@@ -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<ItemStack> {
|
||||
@@ -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<ItemStack>] {
|
||||
@@ -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<ItemStack>] {
|
||||
@@ -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 [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String> {
|
||||
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<String, Arc<MobType>>, id: u32) -> Option<Mob> {
|
||||
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<String, Arc<MobType>>, 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]))
|
||||
}
|
||||
|
||||
@@ -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<boats::Boat>,
|
||||
boat_models: boats::BoatModels,
|
||||
carts: Vec<minecarts::Minecart>,
|
||||
/// 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<u32>,
|
||||
/// 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<Hit> {
|
||||
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,
|
||||
|
||||
@@ -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(());
|
||||
};
|
||||
|
||||
@@ -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::<Vec<_>>(),
|
||||
"riding": self.riding,
|
||||
"using": self.using,
|
||||
"render_distance": self.streaming.radius,
|
||||
"chunks": self.world.chunks.len(),
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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<Screen> {
|
||||
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),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<Vertex>) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -15,6 +15,8 @@ pub(super) struct Titles {
|
||||
pub fade_out: i32,
|
||||
pub overlay: Option<Text>,
|
||||
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)]
|
||||
}
|
||||
|
||||
@@ -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<crate::fog::FogData>,
|
||||
/// 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(..));
|
||||
|
||||
@@ -54,6 +54,8 @@ pub struct ItemInfo {
|
||||
/// `equippable.swappable` and `equip_sound`.
|
||||
pub swappable: bool,
|
||||
pub equip_sound: Option<String>,
|
||||
/// `jukebox_playable`: the jukebox song it plays.
|
||||
pub jukebox_song: Option<String>,
|
||||
}
|
||||
/// A reduction of `blocks_attacks.damage_reductions`.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -144,6 +146,53 @@ pub struct Items {
|
||||
pub block_tags: HashMap<String, HashSet<String>>,
|
||||
pub item_tags: HashMap<String, HashSet<String>>,
|
||||
loot: HashMap<String, Value>,
|
||||
/// The `jukebox_song` registry.
|
||||
pub songs: HashMap<String, Song>,
|
||||
}
|
||||
/// 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<String, Song> {
|
||||
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::<Value>(&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<HashMap<String, HashSet<String>>> {
|
||||
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 {
|
||||
|
||||
@@ -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<String>,
|
||||
pub name_visible: bool,
|
||||
pub random: LegacyRandom,
|
||||
pub ai: Box<ai::Ai>,
|
||||
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,
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -54,7 +54,9 @@ impl<L: LevelAccess + ?Sized> 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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
Reference in New Issue
Block a user