Name tags show through walls

SubmitNodeCollection.submitNameTag: a name that is not discrete is drawn
in full over the world and, faded on its background, again with
RenderPipelines.TEXT_SEE_THROUGH (no depth test) after the rest of the
world; a discrete one (a crouching player) only once, faded, on its
background. The background is ARGB.color(0.25, black): alpha 0x3F.

Part of #435

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-16 10:08:20 +02:00
parent 7e1e5eb7a0
commit 3f7fba836e
5 changed files with 269 additions and 94 deletions
+11 -1
View File
@@ -762,6 +762,8 @@ struct Game<'a> {
renderer: Option<Renderer>,
/// CPU geometry storage retained across frames, including empty/title frames.
entity_vertices: Vec<Vertex>,
/// Name tags drawn over everything (`RenderPipelines.TEXT_SEE_THROUGH`).
see_through_vertices: Vec<Vertex>,
started: Instant,
previous: Instant,
/// FramerateLimitTracker.latestInputTime.
@@ -5353,7 +5355,10 @@ impl Game<'_> {
self.player_model_geometry(camera, alpha, &mut out);
self.guest_model_geometry(camera, alpha, &mut out);
self.fangs_geometry(camera, alpha, &mut out);
self.name_tag_geometry(camera, alpha, &mut out);
let mut see_through = std::mem::take(&mut self.see_through_vertices);
see_through.clear();
self.name_tag_geometry(camera, alpha, &mut out, &mut see_through);
self.see_through_vertices = see_through;
// Entity shadows (EntityRenderer.extractShadow).
if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() {
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
@@ -8488,6 +8493,7 @@ impl Game<'_> {
// Keep the buffer local while builders need mutable access to the game.
let mut entities = std::mem::take(&mut self.entity_vertices);
entities.clear();
self.see_through_vertices.clear();
if !title {
entities = horizon_client::spans::time("entity_geometry", || {
self.entity_geometry(camera, alpha, entities)
@@ -8552,6 +8558,7 @@ impl Game<'_> {
let border = (!title)
.then(|| self.border_draw(camera.to_array(), alpha as f32))
.flatten();
let see_through = std::mem::take(&mut self.see_through_vertices);
let frame = Frame {
shader: self.shader_inputs(camera, alpha as f32),
nether_lighting: self.dim == Dim::Nether,
@@ -8592,6 +8599,7 @@ impl Game<'_> {
hud: &hud,
entities: &entities,
additive: &additive,
see_through: &see_through,
celestial: if self.settings.horizon.sky || title {
&celestial
} else {
@@ -8639,6 +8647,7 @@ impl Game<'_> {
};
// Restore storage even when rendering fails (for example, a lost surface).
self.entity_vertices = entities;
self.see_through_vertices = see_through;
result
}
/// The LevelLoadingScreen shown while the player waits for its chunks:
@@ -10003,6 +10012,7 @@ pub fn run() -> Result<()> {
window: None,
renderer: None,
entity_vertices: Vec::new(),
see_through_vertices: Vec::new(),
health_hud: hud_layout::HealthHud::default(),
started: now,
previous: now,
+133 -80
View File
@@ -6,7 +6,10 @@
//! objective displayed below names. Other players' names (on a LAN host
//! or a server) show whenever `LivingEntityRenderer.shouldShowName` allows.
use super::{Game, view_vector};
use horizon_client::{mesher::Vertex, mobs::Mob, save::uuid_text, scoreboard as sb, text::Text};
use horizon_client::{
block_entity_render::vertex_light, mesher::Vertex, mobs::Mob, save::uuid_text,
scoreboard as sb, text::Text,
};
impl Game<'_> {
/// A named name tag names the mob under the crosshair.
@@ -69,16 +72,11 @@ impl Game<'_> {
pub(super) fn shown_name_tags(&self, camera: glam::DVec3) -> Vec<String> {
self.name_tags(camera, 1.0)
.into_iter()
.filter_map(|(_, lines, _)| lines.last().map(|(t, _)| t.plain()))
.filter_map(|t| t.lines.last().map(|(t, _)| t.plain()))
.collect()
}
/// Each name tag: where it hangs, its lines (text, lift) and its light.
#[allow(clippy::type_complexity)]
fn name_tags(
&self,
camera: glam::DVec3,
alpha: f64,
) -> Vec<(glam::DVec3, Vec<(Text, f64)>, u32)> {
/// Each name tag this frame.
fn name_tags(&self, camera: glam::DVec3, alpha: f64) -> Vec<NameTag> {
let target = self.mob_hit().map(|(i, _)| self.mobs[i].id);
let viewer = self.player_team();
let mut tags = Vec::new();
@@ -128,8 +126,10 @@ impl Game<'_> {
self.spectator(),
m.has_effect("minecraft:invisibility"),
);
// Entity.isDiscrete: a crouching player.
let discrete = player && m.extra.crouching;
let view = sb::NameView {
discrete: player && m.extra.crouching,
discrete,
distance_sqr,
invisible_to_viewer: invisible,
hud_hidden: self.ui.hide_gui,
@@ -164,91 +164,144 @@ impl Game<'_> {
(m.position.y + height).floor() as i32,
m.position.z.floor() as i32,
);
let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8);
tags.push((p, lines, light));
tags.push(NameTag {
at: p,
lines,
light: l,
discrete,
});
}
tags
}
pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
/// `SubmitNodeCollection.submitNameTag`: a discrete name is drawn once,
/// faded, on its background; any other in full over the world, its faded
/// copy and background in `see_through`, over everything.
pub(super) fn name_tag_geometry(
&self,
camera: glam::DVec3,
alpha: f64,
out: &mut Vec<Vertex>,
see_through: &mut Vec<Vertex>,
) {
// The text alpha that goes with getBackgroundOpacity(0.25):
// max((0.25 + 0.75) / 2, 0.5), as ARGB.color (the floor of 255 times it).
const FADED: u32 = 0x7F;
for tag in self.name_tags(camera, alpha) {
let o = tag.at - camera;
if tag.discrete {
self.name_tag_quads(o, &tag.lines, FADED, true, 0, vertex_light(tag.light), out);
continue;
}
// LightCoordsUtil.lightCoordsWithEmission(lightCoords, 2).
let lit = (tag.light >> 4).max(2) << 4 | (tag.light & 15).max(2);
self.name_tag_quads(o, &tag.lines, 0xFF, false, 0, vertex_light(lit), out);
// RenderPipelines.TEXT_SEE_THROUGH: no depth test, no lightmap.
self.name_tag_quads(o, &tag.lines, FADED, true, 2, 0, see_through);
}
}
/// The lines of one name tag, `o` from the camera: the text at
/// `text_alpha` in its layer, on the translucent black background
/// (unlit, a hair behind) when `background`.
#[allow(clippy::too_many_arguments)]
fn name_tag_quads(
&self,
o: glam::DVec3,
lines: &[(Text, f64)],
text_alpha: u32,
background: bool,
text_layer: u32,
light: u32,
out: &mut Vec<Vertex>,
) {
// Options.getBackgroundOpacity(0.25) black, as ARGB.color.
const BACKGROUND: u32 = 0x3F00_0000;
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();
let away = forward.as_vec3() * 0.002;
for (p, lines, light) in self.name_tags(camera, alpha) {
for (text, lift) in lines {
let o = (p + glam::DVec3::new(0.0, lift, 0.0) - 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 chars: Vec<(char, u32)> = text
.spans
.iter()
.flat_map(|s| {
let rgb = s.style.color.unwrap_or(0xFF_FF_FF);
// RGBA8, alpha in the top byte.
let color = 0xFF00_0000
| ((rgb & 0xFF) << 16)
| (rgb & 0xFF00)
| ((rgb >> 16) & 0xFF);
s.text.chars().map(move |c| (c, color))
})
.collect();
let width: f32 = chars
.iter()
.map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1))
.sum();
let x0 = -(width / 2.0).trunc();
let y0 = if text.plain() == "deadmau5" {
-10.0
} else {
0.0
};
// `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 {
normal: [0; 4],
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.
for (text, lift) in lines {
let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).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 chars: Vec<(char, u32)> = text
.spans
.iter()
.flat_map(|s| {
let rgb = s.style.color.unwrap_or(0xFF_FF_FF);
// RGBA8, alpha in the top byte.
let color = text_alpha << 24
| ((rgb & 0xFF) << 16)
| (rgb & 0xFF00)
| ((rgb >> 16) & 0xFF);
s.text.chars().map(move |c| (c, color))
})
.collect();
let width: f32 = chars
.iter()
.map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1))
.sum();
let x0 = -(width / 2.0).trunc();
let y0 = if text.plain() == "deadmau5" {
-10.0
} else {
0.0
};
let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, behind: bool, layer: u32| {
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 {
normal: [0; 4],
pos: (at(x, y) + if behind { away } else { glam::Vec3::ZERO }).to_array(),
uv,
layer,
color,
light,
});
}
};
if background {
quad(
[x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0],
[white.u0, white.v0, white.u1, white.v1],
0x40_00_00_00,
BACKGROUND,
true,
2,
);
let mut x = x0;
for (ch, color) in 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],
color,
false,
);
}
x += advance;
}
let mut x = x0;
for (ch, color) in 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],
color,
false,
text_layer,
);
}
x += advance;
}
}
}
}
/// A name tag: where it hangs, its lines (text, lift), the packed light at
/// the entity and whether it is discrete.
struct NameTag {
at: glam::DVec3,
lines: Vec<(Text, f64)>,
light: u8,
discrete: bool,
}
+43 -7
View File
@@ -143,6 +143,8 @@ pub struct Frame<'a> {
pub entities: &'a [Vertex],
/// Additive translucent geometry after the entities (lightning, dragon rays).
pub additive: &'a [Vertex],
/// Name tags over everything, without depth (`TEXT_SEE_THROUGH`).
pub see_through: &'a [Vertex],
/// Camera-relative sun, moon and stars (drawn behind everything, additive).
pub celestial: &'a [Vertex],
/// First-person hand and held item, drawn after clearing depth.
@@ -249,6 +251,7 @@ pub struct Renderer {
crumbling_pipeline: wgpu::RenderPipeline,
cloud_pipeline: wgpu::RenderPipeline,
additive_pipeline: wgpu::RenderPipeline,
see_through_pipeline: wgpu::RenderPipeline,
celestial_pipeline: wgpu::RenderPipeline,
celestial_buffer: wgpu::Buffer,
panorama: panorama::Panorama,
@@ -974,7 +977,7 @@ impl Renderer {
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &entity_attributes,
})];
let entity_pipeline = |label, cull_mode, depth_write, bias, blend| {
let entity_pipeline = |label, cull_mode, depth_write, depth_compare, bias, blend| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&entity_layout),
@@ -991,7 +994,7 @@ impl Renderer {
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(depth_write),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
depth_compare: Some(depth_compare),
stencil: Default::default(),
bias,
}),
@@ -1014,6 +1017,7 @@ impl Renderer {
"Breaking cracks",
Some(wgpu::Face::Back),
false,
wgpu::CompareFunction::GreaterEqual,
wgpu::DepthBiasState {
constant: 10,
slope_scale: 1.0,
@@ -1025,11 +1029,27 @@ impl Renderer {
"Clouds",
Some(wgpu::Face::Back),
true,
wgpu::CompareFunction::GreaterEqual,
Default::default(),
alpha_blend,
);
// RenderPipelines.TEXT_SEE_THROUGH: translucent, no depth test or writes.
let see_through_pipeline = entity_pipeline(
"See-through text",
None,
false,
wgpu::CompareFunction::Always,
Default::default(),
alpha_blend,
);
let entity_pipeline = entity_pipeline(
"Entities",
None,
true,
wgpu::CompareFunction::GreaterEqual,
Default::default(),
alpha_blend,
);
let entity_pipeline =
entity_pipeline("Entities", None, true, Default::default(), alpha_blend);
// BlendFunction.LIGHTNING: src alpha, one; no depth writes.
let additive_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Additive entities"),
@@ -1411,6 +1431,7 @@ impl Renderer {
crumbling_pipeline,
cloud_pipeline,
additive_pipeline,
see_through_pipeline,
celestial_pipeline,
celestial_buffer,
panorama,
@@ -2171,14 +2192,18 @@ impl Renderer {
crumbling_quads,
translucent_crumbling_quads,
cloud_quads,
] = self
.entity_batch
.update(frame.entities, frame.additive, frame.hand);
] = self.entity_batch.update(
frame.entities,
frame.additive,
frame.hand,
frame.see_through,
);
let world_quads =
entity_quads + crumbling_quads + translucent_crumbling_quads + cloud_quads;
let all_entities = &self.entity_batch.combined;
let hand_quads = (frame.hand.len() / 4) as u32;
let additive_quads = (frame.additive.len() / 4) as u32;
let see_through_quads = (frame.see_through.len() / 4) as u32;
let entity_vertices = all_entities.len() as u64;
if entity_vertices > self.entity_capacity {
self.entity_capacity = entity_vertices.next_power_of_two();
@@ -2389,6 +2414,17 @@ impl Renderer {
0..1,
);
}
// LevelRenderer.executeSeeThrough, after the rest of the world.
if see_through_quads > 0 {
pass.set_pipeline(&self.see_through_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..see_through_quads * 6,
((world_quads + additive_quads + hand_quads) * 4) as i32,
0..1,
);
}
}
if let (true, Some((color, depth)), Some(size), Some(stages)) =
(pack, &scaled, self.world_post.size(), self.pack.as_mut())
@@ -16,6 +16,7 @@ impl EntityBatch {
entities: &[Vertex],
additive: &[Vertex],
hand: &[Vertex],
see_through: &[Vertex],
) -> [u32; 4] {
let quads = entities.as_chunks::<4>().0;
for bucket in &mut self.buckets {
@@ -36,7 +37,8 @@ impl EntityBatch {
}
let entity_vertices = quads.len() * 4;
self.combined.reserve(
(entity_vertices + additive.len() + hand.len()).saturating_sub(self.combined.len()),
(entity_vertices + additive.len() + hand.len() + see_through.len())
.saturating_sub(self.combined.len()),
);
self.combined
.resize(entity_vertices, bytemuck::Zeroable::zeroed());
@@ -61,6 +63,7 @@ impl EntityBatch {
}
self.combined.extend_from_slice(additive);
self.combined.extend_from_slice(hand);
self.combined.extend_from_slice(see_through);
counts.map(|count| count as u32)
}
}
@@ -121,7 +124,7 @@ mod tests {
hand: &[Vertex],
) {
let (expected, counts) = baseline(entities, additive, hand);
assert_eq!(batch.update(entities, additive, hand), counts);
assert_eq!(batch.update(entities, additive, hand, &[]), counts);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&batch.combined),
bytemuck::cast_slice::<_, u8>(&expected)
@@ -192,7 +195,7 @@ mod tests {
equivalent(&mut batch, &entities, &additive, &hand);
for _ in 0..50 {
black_box(baseline(black_box(&entities), &additive, &hand));
black_box(batch.update(black_box(&entities), &additive, &hand));
black_box(batch.update(black_box(&entities), &additive, &hand, &[]));
black_box(&batch.combined);
}
let mut before = Vec::new();
@@ -205,7 +208,7 @@ mod tests {
before.push(start.elapsed().as_nanos() / 100);
let start = Instant::now();
for _ in 0..100 {
black_box(batch.update(black_box(&entities), &additive, &hand));
black_box(batch.update(black_box(&entities), &additive, &hand, &[]));
black_box(&batch.combined);
}
after.push(start.elapsed().as_nanos() / 100);
+75 -2
View File
@@ -40,6 +40,7 @@ import subprocess
import sys
import tempfile
import time
import zlib
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
@@ -47,7 +48,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
CHECKS = ['tab', 'self', 'armour', 'nametags', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'walls']
class Game:
@@ -474,6 +475,77 @@ def check_feedback(host, guest, out):
return chat
def png_rows(path):
"""The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel."""
data = Path(path).read_bytes()
pos, idat, head = 8, b'', None
while pos < len(data):
size = int.from_bytes(data[pos:pos + 4], 'big')
kind, body = data[pos + 4:pos + 8], data[pos + 8:pos + 8 + size]
if kind == b'IHDR':
head = body
elif kind == b'IDAT':
idat += body
pos += 12 + size
width, height = int.from_bytes(head[:4], 'big'), int.from_bytes(head[4:8], 'big')
assert head[8] == 8 and head[9] in (2, 6) and head[12] == 0, f'unsupported PNG {head.hex()}'
bpp = 4 if head[9] == 6 else 3
raw, stride, rows, prev = zlib.decompress(idat), width * bpp, [], bytearray(width * bpp)
for y in range(height):
kind, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
for i in range(stride):
a = line[i - bpp] if i >= bpp else 0
b, c = prev[i], prev[i - bpp] if i >= bpp else 0
if kind == 1:
line[i] = (line[i] + a) & 255
elif kind == 2:
line[i] = (line[i] + b) & 255
elif kind == 3:
line[i] = (line[i] + (a + b) // 2) & 255
elif kind == 4:
pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c)
line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
rows.append(bytes(line))
prev = line
return rows, bpp
def changed_pixels(a, b):
(ra, bpp), (rb, _) = png_rows(a), png_rows(b)
return sum(1 for la, lb in zip(ra, rb) for i in range(0, len(la), bpp)
if max(abs(la[i + k] - lb[i + k]) for k in range(3)) > 24)
def check_walls(host, guest, out):
# A stone wall between the two: the host still sees the guest's name through it
# (TEXT_SEE_THROUGH), but not once the guest crouches (Entity.isDiscrete).
hx, hy, hz = pos_of(host)
gx, gy, gz = pos_of(guest)
wall = int(hx // 1) + 1
host('command', command=f'fill {wall} {int(hy // 1)} {int(hz // 1) - 3} {wall} {int(hy // 1) + 4} '
f'{int(hz // 1) + 3} minecraft:stone')
try:
host.raw('look-at', f'{gx:.2f}', f'{gy + 2.3:.2f}', f'{gz:.2f}')
# Chat lines fade out after 200 ticks; let them go so only the name tag can differ.
host.wait(210)
standing = host.shot(out, 'walls-standing')
guest.raw('key', 'shift', 'down')
guest.wait(20)
crouching = host.shot(out, 'walls-crouching')
guest.raw('key', 'shift', 'up')
guest.wait(10)
again = host.shot(out, 'walls-standing-again')
finally:
guest.raw('key', 'shift', 'up')
host('command', command=f'fill {wall} {int(hy // 1)} {int(hz // 1) - 3} {wall} {int(hy // 1) + 4} '
f'{int(hz // 1) + 3} minecraft:air')
face_each_other(host, guest)
seen, steady = changed_pixels(standing, crouching), changed_pixels(standing, again)
assert seen > 50, f'no name tag through the wall: {seen} pixels differ standing vs crouching'
assert steady < seen // 4, f'the view itself changed: {steady} pixels between two standing shots ({seen})'
return {'standing_vs_crouching': seen, 'standing_twice': steady}
def state_of(game, pos, key):
state = game.raw('block', *pos)['state']
return dict(kv.split('=') for kv in state.partition('[')[2].rstrip(']').split(',') if kv).get(key)
@@ -532,7 +604,8 @@ def check_trials(host, guest, out):
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage,
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials}
'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials,
'walls': check_walls}
def run(ctl, out, resources, checks):