From 21baf0dc995299309df2483a9d2bfb38c76f11b2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:53:03 +0200 Subject: [PATCH 1/3] Screen overlays: blur and clamp from the texture's .png.mcmeta TextureMetadataSection's blur and clamp choose how vanilla samples a standalone texture (ReloadableTexture.setSampler). The atlas now keeps each texture's flags and the screen-effect quads (vignette, pumpkin blur, powder snow outline, underwater, equippable camera overlays) sample their sprite rectangle linearly and with clamp or repeat as those flags say, instead of always nearest and repeat. Fixes #335 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/render_tick.rs | 1 + crates/horizon-client/src/gfx.rs | 2 +- crates/horizon-client/src/hud.rs | 43 +++++++- crates/horizon-client/src/screen.wgsl | 38 +++++-- crates/horizon-client/src/screen_effects.rs | 102 +++++++++++++++++- 5 files changed, 170 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 4ad9db548..e947d2af5 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -222,6 +222,7 @@ impl Game<'_> { hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope); self.screen_fx.build(&ScreenInputs { sprites: &self.gui.atlas.sprites, + flags: &self.gui.atlas.flags, aspect: size[0] as f32 / size[1].max(1) as f32, partial, block_overlay, diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 127aaf737..c03193be4 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1921,7 +1921,7 @@ impl Renderer { source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()), }); let screen_attributes = - wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4]; + wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4,4=>Uint32]; let screen_vertex = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 0cc99b07b..cbf674136 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -18,11 +18,35 @@ pub struct Rect { pub w: u32, pub h: u32, } +/// `TextureMetadataSection`'s `blur` and `clamp`: how vanilla samples a +/// standalone texture (`ReloadableTexture.setSampler`: linear rather than +/// nearest filtering, clamp-to-edge rather than repeat addressing). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TextureFlags { + pub blur: bool, + pub clamp: bool, +} +impl TextureFlags { + /// The `texture` section of a `.png.mcmeta` file, if it sets either flag. + pub fn from_mcmeta(json: &str) -> Option { + let meta: serde_json::Value = serde_json::from_str(json).ok()?; + let section = meta.get("texture")?; + let flag = |key| section.get(key).and_then(serde_json::Value::as_bool) == Some(true); + let flags = Self { + blur: flag("blur"), + clamp: flag("clamp"), + }; + (flags != Self::default()).then_some(flags) + } +} pub struct HudAtlas { pub pixels: Vec, pub width: u32, pub height: u32, pub sprites: HashMap, + /// Sprites whose `.png.mcmeta` sets `blur` or `clamp`; the others + /// sample as vanilla's defaults (nearest, repeat). + pub flags: HashMap, pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>, /// The default font (bitmap sheets in this atlas, unifont rasterized on demand). pub font: crate::font::Font, @@ -211,7 +235,7 @@ impl HudAtlas { let s = p.to_string_lossy(); !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); - let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec)> { + let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option)> { let name = path .strip_prefix(&textures) .ok()? @@ -226,11 +250,15 @@ impl HudAtlas { } else { pixels }; - (w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels)) + let flags = fs::read_to_string(path.with_extension("png.mcmeta")) + .ok() + .and_then(|json| TextureFlags::from_mcmeta(&json)); + (w <= 1024 && (h <= 512 || name.starts_with("font/"))) + .then_some(((name, w, h, pixels), flags)) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); let chunk = files.len().div_ceil(threads).max(1); - let mut images: Vec<_> = std::thread::scope(|scope| { + let decoded: Vec<_> = std::thread::scope(|scope| { let handles: Vec<_> = files .chunks(chunk) .map(|part| { @@ -242,6 +270,14 @@ impl HudAtlas { .flat_map(|h| h.join().unwrap_or_default()) .collect() }); + let mut flags = HashMap::new(); + let mut images: Vec = Vec::with_capacity(decoded.len()); + for (image, image_flags) in decoded { + if let Some(f) = image_flags { + flags.insert(image.0.clone(), f); + } + images.push(image); + } if full { images.extend(atlas_sprites(root, &images)); } @@ -337,6 +373,7 @@ impl HudAtlas { width, height, sprites, + flags, fire_animations, font, white, diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl index 62cb2ee6c..a82b0f890 100644 --- a/crates/horizon-client/src/screen.wgsl +++ b/crates/horizon-client/src/screen.wgsl @@ -1,26 +1,50 @@ -// Full-screen camera effects (screen_effects.rs): clip-space quads sampling -// the shared 2D atlas with repeat inside each sprite rectangle. +// Full-screen camera effects (screen_effects.rs): clip-space quads reading +// one sprite rectangle of the shared 2D atlas as if it were its own texture, +// with the sampler vanilla gives it (ReloadableTexture.setSampler: linear +// when `blur`, clamp-to-edge when `clamp`, else nearest and repeat). @group(0) @binding(1) var atlas: texture_2d; -@group(0) @binding(2) var atlas_sampler: sampler; struct Out { @builtin(position) clip: vec4, @location(0) uv: vec2, @location(1) @interpolate(flat) rect: vec4, @location(2) color: vec4, + @location(3) @interpolate(flat) sampling: u32, } @vertex fn vs_screen(@location(0) pos: vec2, @location(1) uv: vec2, - @location(2) rect: vec4, @location(3) color: vec4) -> Out { + @location(2) rect: vec4, @location(3) color: vec4, + @location(4) sampling: u32) -> Out { var out: Out; out.clip = vec4(pos, 0.0, 1.0); out.uv = uv; out.rect = rect; out.color = color; + out.sampling = sampling; return out; } +const SAMPLE_BLUR: u32 = 1u; +const SAMPLE_CLAMP: u32 = 2u; +// A texel of the sprite, addressed by repeat or clamp-to-edge. +fn texel(origin: vec2, size: vec2, p: vec2, clamp_edge: bool) -> vec4 { + var q = ((p % size) + size) % size; + if clamp_edge { q = clamp(p, vec2(0), size - 1); } + return textureLoad(atlas, origin + q, 0); +} fn sample(in: Out) -> vec4 { - let f = fract(in.uv); - let uv = in.rect.xy + f * (in.rect.zw - in.rect.xy); - return textureSampleLevel(atlas, atlas_sampler, uv, 0.0) * in.color; + let dims = vec2(textureDimensions(atlas)); + let origin = vec2(round(in.rect.xy * dims)); + let size = max(vec2(round((in.rect.zw - in.rect.xy) * dims)), vec2(1)); + let clamp_edge = (in.sampling & SAMPLE_CLAMP) != 0u; + let p = in.uv * vec2(size); + if (in.sampling & SAMPLE_BLUR) == 0u { + return texel(origin, size, vec2(floor(p)), clamp_edge) * in.color; + } + // GL_LINEAR: the four texels around the sample point, weighted. + let c = p - 0.5; + let i = vec2(floor(c)); + let t = c - floor(c); + let a = mix(texel(origin, size, i, clamp_edge), texel(origin, size, i + vec2(1, 0), clamp_edge), t.x); + let b = mix(texel(origin, size, i + vec2(0, 1), clamp_edge), texel(origin, size, i + vec2(1, 1), clamp_edge), t.x); + return mix(a, b, t.y) * in.color; } @fragment fn fs_screen(in: Out) -> @location(0) vec4 { let c = sample(in); diff --git a/crates/horizon-client/src/screen_effects.rs b/crates/horizon-client/src/screen_effects.rs index bc7756453..48f468d4d 100644 --- a/crates/horizon-client/src/screen_effects.rs +++ b/crates/horizon-client/src/screen_effects.rs @@ -4,7 +4,10 @@ //! `hud_overlays::camera_overlays` (vignette, pumpkin blur, powder-snow //! outline, nether portal swirl). Positions are clip-space quads; textures //! come from the shared 2D atlas and may repeat. -use crate::{hud::Rect, hud_layout::GuiDraw}; +use crate::{ + hud::{Rect, TextureFlags}, + hud_layout::GuiDraw, +}; use std::collections::HashMap; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -24,6 +27,17 @@ pub struct ScreenVertex { /// Atlas rectangle (u0, v0, u1, v1) of the sprite. pub rect: [f32; 4], pub color: [f32; 4], + /// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`]. + pub sampling: u32, +} +/// Linear filtering (`TextureMetadataSection.blur`), else nearest. +pub const SAMPLE_BLUR: u32 = 1; +/// Clamp-to-edge addressing (`TextureMetadataSection.clamp`), else repeat. +pub const SAMPLE_CLAMP: u32 = 2; +/// The sampling bits of a standalone texture's flags. +pub fn sampling(flags: TextureFlags) -> u32 { + let bit = |on: bool, bit: u32| if on { bit } else { 0 }; + bit(flags.blur, SAMPLE_BLUR) | bit(flags.clamp, SAMPLE_CLAMP) } #[derive(Clone, Debug)] pub struct ScreenQuad { @@ -34,6 +48,8 @@ pub struct ScreenQuad { /// What the camera sees this frame. pub struct ScreenInputs<'a> { pub sprites: &'a HashMap, + /// `.png.mcmeta` sampling of the standalone textures among `sprites`. + pub flags: &'a HashMap, pub aspect: f32, pub partial: f32, /// Particle sprite of the view-blocking block around the eye. @@ -92,17 +108,23 @@ impl ScreenEffects { pub fn build(&self, input: &ScreenInputs) -> Vec { let mut out = Vec::new(); let sprite = |name: &str| input.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); + // Standalone textures (`ReloadableTexture.setSampler`) follow their + // metadata; atlas sprites (block overlay, fire, portal) sample + // nearest with repeat. + let texture_sampling = |name: &str| input.flags.get(name).copied().map_or(0, sampling); let scale = hand_scale(input.aspect); // Screen-effect quads live at view depth 0.5 in the hand projection. let hand_quad = |corners: [[f32; 2]; 4], uv: [[f32; 2]; 4], rect: [f32; 4], - color: [f32; 4]| ScreenQuad { + color: [f32; 4], + sampling: u32| ScreenQuad { vertices: std::array::from_fn(|i| ScreenVertex { pos: [corners[i][0] * scale[0], corners[i][1] * scale[1]], uv: uv[i], rect, color, + sampling, }), blend: Blend::Alpha, }; @@ -117,6 +139,7 @@ impl ScreenEffects { [[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]], rect, [c, c, c, 1.0], + 0, )); } if let Some((brightness, yaw, pitch)) = input.water @@ -129,6 +152,7 @@ impl ScreenEffects { uv, rect, [brightness, brightness, brightness, 0.1], + texture_sampling("misc/underwater"), )); } if input.on_fire @@ -150,11 +174,12 @@ impl ScreenEffects { [[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]], rect, [1.0, 1.0, 1.0, alpha], + 0, )); } } // Hud camera overlays: GUI-space full-screen blits (v grows downwards). - let gui = |rect: [f32; 4], color: [f32; 4], blend: Blend| ScreenQuad { + let gui = |rect: [f32; 4], color: [f32; 4], blend: Blend, sampling: u32| ScreenQuad { vertices: std::array::from_fn(|i| { let p = [[-1.0f32, 1.0], [1.0, 1.0], [1.0, -1.0], [-1.0, -1.0]][i]; ScreenVertex { @@ -162,6 +187,7 @@ impl ScreenEffects { uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]][i], rect, color, + sampling, } }), blend, @@ -188,7 +214,7 @@ impl ScreenEffects { Blend::Alpha }; if let Some(rect) = sprite(texture) { - out.push(gui(rect, rgba(*color), blend)); + out.push(gui(rect, rgba(*color), blend, texture_sampling(texture))); } } GuiDraw::AtlasSprite { @@ -197,7 +223,7 @@ impl ScreenEffects { .. } => { if let Some(rect) = sprite(name) { - out.push(gui(rect, rgba(*color), Blend::Alpha)); + out.push(gui(rect, rgba(*color), Blend::Alpha, 0)); } } _ => {} @@ -243,8 +269,10 @@ mod tests { }, ); let e = ScreenEffects::default(); + let flags = HashMap::new(); let input = ScreenInputs { sprites: &sprites, + flags: &flags, aspect: 1.6, partial: 0.0, block_overlay: None, @@ -255,5 +283,69 @@ mod tests { let quads = e.build(&input); assert_eq!(quads.len(), 1); assert_eq!(quads[0].blend, Blend::Vignette); + assert_eq!(quads[0].vertices[0].sampling, 0); + } + #[test] + fn standalone_textures_sample_by_their_metadata() { + let rect = Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }; + let sprites: HashMap<_, _> = ["misc/vignette", "misc/underwater", "block/stone"] + .map(|name| (name.to_owned(), rect)) + .into(); + let blur = TextureFlags { + blur: true, + clamp: false, + }; + let clamp = TextureFlags { + blur: false, + clamp: true, + }; + let flags: HashMap<_, _> = [ + ("misc/vignette".to_owned(), blur), + ("misc/underwater".to_owned(), clamp), + // Atlas sprites ignore the texture section. + ("block/stone".to_owned(), blur), + ] + .into(); + let quads = ScreenEffects::default().build(&ScreenInputs { + sprites: &sprites, + flags: &flags, + aspect: 1.6, + partial: 0.0, + block_overlay: Some("block/stone".to_owned()), + water: Some((1.0, 0.0, 0.0)), + on_fire: false, + gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)], + }); + let sampling: Vec<_> = quads.iter().map(|q| q.vertices[0].sampling).collect(); + assert_eq!(sampling, [0, SAMPLE_CLAMP, SAMPLE_BLUR]); + } + #[test] + fn mcmeta_texture_section() { + let parse = TextureFlags::from_mcmeta; + assert_eq!( + parse(r#"{"texture":{"blur":true}}"#), + Some(TextureFlags { + blur: true, + clamp: false + }) + ); + assert_eq!( + parse(r#"{"texture":{"clamp":true,"mipmap_strategy":"mean"}}"#), + Some(TextureFlags { + blur: false, + clamp: true + }) + ); + // Defaults (false, false) or no section: the default sampler. + assert_eq!(parse(r#"{"texture":{"blur":false}}"#), None); + assert_eq!(parse(r#"{"animation":{}}"#), None); + assert_eq!(parse("not json"), None); } } From 0c133101b695d8bccfa6d546411da6a171a80888 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:55:22 +0200 Subject: [PATCH 2/3] Screen overlays: wrap texels with a select, not integer modulo The camera overlays (the vignette every frame) read up to four texels a pixel, each wrapped with two integer modulos. Intel GPUs emulate integer division. Reducing the coordinate to one period first (fract, as the shader did before) leaves every read at most one texel outside the sprite, so a select wraps it. Same texels and weights; clamp-to-edge is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/screen.wgsl | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl index a82b0f890..f32274bc8 100644 --- a/crates/horizon-client/src/screen.wgsl +++ b/crates/horizon-client/src/screen.wgsl @@ -23,9 +23,11 @@ struct Out { } const SAMPLE_BLUR: u32 = 1u; const SAMPLE_CLAMP: u32 = 2u; -// A texel of the sprite, addressed by repeat or clamp-to-edge. +// A texel of the sprite, addressed by repeat or clamp-to-edge. With repeat, `p` is at most one +// texel outside the sprite (`sample` reduces the coordinate first), so wrapping is a select: no +// integer division, which Intel GPUs emulate (it cost 0.85 ms a frame on the vignette on an HD 620). fn texel(origin: vec2, size: vec2, p: vec2, clamp_edge: bool) -> vec4 { - var q = ((p % size) + size) % size; + var q = select(select(p, p - size, p >= size), p + size, p < vec2(0)); if clamp_edge { q = clamp(p, vec2(0), size - 1); } return textureLoad(atlas, origin + q, 0); } @@ -34,7 +36,8 @@ fn sample(in: Out) -> vec4 { let origin = vec2(round(in.rect.xy * dims)); let size = max(vec2(round((in.rect.zw - in.rect.xy) * dims)), vec2(1)); let clamp_edge = (in.sampling & SAMPLE_CLAMP) != 0u; - let p = in.uv * vec2(size); + // Repeat: one period of the sprite, so every texel read is at most one outside it. + let p = select(fract(in.uv), in.uv, clamp_edge) * vec2(size); if (in.sampling & SAMPLE_BLUR) == 0u { return texel(origin, size, vec2(floor(p)), clamp_edge) * in.color; } From 144741b7c7f165353dc4c34ae0e9ebad0707cbb6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 06:39:22 +0200 Subject: [PATCH 3/3] Screen overlays: one texture sample, as on main The vignette, drawn over every frame, went from one texture sample to up to four texel loads and per-pixel address arithmetic: +0.85 ms of GPU a frame on an HD 620 (integer modulo, removed in the commit before), still +0.4 ms after it. - A blurred sprite gets a one-texel border in the atlas, copied from its opposite edges: the hardware's bilinear sample of the atlas with the entity group's linear sampler is then GL_LINEAR with repeat, edges included. Clamp-to-edge keeps the sample point half a texel inside the sprite, which is what the hardware's clamp does for both filters. - Each sampling has its own pipeline, the shader specialised by override constants: a repeat sprite runs main's arithmetic and one sample, nearest or linear; only clamp adds a clamp. The sampling moves from the vertices to the quad, so the vertex layout is main's again. - A black vignette changes no pixel (it darkens by texture x colour), and is no longer drawn: in daylight its brightness fades to 0 within half a minute, so most frames outdoors skip it, which main never could. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 92 ++++++++++++--------- crates/horizon-client/src/hud.rs | 54 +++++++++++- crates/horizon-client/src/screen.wgsl | 56 ++++++------- crates/horizon-client/src/screen_effects.rs | 29 +++++-- 4 files changed, 156 insertions(+), 75 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 3aa4ace2a..f1cc3393d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -357,8 +357,9 @@ pub struct Renderer { border_group: wgpu::BindGroup, border_uniform: wgpu::Buffer, border_vertices: wgpu::Buffer, - /// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines. - screen_pipelines: [wgpu::RenderPipeline; 2], + /// Screen effects: alpha-blended, then vignette (`dst * (1 - src)`) + /// pipelines, each for every sampling (index `blend * 4 + sampling`). + screen_pipelines: [wgpu::RenderPipeline; 8], screen_buffer: wgpu::Buffer, screen_capacity: u64, entity_group: wgpu::BindGroup, @@ -1983,7 +1984,7 @@ impl Renderer { source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()), }); let screen_attributes = - wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4,4=>Uint32]; + wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4]; let screen_vertex = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, @@ -2001,37 +2002,52 @@ impl Renderer { operation: wgpu::BlendOperation::Add, }, }; - let screen_pipelines = - [("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("Screen effects"), - layout: Some(&entity_layout), - vertex: wgpu::VertexState { - module: &screen_shader, - entry_point: Some("vs_screen"), - compilation_options: Default::default(), - buffers: &screen_vertex, - }, - primitive: wgpu::PrimitiveState { - cull_mode: None, - ..Default::default() - }, - depth_stencil: None, - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &screen_shader, - entry_point: Some(entry), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: config.format.remove_srgb_suffix(), - blend: Some(blend), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - multiview_mask: None, - cache: None, - }) - }); + // One per blend and `.png.mcmeta` sampling (screen_effects::SAMPLE_*): + // the shader is specialised, so a pixel pays for none of the others. + let screen_pipelines: [wgpu::RenderPipeline; 8] = std::array::from_fn(|i| { + let (entry, blend) = if i & 4 == 0 { + ("fs_screen", alpha_blend) + } else { + ("fs_vignette", vignette_blend) + }; + let on = |bit: u32| f64::from(u8::from(i as u32 & bit != 0)); + let constants = [ + ("BLUR", on(crate::screen_effects::SAMPLE_BLUR)), + ("CLAMP", on(crate::screen_effects::SAMPLE_CLAMP)), + ]; + let compilation_options = wgpu::PipelineCompilationOptions { + constants: &constants, + ..Default::default() + }; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Screen effects"), + layout: Some(&entity_layout), + vertex: wgpu::VertexState { + module: &screen_shader, + entry_point: Some("vs_screen"), + compilation_options: compilation_options.clone(), + buffers: &screen_vertex, + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &screen_shader, + entry_point: Some(entry), + compilation_options, + targets: &[Some(wgpu::ColorTargetState { + format: config.format.remove_srgb_suffix(), + blend: Some(blend), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }); let screen_capacity = 64; let screen_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Screen effect vertices"), @@ -3911,11 +3927,11 @@ impl Renderer { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(0, self.screen_buffer.slice(..)); for (i, quad) in frame.screen.iter().enumerate() { - let pipeline = match quad.blend { - crate::screen_effects::Blend::Alpha => &self.screen_pipelines[0], - crate::screen_effects::Blend::Vignette => &self.screen_pipelines[1], + let blend = match quad.blend { + crate::screen_effects::Blend::Alpha => 0, + crate::screen_effects::Blend::Vignette => 4, }; - pass.set_pipeline(pipeline); + pass.set_pipeline(&self.screen_pipelines[blend + (quad.sampling & 3) as usize]); pass.draw_indexed(0..6, (i * 4) as i32, 0..1); } } diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 43ae29c74..dbd44266a 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -104,6 +104,20 @@ fn walk(dir: &Path, out: &mut Vec) { } /// A packed atlas image: sprite name, size and RGBA pixels. type PackedImage = (String, u32, u32, Vec); +/// `image` inside a one-texel border copied from its opposite edges, the +/// texels repeat addressing reads past each edge. +fn wrap_border((name, w, h, data): &PackedImage) -> PackedImage { + let (bw, bh) = (w + 2, h + 2); + let mut out = Vec::with_capacity((bw * bh * 4) as usize); + for y in 0..bh { + let row = (y + h - 1) % h; + for x in 0..bw { + let at = ((row * w + (x + w - 1) % w) * 4) as usize; + out.extend_from_slice(&data[at..at + 4]); + } + } + (name.clone(), bw, bh, out) +} /// Sprites the atlas definitions (`atlases/*.json`) add beyond the texture /// files already packed: generated ones (`paletted_permutations` such as the /// armour trim sprites, `unstitch` regions) and files listed under another id. @@ -326,6 +340,16 @@ impl HudAtlas { if full { Self::slots(&mut images, crate::trims::slot_size(root)); } + // Blurred sprites are sampled linearly in the atlas (screen.wgsl): a + // border wrapped from their own edges keeps the filter off their + // neighbours, as repeat addressing of their own texture would. + let mut bordered = std::collections::HashSet::new(); + for image in &mut images { + if flags.get(&image.0).is_some_and(|f: &TextureFlags| f.blur) { + *image = wrap_border(image); + bordered.insert(image.0.clone()); + } + } images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); let width = 4096u32; let mut placements = Vec::with_capacity(images.len()); @@ -350,6 +374,8 @@ impl HudAtlas { let dst = (((py + row) * width + px) * 4) as usize; pixels[dst..dst + (w * 4) as usize].copy_from_slice(src); } + let b = u32::from(bordered.contains(name)); + let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b); sprites.insert( name.clone(), Rect { @@ -357,8 +383,8 @@ impl HudAtlas { v0: py as f32 / height as f32, u1: (px + w) as f32 / width as f32, v1: (py + h) as f32 / height as f32, - w: *w, - h: *h, + w, + h, }, ); } @@ -1246,6 +1272,30 @@ impl HudRenderer { mod tests { use super::*; + #[test] + fn a_wrapped_border_repeats_the_opposite_edges() { + // 2x2 texels a b / c d, one byte each in red. + let image = ( + "x".to_owned(), + 2, + 2, + [1u8, 2, 3, 4] + .iter() + .flat_map(|&v| [v, 0, 0, 255]) + .collect(), + ); + let (_, w, h, data) = wrap_border(&image); + assert_eq!((w, h), (4, 4)); + let red: Vec = data.chunks(4).map(|t| t[0]).collect(); + #[rustfmt::skip] + assert_eq!(red, [ + 4, 3, 4, 3, + 2, 1, 2, 1, + 4, 3, 4, 3, + 2, 1, 2, 1, + ]); + } + #[test] fn the_fonts_only_atlas_measures_text_like_the_full_one() { // A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide. diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl index f32274bc8..e70aeb896 100644 --- a/crates/horizon-client/src/screen.wgsl +++ b/crates/horizon-client/src/screen.wgsl @@ -3,51 +3,49 @@ // with the sampler vanilla gives it (ReloadableTexture.setSampler: linear // when `blur`, clamp-to-edge when `clamp`, else nearest and repeat). @group(0) @binding(1) var atlas: texture_2d; +// The block sprites' sampler (nearest), and the entity group's lightmap +// sampler (linear) for `blur`. A blurred sprite has a one-texel border in the +// atlas, wrapped as repeat reads it (hud.rs), so the hardware's bilinear +// sample is GL_LINEAR with repeat; clamp-to-edge keeps the sample point half +// a texel inside. Each sampling has its own pipeline (gfx.rs), so a pixel +// costs what it did with nearest and repeat only: one sample. +@group(0) @binding(2) var nearest_sampler: sampler; +@group(0) @binding(4) var linear_sampler: sampler; +override BLUR: bool = false; +override CLAMP: bool = false; struct Out { @builtin(position) clip: vec4, @location(0) uv: vec2, @location(1) @interpolate(flat) rect: vec4, @location(2) color: vec4, - @location(3) @interpolate(flat) sampling: u32, + // With clamp-to-edge, the sprite's first and last texel centres. + @location(3) @interpolate(flat) edges: vec4, } @vertex fn vs_screen(@location(0) pos: vec2, @location(1) uv: vec2, - @location(2) rect: vec4, @location(3) color: vec4, - @location(4) sampling: u32) -> Out { + @location(2) rect: vec4, @location(3) color: vec4) -> Out { var out: Out; out.clip = vec4(pos, 0.0, 1.0); out.uv = uv; out.rect = rect; out.color = color; - out.sampling = sampling; + let half = 0.5 / vec2(textureDimensions(atlas)); + out.edges = vec4(rect.xy + half, rect.zw - half); return out; } -const SAMPLE_BLUR: u32 = 1u; -const SAMPLE_CLAMP: u32 = 2u; -// A texel of the sprite, addressed by repeat or clamp-to-edge. With repeat, `p` is at most one -// texel outside the sprite (`sample` reduces the coordinate first), so wrapping is a select: no -// integer division, which Intel GPUs emulate (it cost 0.85 ms a frame on the vignette on an HD 620). -fn texel(origin: vec2, size: vec2, p: vec2, clamp_edge: bool) -> vec4 { - var q = select(select(p, p - size, p >= size), p + size, p < vec2(0)); - if clamp_edge { q = clamp(p, vec2(0), size - 1); } - return textureLoad(atlas, origin + q, 0); -} fn sample(in: Out) -> vec4 { - let dims = vec2(textureDimensions(atlas)); - let origin = vec2(round(in.rect.xy * dims)); - let size = max(vec2(round((in.rect.zw - in.rect.xy) * dims)), vec2(1)); - let clamp_edge = (in.sampling & SAMPLE_CLAMP) != 0u; - // Repeat: one period of the sprite, so every texel read is at most one outside it. - let p = select(fract(in.uv), in.uv, clamp_edge) * vec2(size); - if (in.sampling & SAMPLE_BLUR) == 0u { - return texel(origin, size, vec2(floor(p)), clamp_edge) * in.color; + var f = in.uv; + if !CLAMP { + // Repeat: one period of the sprite. + f = fract(f); } - // GL_LINEAR: the four texels around the sample point, weighted. - let c = p - 0.5; - let i = vec2(floor(c)); - let t = c - floor(c); - let a = mix(texel(origin, size, i, clamp_edge), texel(origin, size, i + vec2(1, 0), clamp_edge), t.x); - let b = mix(texel(origin, size, i + vec2(0, 1), clamp_edge), texel(origin, size, i + vec2(1, 1), clamp_edge), t.x); - return mix(a, b, t.y) * in.color; + var uv = in.rect.xy + f * (in.rect.zw - in.rect.xy); + if CLAMP { + uv = clamp(uv, in.edges.xy, in.edges.zw); + } + if BLUR { + return textureSampleLevel(atlas, linear_sampler, uv, 0.0) * in.color; + } + return textureSampleLevel(atlas, nearest_sampler, uv, 0.0) * in.color; } @fragment fn fs_screen(in: Out) -> @location(0) vec4 { let c = sample(in); diff --git a/crates/horizon-client/src/screen_effects.rs b/crates/horizon-client/src/screen_effects.rs index 48f468d4d..269a534e7 100644 --- a/crates/horizon-client/src/screen_effects.rs +++ b/crates/horizon-client/src/screen_effects.rs @@ -27,8 +27,6 @@ pub struct ScreenVertex { /// Atlas rectangle (u0, v0, u1, v1) of the sprite. pub rect: [f32; 4], pub color: [f32; 4], - /// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`]. - pub sampling: u32, } /// Linear filtering (`TextureMetadataSection.blur`), else nearest. pub const SAMPLE_BLUR: u32 = 1; @@ -43,6 +41,8 @@ pub fn sampling(flags: TextureFlags) -> u32 { pub struct ScreenQuad { pub vertices: [ScreenVertex; 4], pub blend: Blend, + /// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`]. + pub sampling: u32, } /// What the camera sees this frame. @@ -124,9 +124,9 @@ impl ScreenEffects { uv: uv[i], rect, color, - sampling, }), blend: Blend::Alpha, + sampling, }; let full = [[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]]; // ScreenEffectRenderer.submitBlockSprite: u1/v1 at (-1, -1), colour 0xFF191919. @@ -187,10 +187,10 @@ impl ScreenEffects { uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]][i], rect, color, - sampling, } }), blend, + sampling, }; let rgba = |c: u32| { let [a, r, g, b] = c.to_be_bytes(); @@ -213,6 +213,12 @@ impl ScreenEffects { } else { Blend::Alpha }; + // The vignette darkens by texture × colour: black (in + // daylight its brightness fades to 0 within half a + // minute) leaves every pixel as it was. + if blend == Blend::Vignette && color & 0x00ff_ffff == 0 { + continue; + } if let Some(rect) = sprite(texture) { out.push(gui(rect, rgba(*color), blend, texture_sampling(texture))); } @@ -283,7 +289,18 @@ mod tests { let quads = e.build(&input); assert_eq!(quads.len(), 1); assert_eq!(quads[0].blend, Blend::Vignette); - assert_eq!(quads[0].vertices[0].sampling, 0); + assert_eq!(quads[0].sampling, 0); + // A black vignette (faded out in daylight) changes no pixel: no quad. + // Below 1/255 the colour's channels are 0; a border warning tints it. + for (brightness, warning, drawn) in [(0.003, 0.0, 0), (0.004, 0.0, 1), (0.0, 0.5, 1)] { + let overlays = [crate::hud_overlays::vignette(320, 240, brightness, warning)]; + let input = ScreenInputs { + block_overlay: None, + gui_overlays: &overlays, + ..input + }; + assert_eq!(e.build(&input).len(), drawn, "{brightness} {warning}"); + } } #[test] fn standalone_textures_sample_by_their_metadata() { @@ -323,7 +340,7 @@ mod tests { on_fire: false, gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)], }); - let sampling: Vec<_> = quads.iter().map(|q| q.vertices[0].sampling).collect(); + let sampling: Vec<_> = quads.iter().map(|q| q.sampling).collect(); assert_eq!(sampling, [0, SAMPLE_CLAMP, SAMPLE_BLUR]); } #[test]