diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 69c0df3fc..799e48cb9 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4342,14 +4342,7 @@ impl Game<'_> { } else { ("Crafting", 97.0) }; - batch.text( - atlas, - title, - ox + tx, - oy + if self.craft_size == 3 { 6.0 } else { 8.0 }, - grey, - false, - ); + batch.text(atlas, title, ox + tx, oy + 6.0, grey, false); if self.craft_size == 3 { batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false); } diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index a66ca487d..bb463547f 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -427,7 +427,7 @@ impl Game<'_> { } /// `extractEntityInInventoryFollowsMouse`: the player in the box /// `[x0, x1) x [y0, y1)`, `size` pixels per block, turned toward the - /// cursor; drawn as depth-sorted, back-face-culled quads. + /// cursor; drawn with a depth buffer and back-face culling. #[allow(clippy::too_many_arguments)] pub(super) fn draw_player_preview( &self, @@ -495,9 +495,9 @@ impl Game<'_> { let quads = player_preview_quads(verts, gui, fire, &atlas.sprites); let start = batch.vertices.len(); for (_, p, uv, color) in quads { - batch.quad(p, uv, color); + batch.quad_3d(p, uv, color); } - batch.clip_since(start, x0, y0, x1, y1); + batch.depth_since(start, [x0, y0, x1, y1]); } /// The survival inventory's player box (`InventoryScreen`). pub(super) fn draw_inventory_player(&self, batch: &mut HudBatch, ox: f32, oy: f32) { @@ -570,7 +570,7 @@ fn player_preview_quads( gui: glam::Mat4, fire: Option<(f32, f32)>, sprites: &std::collections::HashMap, -) -> Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> { +) -> Vec<(f32, [[f32; 3]; 4], [[f32; 2]; 4], u32)> { let flame_start = verts.len(); if let Some((width, height)) = fire { horizon_client::fire_render::flames( @@ -584,7 +584,7 @@ fn player_preview_quads( &mut verts, ); } - let mut quads: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); + let mut quads: Vec<(f32, [[f32; 3]; 4], [[f32; 2]; 4], u32)> = Vec::new(); for (index, q) in verts.as_chunks::<4>().0.iter().enumerate() { let p: [glam::Vec3; 4] = std::array::from_fn(|i| gui.transform_point3(glam::Vec3::from_array(q[i].pos))); @@ -606,12 +606,12 @@ fn player_preview_quads( let depth = p.iter().map(|v| v.z).sum::() / 4.0; quads.push(( depth, - p.map(|v| [v.x, v.y]), + p.map(|v| v.to_array()), std::array::from_fn(|i| q[i].uv), color, )); } - // Far (low z) first: the viewer is on the +z side. + // Keep far-to-near order for translucent faces; opaque overlap uses depth. quads.sort_by(|a, b| a.0.total_cmp(&b.0)); quads } @@ -619,6 +619,60 @@ fn player_preview_quads( #[cfg(test)] mod preview_tests { use super::*; + #[test] + fn preview_keeps_crossing_faces_depth_and_clips_without_dropping_faces() { + use horizon_client::{ + hud::{Blend, HudBatch}, + mesher::Vertex, + }; + let face = |z: [f32; 4]| { + [[-2.0, -1.0], [-2.0, 1.0], [2.0, 1.0], [2.0, -1.0]] + .into_iter() + .zip(z) + .map(|([x, y], z)| Vertex { + pos: [x, y, z], + uv: [0.0; 2], + layer: 0, + color: u32::MAX, + light: 0, + normal: [0; 4], + }) + }; + // A shield and arm can intersect: neither average depth orders both ends. + let verts = face([1.0, 1.0, -1.0, -1.0]).chain(face([0.0; 4])).collect(); + let quads = player_preview_quads(verts, glam::Mat4::IDENTITY, None, &Default::default()); + assert_eq!(quads.len(), 2); + let mut batch = HudBatch::new([320, 240]); + for (_, p, uv, color) in quads { + batch.quad_3d(p, uv, color); + } + // Its centre is outside this scissor; the visible part must still be drawn. + batch.depth_since(0, [1.0, 0.0, 2.0, 1.0]); + assert_eq!(batch.vertices.len(), 12); + let shield = &batch.vertices[..6]; + let arm = &batch.vertices[6..]; + assert!(shield[0].depth < arm[0].depth); + assert!(shield[2].depth > arm[2].depth); + assert_eq!(batch.runs(), vec![(0..12, Blend::Depth([1, 0, 1, 1]))]); + } + + #[test] + #[ignore = "requires prepared model data in HORIZON_TEST_RESOURCES"] + fn player_render_transform_uses_vanilla_avatar_scale() { + let root = std::path::PathBuf::from( + std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"), + ); + let mut m = Mob::new(1, player_type(&root).unwrap(), Vec3::ZERO, 0.0); + for (id, expected) in [("minecraft:player", 0.9375), ("minecraft:zombie", 1.0)] { + Arc::make_mut(&mut m.kind).id = id.into(); + let transform = + horizon_client::mobs::render::base_transform_at(&m, 1.0, glam::Mat4::IDENTITY); + for axis in [glam::Vec3::X, glam::Vec3::Y, glam::Vec3::Z] { + assert!((transform.transform_vector3(axis).length() - expected).abs() < 1e-6); + } + } + } + #[test] fn burning_inventory_preview_keeps_visible_fullbright_flames() { let rect = |u0| horizon_client::hud::Rect { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index f64200e5c..bc2e708a3 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -2776,6 +2776,7 @@ impl Renderer { &mut self.uploads, &mut encoder, &view_target, + &self.depth, frame.hud, [self.config.width, self.config.height], ); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index c42f8c8bc..be4bdb52e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -349,6 +349,7 @@ pub struct HudVertex { pub pos: [f32; 2], pub uv: [f32; 2], pub color: u32, + pub depth: f32, } /// The GUI Scale option (0 = auto). pub static GUI_SCALE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -360,10 +361,10 @@ pub struct HudBatch { pub height: f32, /// Glyph pixels to upload into the atlas before drawing. pub patches: Vec, - /// Vertex ranges drawn with another blend than alpha blending, in order. + /// Vertex ranges with another blend or depth/scissor state, in order. pub blends: Vec<(std::ops::Range, Blend)>, } -/// How a run of HUD vertices blends with what is under it. +/// How a run of HUD vertices blends and tests depth. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Blend { /// `BlendFunction.TRANSLUCENT`. @@ -372,6 +373,8 @@ pub enum Blend { Invert, /// `BlendFunction.ADDITIVE` (`RenderPipelines.GUI_TEXT_HIGHLIGHT`). Additive, + /// Alpha blending with an isolated depth buffer and a pixel scissor. + Depth([u32; 4]), } pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 { u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r) @@ -460,9 +463,44 @@ impl HudBatch { pos: p[i], uv: uv[i], color, + depth: 0.0, }); } } + pub fn quad_3d(&mut self, p: [[f32; 3]; 4], uv: [[f32; 2]; 4], color: u32) { + for i in [0, 1, 2, 0, 2, 3] { + self.vertices.push(HudVertex { + pos: [p[i][0], p[i][1]], + uv: uv[i], + color, + depth: p[i][2], + }); + } + } + /// Keep per-vertex depth for an orthographic GUI model, with +z toward the viewer. + pub fn depth_since(&mut self, start: usize, clip: [f32; 4]) { + let vertices = &mut self.vertices[start..]; + if vertices.is_empty() { + return; + } + let min = vertices + .iter() + .map(|v| v.depth) + .fold(f32::INFINITY, f32::min); + let max = vertices + .iter() + .map(|v| v.depth) + .fold(f32::NEG_INFINITY, f32::max); + for v in vertices { + v.depth = (max - v.depth) / (max - min).max(f32::EPSILON); + } + let [x0, y0, x1, y1] = clip.map(|v| (v * self.scale).max(0.0) as u32); + // Separate previews clear depth independently, even if their scissors match. + self.blends.push(( + start as u32..self.vertices.len() as u32, + Blend::Depth([x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0)]), + )); + } pub fn rect_uv(&mut self, x: f32, y: f32, w: f32, h: f32, r: Rect, color: u32) { self.quad( [[x, y], [x + w, y], [x + w, y + h], [x, y + h]], @@ -599,6 +637,7 @@ impl HudBatch { pos: p[i], uv, color: c[i], + depth: 0.0, }); } } @@ -759,6 +798,7 @@ pub struct HudRenderer { /// `RenderPipelines.CROSSHAIR`. invert_pipeline: wgpu::RenderPipeline, additive_pipeline: wgpu::RenderPipeline, + depth_pipeline: wgpu::RenderPipeline, group: wgpu::BindGroup, uniform: wgpu::Buffer, buffer: wgpu::Buffer, @@ -838,8 +878,8 @@ impl HudRenderer { bind_group_layouts: &[Some(&layout)], ..Default::default() }); - let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4]; - let create = |label, blend, fragment_entry| { + let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4,3=>Float32]; + let create = |label, blend, fragment_entry, depth: bool| { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(&pipeline_layout), @@ -854,7 +894,13 @@ impl HudRenderer { })], }, primitive: Default::default(), - depth_stencil: None, + depth_stencil: depth.then_some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias: Default::default(), + }), multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &shader, @@ -870,7 +916,13 @@ impl HudRenderer { cache: None, }) }; - let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING, "fs_main"); + let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING, "fs_main", false); + let depth_pipeline = create( + "HUD model", + wgpu::BlendState::ALPHA_BLENDING, + "fs_main", + true, + ); // BlendFunction.INVERT: ONE_MINUS_DST_COLOR, ONE_MINUS_SRC_COLOR, // ONE, ZERO. let invert_pipeline = create( @@ -888,6 +940,7 @@ impl HudRenderer { }, }, "fs_crosshair", + false, ); // BlendFunction.ADDITIVE: ONE, ONE. let add = wgpu::BlendComponent { @@ -902,6 +955,7 @@ impl HudRenderer { alpha: add, }, "fs_main", + false, ); let capacity = 1 << 16; let buffer = device.create_buffer(&wgpu::BufferDescriptor { @@ -916,6 +970,7 @@ impl HudRenderer { pipeline, invert_pipeline, additive_pipeline, + depth_pipeline, group, uniform, buffer, @@ -965,6 +1020,7 @@ impl HudRenderer { uploads: &mut crate::gfx::upload::Uploads, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, + depth: &wgpu::TextureView, batch: &HudBatch, size: [u32; 2], ) { @@ -995,7 +1051,7 @@ impl HudRenderer { ); } } - if batch.vertices.is_empty() { + if batch.vertices.is_empty() || size.contains(&0) { return; } let count = batch.vertices.len() as u64; @@ -1031,20 +1087,55 @@ impl HudRenderer { store: wgpu::StoreOp::Store, }, })]; - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("HUD"), - color_attachments: &attachments, - ..Default::default() - }); - pass.set_bind_group(0, &self.group, &[]); - pass.set_vertex_buffer(0, self.buffer.slice(..)); - for (range, blend) in batch.runs() { - pass.set_pipeline(match blend { - Blend::Alpha => &self.pipeline, - Blend::Invert => &self.invert_pipeline, - Blend::Additive => &self.additive_pipeline, + let runs = batch.runs(); + let mut at = 0; + while at < runs.len() { + let clip = match runs[at].1 { + Blend::Depth(clip) => Some(clip), + _ => None, + }; + let end = if clip.is_some() { + at + 1 + } else { + runs[at..] + .iter() + .position(|(_, b)| matches!(b, Blend::Depth(_))) + .map_or(runs.len(), |n| at + n) + }; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("HUD"), + color_attachments: &attachments, + depth_stencil_attachment: clip.map(|_| wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + ..Default::default() }); - pass.draw(range, 0..1); + pass.set_bind_group(0, &self.group, &[]); + pass.set_vertex_buffer(0, self.buffer.slice(..)); + if let Some([x, y, w, h]) = clip { + let (x, y) = (x.min(size[0]), y.min(size[1])); + let (w, h) = (w.min(size[0] - x), h.min(size[1] - y)); + if w == 0 || h == 0 { + at = end; + continue; + } + pass.set_scissor_rect(x, y, w, h); + } + for (range, blend) in &runs[at..end] { + pass.set_pipeline(match blend { + Blend::Alpha => &self.pipeline, + Blend::Invert => &self.invert_pipeline, + Blend::Additive => &self.additive_pipeline, + Blend::Depth(_) => &self.depth_pipeline, + }); + pass.draw(range.clone(), 0..1); + } + at = end; } } } @@ -1159,6 +1250,41 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[test] + fn gui_models_keep_separate_depth_runs_between_overlay_draws() { + let mut batch = HudBatch::new([640, 480]); + batch.scale = 2.0; + let p = [ + [0.0, 0.0, 2.0], + [0.0, 1.0, 2.0], + [1.0, 1.0, 2.0], + [1.0, 0.0, 2.0], + ]; + let uv = [[0.0; 2]; 4]; + batch.quad([[0.0; 2]; 4], uv, u32::MAX); + for _ in 0..2 { + let start = batch.vertices.len(); + batch.quad_3d(p, uv, u32::MAX); + batch.depth_since(start, [1.0, 2.0, 4.0, 6.0]); + } + batch.quad([[0.0; 2]; 4], uv, u32::MAX); + assert_eq!( + batch.runs(), + vec![ + (0..6, Blend::Alpha), + (6..12, Blend::Depth([2, 4, 6, 8])), + (12..18, Blend::Depth([2, 4, 6, 8])), + (18..24, Blend::Alpha), + ] + ); + assert!( + batch + .vertices + .iter() + .all(|v| v.depth.is_finite() && (0.0..=1.0).contains(&v.depth)) + ); + } + #[test] fn hud_shader_validates_both_fragment_entries() { let module = naga::front::wgsl::parse_str(include_str!("hud.wgsl")).unwrap(); diff --git a/crates/horizon-client/src/hud.wgsl b/crates/horizon-client/src/hud.wgsl index 055bfc1f1..17d50d51a 100644 --- a/crates/horizon-client/src/hud.wgsl +++ b/crates/horizon-client/src/hud.wgsl @@ -7,10 +7,10 @@ struct Out { @location(0) uv: vec2, @location(1) color: vec4, } -@vertex fn vs_main(@location(0) pos: vec2, @location(1) uv: vec2, @location(2) color: vec4) -> Out { +@vertex fn vs_main(@location(0) pos: vec2, @location(1) uv: vec2, @location(2) color: vec4, @location(3) depth: f32) -> Out { let pixels = pos * hud.size.z; var out: Out; - out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, 0.0, 1.0); + out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, depth, 1.0); out.uv = uv; out.color = color; return out; diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 4c312e5fd..e8120e92e 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -847,6 +847,10 @@ fn red_overlay(m: &Mob) -> bool { m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)) } fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 { + if m.kind.id == "minecraft:player" { + // AvatarRenderer.scale, shared by the inventory and world renderer. + return glam::Mat4::from_scale(glam::Vec3::splat(0.9375)); + } match m.species() { Species::Wither => { glam::Mat4::from_scale(glam::Vec3::splat(super::wither::scale(m, alpha))) diff --git a/crates/horizon-client/src/ui_theme.rs b/crates/horizon-client/src/ui_theme.rs index 1c41add9d..d5073bec9 100644 --- a/crates/horizon-client/src/ui_theme.rs +++ b/crates/horizon-client/src/ui_theme.rs @@ -690,6 +690,7 @@ impl<'a> Ui<'a> { pos: p[i], uv: [cu, cv], color: c[i], + depth: 0.0, }); } }