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 c14a32e2c..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, @@ -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 2537949d0..82e606947 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, @@ -80,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. @@ -243,7 +281,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()? @@ -258,11 +296,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| { @@ -274,6 +316,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)); } @@ -290,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()); @@ -314,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 { @@ -321,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, }, ); } @@ -369,6 +431,7 @@ impl HudAtlas { width, height, sprites, + flags, fire_animations, font, white, @@ -1277,6 +1340,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, + ]); + } + /// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide. fn two_glyph_font(name: &str) -> std::path::PathBuf { let root = diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl index 62cb2ee6c..e70aeb896 100644 --- a/crates/horizon-client/src/screen.wgsl +++ b/crates/horizon-client/src/screen.wgsl @@ -1,12 +1,25 @@ -// 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; +// 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, + // 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) -> Out { @@ -15,12 +28,24 @@ struct Out { out.uv = uv; out.rect = rect; out.color = color; + let half = 0.5 / vec2(textureDimensions(atlas)); + out.edges = vec4(rect.xy + half, rect.zw - half); return out; } 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; + var f = in.uv; + if !CLAMP { + // Repeat: one period of the sprite. + f = fract(f); + } + 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 bc7756453..269a534e7 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)] @@ -25,15 +28,28 @@ pub struct ScreenVertex { pub rect: [f32; 4], pub color: [f32; 4], } +/// 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 { 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. 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,12 +108,17 @@ 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], @@ -105,6 +126,7 @@ impl ScreenEffects { color, }), 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. @@ -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 { @@ -165,6 +190,7 @@ impl ScreenEffects { } }), blend, + sampling, }; let rgba = |c: u32| { let [a, r, g, b] = c.to_be_bytes(); @@ -187,8 +213,14 @@ 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)); + out.push(gui(rect, rgba(*color), blend, texture_sampling(texture))); } } GuiDraw::AtlasSprite { @@ -197,7 +229,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 +275,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 +289,80 @@ mod tests { let quads = e.build(&input); assert_eq!(quads.len(), 1); assert_eq!(quads[0].blend, Blend::Vignette); + 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() { + 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.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); } }