From 92b8cd692da2ffb244b4c81bb1a965d4608f956a Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:50:29 +0100 Subject: [PATCH] perf(client): retain the End sky mesh on the GPU --- crates/horizon-client/src/game.rs | 11 +- crates/horizon-client/src/game/end.rs | 45 +-- crates/horizon-client/src/gfx.rs | 25 +- crates/horizon-client/src/gfx/end_sky.rs | 84 +++++ .../horizon-client/src/gfx/end_sky/tests.rs | 330 ++++++++++++++++++ 5 files changed, 447 insertions(+), 48 deletions(-) create mode 100644 crates/horizon-client/src/gfx/end_sky.rs create mode 100644 crates/horizon-client/src/gfx/end_sky/tests.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f706e9348..ccc838bbb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9812,8 +9812,8 @@ impl Game<'_> { { // Camera.doesMobEffectBlockSky: no sun, moon or stars. self.celestial_geometry(&sky) - } else if self.dim == Dim::End { - (self.end_sky_geometry(), None) + } else if self.dim == Dim::End && self.settings.horizon.sky { + (self.end_flash_geometry(), None) } else { (Vec::new(), None) }; @@ -9860,6 +9860,12 @@ impl Game<'_> { title: title && !live, skybox: self.dim == Dim::Overworld && self.settings.horizon.sky, end_sky: self.dim == Dim::End && self.settings.horizon.sky, + end_sky_sprite: self + .gui + .atlas + .sprites + .get("environment/end_sky") + .map(|r| [r.u0, r.v0, r.u1, r.v1]), environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)), cave_culling, water_fog, @@ -12363,6 +12369,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { title: true, skybox: false, end_sky: false, + end_sky_sprite: None, environment_fog: None, water_fog: [0.0; 3], fog: None, diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index a7813c767..98a595f76 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -138,47 +138,12 @@ impl Game<'_> { } } - /// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times, - /// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. - pub(super) fn end_sky_geometry(&self) -> Vec { - let mut out = Vec::with_capacity(6 * 256 * 4); - let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else { + /// SkyRenderer.renderEndFlash, drawn after the renderer's resident sky mesh. + pub(super) fn end_flash_geometry(&self) -> Vec { + let mut out = Vec::new(); + // The old combined sky/flash draw also skipped the flash without a sky sprite. + if !self.gui.atlas.sprites.contains_key("environment/end_sky") { return out; - }; - use std::f32::consts::FRAC_PI_2; - let faces = [ - glam::Mat4::IDENTITY, - glam::Mat4::from_rotation_x(FRAC_PI_2), - glam::Mat4::from_rotation_x(-FRAC_PI_2), - glam::Mat4::from_rotation_x(std::f32::consts::PI), - glam::Mat4::from_rotation_z(FRAC_PI_2), - glam::Mat4::from_rotation_z(-FRAC_PI_2), - ]; - let step = 200.0 / 16.0; - for pose in faces { - for a in 0..16 { - for b in 0..16 { - let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32); - let (x1, z1) = (x0 + step, z0 + step); - let corners = [ - (x0, z0, [r.u0, r.v0]), - (x0, z1, [r.u0, r.v1]), - (x1, z1, [r.u1, r.v1]), - (x1, z0, [r.u1, r.v0]), - ]; - for (x, z, uv) in corners { - let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z)); - out.push(Vertex { - normal: [0; 4], - pos: p.to_array(), - uv, - layer: 2, - color: 0xFF28_2828, - light: 0, - }); - } - } - } } // SkyRenderer.renderEndFlash: the end_flash sprite at height 100, scale 60. let intensity = self.end.flash.intensity(self.clock.fraction() as f32); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 14c040c5c..fb1cd322e 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -61,6 +61,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod cull; +mod end_sky; mod flat; mod java_stages; mod lod; @@ -163,8 +164,10 @@ pub struct Frame<'a> { pub title: bool, /// Dimensions without a skybox (the Nether) clear to the fog colour. pub skybox: bool, - /// The End: clear to black and draw `celestial` (the End sky box) behind the world. + /// The End: clear to black and draw the resident sky box behind the world. pub end_sky: bool, + /// End sky atlas bounds (u0, v0, u1, v1); absent when the sprite is missing. + pub end_sky_sprite: Option<[f32; 4]>, /// Environmental fog start/end (Nether 10..96), if any. pub environment_fog: Option<(f32, f32)>, pub water_fog: [f32; 3], @@ -197,8 +200,8 @@ pub struct Frame<'a> { pub additive: &'a [Vertex], /// Name tags over everything, without depth (`TEXT_SEE_THROUGH`). pub see_through: &'a [Vertex], - /// Camera-relative sun and moon, or the End sky box (drawn behind - /// everything, additive). + /// Camera-relative sun and moon, or the animated End flash (additive, + /// behind everything and after the resident End sky box). pub celestial: &'a [Vertex], /// The stars, drawn from their static buffer after the sun and moon: /// the sky's rotation (camera-relative world from star space) and the @@ -337,6 +340,7 @@ pub struct Renderer { see_through_pipeline: wgpu::RenderPipeline, celestial_pipeline: wgpu::RenderPipeline, celestial_buffer: wgpu::Buffer, + end_sky: end_sky::EndSky, stars: stars::Stars, panorama: panorama::Panorama, /// `RenderPipelines.WORLD_BORDER` and its buffers. @@ -2113,6 +2117,7 @@ impl Renderer { see_through_pipeline, celestial_pipeline, celestial_buffer, + end_sky: end_sky::EndSky::default(), stars, panorama, border_pipeline, @@ -3310,6 +3315,9 @@ impl Renderer { ); } let celestial_vertices = frame.celestial.len().min(2048 * 4); + if frame.end_sky && !frame.title { + self.end_sky.prepare(&self.device, frame.end_sky_sprite); + } if celestial_vertices > 0 { self.uploads.buffer( &mut encoder, @@ -3510,12 +3518,17 @@ impl Renderer { if frame.title { self.panorama.draw(&mut pass); pass.set_bind_group(0, &self.group, &[]); - } else if celestial_vertices > 0 { + } else if celestial_vertices > 0 || frame.end_sky { pass.set_pipeline(&self.celestial_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.set_vertex_buffer(0, self.celestial_buffer.slice(..)); - pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1); + if frame.end_sky { + self.end_sky.draw(&mut pass); + } + if celestial_vertices > 0 { + pass.set_vertex_buffer(0, self.celestial_buffer.slice(..)); + pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1); + } pass.set_bind_group(0, &self.group, &[]); } if !frame.title && frame.stars.is_some() { diff --git a/crates/horizon-client/src/gfx/end_sky.rs b/crates/horizon-client/src/gfx/end_sky.rs new file mode 100644 index 000000000..15e9001fc --- /dev/null +++ b/crates/horizon-client/src/gfx/end_sky.rs @@ -0,0 +1,84 @@ +//! The End sky's six tiled faces, retained for the lifetime of the renderer's atlas. +use crate::mesher::Vertex; +use wgpu::util::DeviceExt; + +const VERTICES: u32 = 6 * 16 * 16 * 4; + +#[derive(Default)] +pub(super) struct EndSky { + mesh: Option<([f32; 4], wgpu::Buffer)>, +} + +impl EndSky { + /// Called only when the End sky is enabled. Rebuild on atlas UV changes; + /// resource reload and device recreation also replace the owning renderer. + pub(super) fn prepare(&mut self, device: &wgpu::Device, uv: Option<[f32; 4]>) { + let Some(uv) = uv else { + self.mesh = None; + return; + }; + if self.mesh.as_ref().is_some_and(|(old, _)| *old == uv) { + return; + } + let vertices = vertices(uv); + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("End sky vertices"), + contents: bytemuck::cast_slice(&vertices), + usage: wgpu::BufferUsages::VERTEX, + }); + self.mesh = Some((uv, buffer)); + } + + /// The celestial pipeline, atlas bind group and quad indices are already bound. + pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) { + if let Some((_, buffer)) = &self.mesh { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw_indexed(0..VERTICES / 4 * 6, 0, 0..1); + } + } +} + +/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times, +/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. +fn vertices(uv: [f32; 4]) -> Vec { + let mut out = Vec::with_capacity(VERTICES as usize); + use std::f32::consts::FRAC_PI_2; + let faces = [ + glam::Mat4::IDENTITY, + glam::Mat4::from_rotation_x(FRAC_PI_2), + glam::Mat4::from_rotation_x(-FRAC_PI_2), + glam::Mat4::from_rotation_x(std::f32::consts::PI), + glam::Mat4::from_rotation_z(FRAC_PI_2), + glam::Mat4::from_rotation_z(-FRAC_PI_2), + ]; + let step = 200.0 / 16.0; + for pose in faces { + for a in 0..16 { + for b in 0..16 { + let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32); + let (x1, z1) = (x0 + step, z0 + step); + let corners = [ + (x0, z0, [uv[0], uv[1]]), + (x0, z1, [uv[0], uv[3]]), + (x1, z1, [uv[2], uv[3]]), + (x1, z0, [uv[2], uv[1]]), + ]; + for (x, z, uv) in corners { + let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z)); + out.push(Vertex { + normal: [0; 4], + pos: p.to_array(), + uv, + layer: 2, + color: 0xFF28_2828, + light: 0, + }); + } + } + } + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/horizon-client/src/gfx/end_sky/tests.rs b/crates/horizon-client/src/gfx/end_sky/tests.rs new file mode 100644 index 000000000..d01fca18c --- /dev/null +++ b/crates/horizon-client/src/gfx/end_sky/tests.rs @@ -0,0 +1,330 @@ +use super::*; +use crate::gfx::{Globals, Renderer}; +use bytemuck::Zeroable; +use glam::Mat4; + +#[test] +fn geometry_matches_pre_residency_vertex_snapshots() { + use sha2::{Digest, Sha256}; + // Captured from game/end.rs at 34c3c1cf for full, tiled and non-binary UVs. + // Quantize positions only, avoiding platform sin/cos rounding differences; + // quad order, UVs, tint, material and light retain their exact byte values. + for (uv, expected) in [ + ( + [0.0, 0.0, 1.0, 1.0], + "f7ee23457fc557b33ecf09c9afaf858f3d8907e108abf06055f627523f733536", + ), + ( + [0.125, 0.25, 0.375, 0.5], + "f74c4b8d23ec2b7c11b5752821d0733851bf11358f1b26f9448226ff62a6a318", + ), + ( + [0.13, 0.27, 0.41, 0.59], + "f0aaa39c5b22168bdc7c6c329acb4d3598a2feb61ff7b6f2850b644682749b39", + ), + ] { + let mut mesh = vertices(uv); + assert_eq!(mesh.len(), VERTICES as usize); + for vertex in &mut mesh { + vertex.pos = vertex.pos.map(|x| { + let n = (x * 1024.0).round() / 1024.0; + if n == 0.0 { 0.0 } else { n } + }); + } + assert_eq!( + format!("{:x}", Sha256::digest(bytemuck::cast_slice(&mesh))), + expected + ); + } +} + +fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?; + eprintln!("End sky test adapter: {:?}", adapter.get_info()); + pollster::block_on(adapter.request_device(&Default::default())).ok() +} + +#[test] +fn resident_buffer_survives_frames_and_refreshes_with_the_atlas() { + let Some((device, _)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let mut sky = EndSky::default(); + let uv = [0.125, 0.25, 0.375, 0.5]; + sky.prepare(&device, Some(uv)); + let first = sky.mesh.as_ref().unwrap().1.clone(); + assert_eq!( + first.size(), + u64::from(VERTICES) * size_of::() as u64 + ); + // Immutable: steady-state frames cannot upload into this buffer. + assert_eq!(first.usage(), wgpu::BufferUsages::VERTEX); + for _ in 0..600 { + sky.prepare(&device, Some(uv)); + assert_eq!(sky.mesh.as_ref().unwrap().1, first); + } + let moved = [0.5, 0.5, 0.75, 0.75]; + sky.prepare(&device, Some(moved)); + assert_ne!(sky.mesh.as_ref().unwrap().1, first); + assert_eq!(sky.mesh.as_ref().unwrap().0, moved); + sky.prepare(&device, None); + assert!(sky.mesh.is_none()); + sky.prepare(&device, Some(uv)); + assert_ne!(sky.mesh.as_ref().unwrap().1, first); + // A resource reload/device recreation starts a new renderer-owned cache, + // even if the replacement atlas happens to use exactly the same UVs. + let mut replacement = EndSky::default(); + replacement.prepare(&device, Some(uv)); + assert_ne!( + replacement.mesh.as_ref().unwrap().1, + sky.mesh.as_ref().unwrap().1 + ); +} + +/// The actual entity shader and celestial blend, comparing the old combined +/// vertex stream with a resident sky draw followed by a separate flash draw. +#[test] +fn separate_draws_match_combined_celestial_pixels() { + let Some((device, queue)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("End sky differential shader"), + source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()), + }); + let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4]; + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("End sky differential pipeline"), + layout: None, + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_entity"), + compilation_options: Default::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &attributes, + })], + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_celestial"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent::OVER, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + let texture = |pixels: &[u8], width, height| { + device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + pixels, + ) + }; + // Asymmetric, translucent texels expose UV/winding and blend-order errors. + let pixels: Vec = (0..16 * 16) + .flat_map(|i| { + [ + (i * 17) as u8, + (i * 31) as u8, + (i * 7) as u8, + (80 + i % 176) as u8, + ] + }) + .collect(); + let atlas = texture(&pixels, 16, 16).create_view(&Default::default()); + let lightmap = texture(&[255; 4], 1, 1).create_view(&Default::default()); + let sampler = device.create_sampler(&Default::default()); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&atlas), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&lightmap), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let indices = Renderer::quad_indices(&device, VERTICES / 4 + 1); + let mut resident = EndSky::default(); + let uv = [0.125, 0.25, 0.375, 0.5]; + resident.prepare(&device, Some(uv)); + let first = resident.mesh.as_ref().unwrap().1.clone(); + let render = |sky: &EndSky, flash: &[Vertex], combined: bool| { + let target = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 64, + height: 64, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = target.create_view(&Default::default()); + let mut vertices = if combined { vertices(uv) } else { Vec::new() }; + vertices.extend_from_slice(flash); + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(&vertices), + usage: wgpu::BufferUsages::VERTEX, + }); + let readback = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 64 * 64 * 4, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })], + ..Default::default() + }); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &group, &[]); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + if !combined { + sky.draw(&mut pass); + } + if !vertices.is_empty() { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw_indexed(0..vertices.len() as u32 / 4 * 6, 0, 0..1); + } + } + encoder.copy_texture_to_buffer( + target.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &readback, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(256), + rows_per_image: Some(64), + }, + }, + target.size(), + ); + queue.submit([encoder.finish()]); + readback + .slice(..) + .map_async(wgpu::MapMode::Read, |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + readback.slice(..).get_mapped_range().unwrap().to_vec() + }; + let mut cases = 0; + let mut visible_flash_cases = 0; + for yaw in [0.0_f32, 45.0, 90.0, 180.0, 270.0] { + for pitch in [-85.0_f32, -30.0, 0.0, 45.0, 85.0] { + let mut globals = Globals::zeroed(); + globals.view_proj = (Mat4::perspective_rh(90_f32.to_radians(), 1.0, 0.05, 1024.0) + * Mat4::from_rotation_x(pitch.to_radians()) + * Mat4::from_rotation_y(yaw.to_radians())) + .to_cols_array_2d(); + queue.write_buffer(&uniform, 0, bytemuck::bytes_of(&globals)); + let no_flash = render(&resident, &[], true); + for level in [0_u32, 1, 127, 255] { + let flash: Vec<_> = if level == 0 { + Vec::new() + } else { + // Same flash size/height, with an arbitrary EndFlashState pose. + let pose = Mat4::from_rotation_y(1.3) * Mat4::from_rotation_x(-1.6); + [(-60.0, -60.0), (60.0, -60.0), (60.0, 60.0), (-60.0, 60.0)] + .map(|(x, z)| Vertex { + pos: pose.transform_point3(glam::vec3(x, 100.0, z)).to_array(), + uv: [0.75 + x / 480.0, 0.75 + z / 480.0], + layer: 2, + color: level * 0x01010101, + light: 0, + normal: [0; 4], + }) + .to_vec() + }; + resident.prepare(&device, Some(uv)); + let expected = render(&resident, &flash, true); + let actual = render(&resident, &flash, false); + visible_flash_cases += usize::from(expected != no_flash); + assert_eq!(actual, expected, "yaw={yaw} pitch={pitch} flash={level}"); + assert!( + actual.chunks_exact(4).any(|p| p[..3] != [0; 3]), + "empty frame" + ); + assert_eq!(resident.mesh.as_ref().unwrap().1, first); + cases += 1; + } + } + } + assert!( + visible_flash_cases > 0, + "the flash must affect the comparison" + ); + eprintln!("{cases} combined/resident framebuffer cases matched exactly"); +}