From 230730d1f5324ed3fc7a658e384767f6d706e713 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 04:02:13 +0100 Subject: [PATCH] Shader packs, clean room 23: the sun and moon (gbuffers_skytextured) gbuffers_skytextured (or gbuffers_textured, gbuffers_basic) draws the frame's sun and moon quads, with their render stages, `texture` reading the shared atlas their sprites live in. The sky's parts draw in vanilla's order (disc, sunset, sun, moon, stars, void), in one render pass while consecutive programs write the same buffers. The sun and moon add to the sky (SRC_ALPHA, ONE) unless blend. says otherwise. Horizon's world pass skips its own sun and moon when the pack draws them; a part without a program stays Horizon's. Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1, 2.3, 5.4; no other loader's code read. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 15 +- crates/horizon-client/src/gfx/pack_post.rs | 298 +++++++++++------- crates/horizon-client/src/gfx/pack_sky.rs | 136 ++++++-- crates/horizon-shaders/src/lib.rs | 4 +- crates/horizon-shaders/src/post.rs | 35 +- .../tests/packs/terrain-test/README.md | 3 +- .../shaders/gbuffers_textured.fsh | 15 + .../shaders/gbuffers_textured.vsh | 10 + crates/horizon-shaders/tests/real_packs.rs | 6 +- 9 files changed, 370 insertions(+), 152 deletions(-) create mode 100644 crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_textured.fsh create mode 100644 crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_textured.vsh diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 7444b136a..bdd8250b8 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -2792,7 +2792,13 @@ impl Renderer { buffers: if flat { &buffers[..1] } else { &buffers }, table: self.flat.as_ref().filter(|_| flat).map(|f| &f.draw_layout), depth_write: true, + atlas: None, }), + celestial: self + .hud + .atlas_texture + .as_ref() + .map(|t| t.create_view(&Default::default())), }; pack_post::PackPost::new( &self.device, @@ -2815,6 +2821,7 @@ impl Renderer { horizon_shaders::GameInputs { terrain: self.pack_terrain_inputs(), sky: Some(pack_sky::inputs()), + celestial: Some(pack_sky::celestial_inputs()), } } @@ -3739,6 +3746,12 @@ impl Renderer { .as_ref() .and_then(|p| p.1.as_ref()) .is_some_and(|p| p.has_sky()); + let pack_draws_celestial = pack_post + && self + .pack_post + .as_ref() + .and_then(|p| p.1.as_ref()) + .is_some_and(|p| p.has_celestial()); let pack_draws_water = pack_draws_terrain && self .pack_post @@ -3814,7 +3827,7 @@ impl Renderer { if frame.end_sky { self.end_sky.draw(&mut pass); } - if celestial_vertices > 0 { + if celestial_vertices > 0 && !pack_draws_celestial { pass.set_vertex_buffer(0, self.celestial_buffer.slice(..)); pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1); } diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index 2334b84c9..9002ad963 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -121,12 +121,13 @@ fn share_samplers(module: &mut naga::Module, slot: &HashMap) { } } -/// The game's geometry a gbuffers pass draws. -#[derive(Clone, Copy, PartialEq)] -enum Gbuffers { - Sky, - Terrain, - Water, +/// The sky's geometry and the programs that draw it: `gbuffers_skybasic` (disc, sunset, stars, +/// void) and `gbuffers_skytextured` (sun, moon), each with its fallbacks. A part without a +/// program is Horizon's own. +struct Sky { + geometry: PackSky, + basic: Option, + textured: Option, } struct Pass { @@ -151,6 +152,8 @@ struct Pass { mipmaps: u16, /// Reads the per-draw block (`DrawUniforms`). draw: bool, + /// What `texture` reads instead of the block atlas. + atlas: Option, groups: HashMap, } @@ -181,6 +184,8 @@ pub(super) struct World<'a> { pub lightmap: wgpu::TextureView, /// Terrain's geometry, when the pack draws it. pub terrain: Option>, + /// The atlas of the sun and moon's sprites. + pub celestial: Option, } pub struct PackPost { @@ -191,7 +196,7 @@ pub struct PackPost { /// What draws translucent terrain (`gbuffers_water` or its fallback), after `deferred`. water: Option, /// What draws the sky (`gbuffers_skybasic` or its fallback), before terrain, and its vertices. - sky: Option<(Pass, PackSky)>, + sky: Option, /// A program after translucent terrain reads `depthtex1`: it is copied before water. depth1: bool, /// Buffers with mipmaps (filterable ones a program asks them for). @@ -494,6 +499,8 @@ pub(super) struct Geometry<'a> { pub table: Option<&'a wgpu::BindGroupLayout>, /// Writes depth (the sky does not). pub depth_write: bool, + /// What `texture` reads instead of the block atlas. + pub atlas: Option, } /// The pass of program `p`: a quad, or `geometry` drawn by the game. `None` (with a note) when @@ -737,6 +744,7 @@ fn build_pass( written, mipmaps: p.mipmaps, draw, + atlas: geometry.and_then(|g| g.atlas.clone()), groups: HashMap::new(), }) } @@ -796,15 +804,29 @@ impl PackPost { .water .zip(world.terrain.as_ref()) .and_then(|(p, g)| build(p, Some(g))); - let sky = post.sky.and_then(|p| { - let sky = PackSky::new(device); - let geometry = Geometry { + let sky = (post.sky.is_some() || post.sky_textured.is_some()).then(|| { + let geometry = PackSky::new(device); + let basic = Geometry { buffers: &PackSky::buffers(), - table: Some(&sky.layout), + table: Some(&geometry.layout), depth_write: false, + atlas: None, }; - Some((build(p, Some(&geometry))?, sky)) + let basic = post.sky.and_then(|p| build(p, Some(&basic))); + let textured = Geometry { + buffers: &PackSky::celestial_buffers(), + table: None, + depth_write: false, + atlas: world.celestial.clone(), + }; + let textured = post.sky_textured.and_then(|p| build(p, Some(&textured))); + Sky { + geometry, + basic, + textured, + } }); + let sky = sky.filter(|s| s.basic.is_some() || s.textured.is_some()); // Developers' aid: `HORIZON_SHADER_PACK_SKIP=composite,final` leaves programs out. let skip = std::env::var("HORIZON_SHADER_PACK_SKIP").unwrap_or_default(); let passes: Vec = post @@ -819,8 +841,13 @@ impl PackPost { if let Some(w) = &water { notes.push(format!("translucent terrain draws with {}", w.name)); } - if let Some((s, _)) = &sky { - notes.push(format!("the sky draws with {}", s.name)); + for (part, pass) in sky + .iter() + .flat_map(|s| [("sky", &s.basic), ("sun and moon", &s.textured)]) + { + if let Some(p) = pass { + notes.push(format!("the {part} draw with {}", p.name)); + } } let depth1 = water.is_some() && passes @@ -837,7 +864,7 @@ impl PackPost { // Gbuffers passes cover part of their targets: a clear is needed if they touch it. let first = sky .iter() - .map(|s| &s.0) + .flat_map(|s| s.basic.iter().chain(&s.textured)) .chain(&terrain) .chain(&water) .find(touched) @@ -1083,7 +1110,11 @@ impl PackPost { Source::Noise => &self.noise, Source::Dummy => &self.dummy, Source::Shadow => &self.shadow.0, - Source::Atlas => self.atlas.as_ref().unwrap_or(&self.dummy), + Source::Atlas => pass + .atlas + .as_ref() + .or(self.atlas.as_ref()) + .unwrap_or(&self.dummy), Source::Lightmap => &self.lightmap, }; let sampler = match SamplerKind::of(s.source, s.filtering) { @@ -1113,46 +1144,12 @@ impl PackPost { group.clone() } - /// The sky, terrain or translucent terrain with the pack's program into the buffers it - /// writes, in place, tested against the world's depth; `draw` issues the game's terrain - /// draws (`true`: translucent), the sky draws itself. - #[allow(clippy::too_many_arguments)] - fn draw_gbuffers( + /// A render pass into the buffers `pass` writes, in place, tested against the world's depth. + fn begin<'e>( &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - size: [u32; 2], - frame: &super::Frame, - which: Gbuffers, - draw: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool), - ) { - let translucent = which == Gbuffers::Water; - let (mut pass, sky) = match which { - Gbuffers::Sky => match self.sky.take() { - Some((pass, sky)) => (pass, Some(sky)), - None => return, - }, - Gbuffers::Terrain => match self.terrain.take() { - Some(pass) => (pass, None), - None => return, - }, - Gbuffers::Water => match self.water.take() { - Some(pass) => (pass, None), - None => return, - }, - }; - if translucent - && let Some(t) = &self.targets - && let Some((copy, _)) = &t.depth1 - { - encoder.copy_texture_to_texture( - t.depth_texture.as_image_copy(), - copy.as_image_copy(), - t.depth_texture.size(), - ); - } - let group = self.bind(device, queue, &mut pass, size); + encoder: &'e mut wgpu::CommandEncoder, + pass: &Pass, + ) -> wgpu::RenderPass<'e> { let targets = self.targets.as_ref().expect("resized"); let load = wgpu::Operations { load: wgpu::LoadOp::Load, @@ -1168,52 +1165,128 @@ impl PackPost { .as_ref() .and_then(|t| attach(&t[usize::from(self.main & 1 << buffer != 0)], load)); } - { - let timestamp_writes = self.timing.as_mut().and_then(|t| t.writes(&pass.name)); - let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some(&pass.name), - color_attachments: &attachments, - timestamp_writes, - depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &targets.depth, - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }), - stencil_ops: None, + let timestamp_writes = self.timing.as_mut().and_then(|t| t.writes(&pass.name)); + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(&pass.name), + color_attachments: &attachments, + timestamp_writes, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &targets.depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, }), - ..Default::default() - }); + stencil_ops: None, + }), + ..Default::default() + }) + } + + /// Terrain (or, `translucent`, translucent terrain) with the pack's program; `draw` issues + /// the game's draws. + fn draw_terrain( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + size: [u32; 2], + translucent: bool, + draw: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool), + ) { + let slot = if translucent { + &mut self.water + } else { + &mut self.terrain + }; + let Some(mut pass) = slot.take() else { + return; + }; + if translucent + && let Some(t) = &self.targets + && let Some((copy, _)) = &t.depth1 + { + encoder.copy_texture_to_texture( + t.depth_texture.as_image_copy(), + copy.as_image_copy(), + t.depth_texture.size(), + ); + } + let group = self.bind(device, queue, &mut pass, size); + { + let mut rp = self.begin(encoder, &pass); rp.set_pipeline(&pass.pipeline); rp.set_bind_group(0, &group, &[]); - let draws = pass.draw.then_some(&self.draws); - match &sky { - Some(sky) => sky.draw(queue, &mut rp, frame, &|rp, stage| { - if let Some(d) = draws { - d.bind(rp, stage); - } - }), - None => { - if let Some(d) = draws { - let stage = if translucent { - "TERRAIN_TRANSLUCENT" - } else { - "TERRAIN_SOLID" - }; - d.bind(&mut rp, stage); - } - draw(&mut rp, translucent); - } + if pass.draw { + let stage = if translucent { + "TERRAIN_TRANSLUCENT" + } else { + "TERRAIN_SOLID" + }; + self.draws.bind(&mut rp, stage); } + draw(&mut rp, translucent); } self.mips_valid &= !pass.written; - match (which, sky) { - (Gbuffers::Sky, Some(sky)) => self.sky = Some((pass, sky)), - (Gbuffers::Water, _) => self.water = Some(pass), - _ => self.terrain = Some(pass), + if translucent { + self.water = Some(pass); + } else { + self.terrain = Some(pass); } } + /// The sky's parts in vanilla's order, each with the program that draws it; one render pass + /// while consecutive programs write the same buffers. + fn draw_sky( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + size: [u32; 2], + frame: &super::Frame, + ) { + let Some(mut sky) = self.sky.take() else { + return; + }; + let parts = sky.geometry.prepare(queue, frame); + let mut groups = [None, None]; + for (i, pass) in [&mut sky.basic, &mut sky.textured].into_iter().enumerate() { + if let Some(pass) = pass { + groups[i] = Some(self.bind(device, queue, pass, size)); + self.mips_valid &= !pass.written; + } + } + let passes = [&sky.basic, &sky.textured]; + let mut open: Option<(wgpu::RenderPass<'_>, usize)> = None; + for part in parts { + let i = usize::from(part.textured); + let (Some(pass), Some(group)) = (passes[i], &groups[i]) else { + continue; + }; + let current = open.as_ref().map(|o| o.1); + if current != Some(i) { + let same = current + .and_then(|c| passes[c].as_ref()) + .is_some_and(|p| p.writes == pass.writes); + if !same { + drop(open.take()); + open = Some((self.begin(encoder, pass).forget_lifetime(), i)); + } + let rp = &mut open.as_mut().expect("open").0; + rp.set_pipeline(&pass.pipeline); + rp.set_bind_group(0, group, &[]); + sky.geometry.bind(rp, part.textured); + open.as_mut().expect("open").1 = i; + } + let rp = &mut open.as_mut().expect("open").0; + if pass.draw { + self.draws.bind(rp, part.stage); + } + rp.draw(part.range, 0..1); + } + drop(open); + self.sky = Some(sky); + } + /// The sky, when it shows, then terrain. fn draw_opaque( &mut self, @@ -1225,17 +1298,9 @@ impl PackPost { terrain: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool), ) { if super::sky_visible(frame) { - self.draw_gbuffers(device, queue, encoder, size, frame, Gbuffers::Sky, terrain); + self.draw_sky(device, queue, encoder, size, frame); } - self.draw_gbuffers( - device, - queue, - encoder, - size, - frame, - Gbuffers::Terrain, - terrain, - ); + self.draw_terrain(device, queue, encoder, size, false, terrain); } /// Regenerates the mip chain of buffer `b`'s side that programs read. @@ -1269,9 +1334,14 @@ impl PackPost { self.terrain.is_some() } - /// Whether the pack draws the sky itself. + /// Whether the pack draws the sky (disc, sunset, stars, void) itself. pub fn has_sky(&self) -> bool { - self.sky.is_some() + self.sky.as_ref().is_some_and(|s| s.basic.is_some()) + } + + /// Whether the pack draws the sun and moon itself. + pub fn has_celestial(&self) -> bool { + self.sky.as_ref().is_some_and(|s| s.textured.is_some()) } /// Whether the pack draws translucent terrain itself. @@ -1521,15 +1591,7 @@ impl PackPost { } if !water_drawn && matches!(pass.group, Group::Composite | Group::Final) { water_drawn = true; - self.draw_gbuffers( - device, - queue, - encoder, - size, - frame, - Gbuffers::Water, - terrain, - ); + self.draw_terrain(device, queue, encoder, size, true, terrain); } if pass.group == Group::Deferred && !seen.0 { seen.0 = true; @@ -1584,15 +1646,7 @@ impl PackPost { self.draw_opaque(device, queue, encoder, size, frame, terrain); } if !water_drawn { - self.draw_gbuffers( - device, - queue, - encoder, - size, - frame, - Gbuffers::Water, - terrain, - ); + self.draw_terrain(device, queue, encoder, size, true, terrain); } let targets = self.targets.as_ref().expect("resized"); let view = |m: u16, i: usize, alt: bool| { diff --git a/crates/horizon-client/src/gfx/pack_sky.rs b/crates/horizon-client/src/gfx/pack_sky.rs index cd99d03b9..007fdc034 100644 --- a/crates/horizon-client/src/gfx/pack_sky.rs +++ b/crates/horizon-client/src/gfx/pack_sky.rs @@ -1,7 +1,8 @@ //! The vanilla sky's geometry for a shader pack's `gbuffers_skybasic` (spec 2.3): the sky disc, //! the sunset fan, the stars and the void disc, as Horizon's own sky draws them (terrain.wgsl, //! stars.rs), built once into a vertex buffer. The frame's colours and rotations sit in a small -//! uniform (set 1) that the vertex inputs read. +//! uniform (set 1) that the vertex inputs read. `gbuffers_skytextured` draws the frame's sun and +//! moon quads, textured from the shared atlas. use std::ops::Range; @@ -36,6 +37,21 @@ struct Uniform { sun: [f32; 4], } +/// A sun or moon vertex: position, atlas UV, RGBA8 colour. +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Celestial { + pos: [f32; 3], + uv: [f32; 2], + color: u32, +} + +/// Quads of the sun and moon (and room to spare). +const CELESTIAL_QUADS: usize = 4; + +const CELESTIAL_ATTRIBUTES: [wgpu::VertexAttribute; 3] = + wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Unorm8x4]; + pub(super) const ATTRIBUTES: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint32]; @@ -83,6 +99,37 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs { } } +/// What `gbuffers_skytextured` reads from the sun and moon's vertices. +pub fn celestial_inputs() -> horizon_shaders::GbuffersInputs { + horizon_shaders::GbuffersInputs { + declarations: + "layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\ + layout(location = 2) in vec4 hz_v_color;\n" + .into(), + body: " hz_Vertex = vec4(hz_v_pos, 1.0);\n \ + hz_MultiTexCoord0 = vec4(hz_v_uv, 0.0, 1.0);\n \ + hz_MultiTexCoord1 = vec4(0.0, 240.0, 0.0, 1.0);\n \ + hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \ + hz_Color = hz_v_color;\n \ + hz_Normal = vec3(0.0, 0.0, 1.0);\n" + .into(), + attributes: vec![ + ("vaPosition".into(), "hz_Vertex.xyz".into()), + ("vaUV0".into(), "hz_v_uv".into()), + ("vaColor".into(), "hz_Color".into()), + ("vaNormal".into(), "hz_Normal".into()), + ], + after: " gl_Position.z = gl_Position.w;\n".into(), + } +} + +/// One draw of the sky: its render stage, whether `gbuffers_skytextured` draws it, its vertices. +pub(super) struct Part { + pub stage: &'static str, + pub textured: bool, + pub range: Range, +} + /// A disc fan at height `y`, radius 512, as triangles (SkyRenderer's sky and void discs). fn disc(y: f32, kind: u32, out: &mut Vec) { let sign = y.signum(); @@ -104,6 +151,7 @@ fn disc(y: f32, kind: u32, out: &mut Vec) { pub(super) struct PackSky { vertices: wgpu::Buffer, + celestial: wgpu::Buffer, uniform: wgpu::Buffer, pub layout: wgpu::BindGroupLayout, group: wgpu::BindGroup, @@ -144,6 +192,12 @@ impl PackSky { contents: bytemuck::cast_slice(&v), usage: wgpu::BufferUsages::VERTEX, }); + let celestial = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack sun and moon"), + size: (std::mem::size_of::() * 6 * CELESTIAL_QUADS) as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); let uniform = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Shader pack sky"), size: std::mem::size_of::() as u64, @@ -173,6 +227,7 @@ impl PackSky { }); Self { vertices, + celestial, uniform, layout, group, @@ -188,15 +243,18 @@ impl PackSky { })] } - /// Draws the frame's sky, each part with its render stage: the disc, the sunset fan while - /// the sun is near the horizon, the stars and, with the camera low, the void. - pub fn draw( - &self, - queue: &wgpu::Queue, - pass: &mut wgpu::RenderPass<'_>, - frame: &super::Frame, - stage: &dyn Fn(&mut wgpu::RenderPass<'_>, &str), - ) { + pub fn celestial_buffers() -> [Option>; 1] { + [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &CELESTIAL_ATTRIBUTES, + })] + } + + /// Writes the frame's sky and returns its draws in vanilla's order: the disc, the sunset + /// fan while the sun is near the horizon, the sun and the moon, the stars and, with the + /// camera low, the void. + pub fn prepare(&self, queue: &wgpu::Queue, frame: &super::Frame) -> Vec { let sun_angle = frame.sky.sun_angle.to_radians(); // The fan turns to the other horizon in the afternoon (terrain.wgsl's sunrise_weight). let flip = if sun_angle.sin() < 0.0 { 180f32 } else { 0.0 }; @@ -210,20 +268,52 @@ impl PackSky { sun: [theta.cos(), theta.sin(), brightness.clamp(0.0, 1.0), 0.0], }; queue.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniform)); - pass.set_bind_group(1, &self.group, &[]); - pass.set_vertex_buffer(0, self.vertices.slice(..)); + // The sun's quad, then the moon's (Game::celestial_geometry), as triangles. + let quads = frame + .celestial + .as_chunks::<4>() + .0 + .iter() + .take(CELESTIAL_QUADS); + let triangles: Vec = quads + .clone() + .flat_map(|q| [0, 1, 2, 0, 2, 3].map(|i| q[i])) + .map(|v| Celestial { + pos: v.pos, + uv: v.uv, + color: v.color, + }) + .collect(); + queue.write_buffer(&self.celestial, 0, bytemuck::cast_slice(&triangles)); let [sky, sunset, stars, void] = self.ranges.clone(); - let parts = [ - ("SKY", sky, true), - ("SUNSET", sunset, frame.sky.sunrise_color[3] > 0.001), - ("STARS", stars, frame.stars.is_some()), - ("VOID", void, frame.dark_disc), - ]; - for (name, range, shown) in parts { - if shown { - stage(pass, name); - pass.draw(range, 0..1); - } + let part = |stage, textured, range| Part { + stage, + textured, + range, + }; + let mut parts = vec![part("SKY", false, sky)]; + if frame.sky.sunrise_color[3] > 0.001 { + parts.push(part("SUNSET", false, sunset)); + } + for (i, stage) in ["SUN", "MOON"].into_iter().enumerate().take(quads.len()) { + parts.push(part(stage, true, i as u32 * 6..i as u32 * 6 + 6)); + } + if frame.stars.is_some() { + parts.push(part("STARS", false, stars)); + } + if frame.dark_disc { + parts.push(part("VOID", false, void)); + } + parts + } + + /// Binds the vertices of the `textured` (sun and moon) or other parts. + pub fn bind(&self, pass: &mut wgpu::RenderPass<'_>, textured: bool) { + if textured { + pass.set_vertex_buffer(0, self.celestial.slice(..)); + } else { + pass.set_bind_group(1, &self.group, &[]); + pass.set_vertex_buffer(0, self.vertices.slice(..)); } } } diff --git a/crates/horizon-shaders/src/lib.rs b/crates/horizon-shaders/src/lib.rs index 853f2f2ba..f33dfec57 100644 --- a/crates/horizon-shaders/src/lib.rs +++ b/crates/horizon-shaders/src/lib.rs @@ -34,8 +34,8 @@ pub use macros::{MC_VERSION, Macros, RENDER_STAGES, render_stage}; pub use options::switches_on; pub use pack::{Pack, PackError}; pub use post::{ - Blend, Factor, GameInputs, Group, Post, PostProgram, TRANSLUCENT_BLEND, dimension_folder, - load_post, + Blend, CELESTIAL_BLEND, Factor, GameInputs, Group, Post, PostProgram, TRANSLUCENT_BLEND, + dimension_folder, load_post, }; pub use preprocess::{Diagnostic, Origin, Preprocessed, preprocess}; pub use properties::{Entry, Note, Properties}; diff --git a/crates/horizon-shaders/src/post.rs b/crates/horizon-shaders/src/post.rs index 56303e67b..944cf10b8 100644 --- a/crates/horizon-shaders/src/post.rs +++ b/crates/horizon-shaders/src/post.rs @@ -96,6 +96,21 @@ const TERRAIN: [&str; 4] = [ /// `gbuffers_skybasic` and its fallback (2.3). const SKY: [&str; 2] = ["gbuffers_skybasic", "gbuffers_basic"]; +/// `gbuffers_skytextured` and its fallbacks (2.3). +const SKY_TEXTURED: [&str; 3] = [ + "gbuffers_skytextured", + "gbuffers_textured", + "gbuffers_basic", +]; + +/// The sun and moon's default blend: added to the sky, as vanilla draws them. +pub const CELESTIAL_BLEND: Blend = [ + Factor::SrcAlpha, + Factor::One, + Factor::One, + Factor::OneMinusSrcAlpha, +]; + const GROUPS: [(Group, &str); 4] = [ (Group::Prepare, "prepare"), (Group::Deferred, "deferred"), @@ -132,6 +147,8 @@ pub struct Post { pub water: Option, /// What draws the sky (disc, sunset, stars, void) before terrain. pub sky: Option, + /// What draws the sun and moon, between the sunset and the stars. + pub sky_textured: Option, /// The custom uniforms of `shaders.properties` (3.4). pub custom: Custom, pub config: Config, @@ -156,6 +173,7 @@ pub fn dimension_folder(pack: &Pack, id: i32) -> String { pub struct GameInputs { pub terrain: Option, pub sky: Option, + pub celestial: Option, } /// Loads the post-processing programs of `folder` and, for the geometry `inputs` describes, the @@ -175,6 +193,7 @@ pub fn load_post( terrain: None, water: None, sky: None, + sky_textured: None, custom: Custom::parse(properties), config: Config::default(), notes: Vec::new(), @@ -221,6 +240,12 @@ pub fn load_post( p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_BLEND)); p }); + let celestial = inputs.celestial.as_ref(); + let sky_textured = celestial.and_then(|i| gbuffers(&SKY_TEXTURED, Group::Gbuffers, i)); + let sky_textured = sky_textured.map(|mut p| { + p.blend = blend(properties, &p.name).unwrap_or(Some(CELESTIAL_BLEND)); + p + }); if let Some(inputs) = &inputs.terrain { let terrain = gbuffers(&TERRAIN, Group::Gbuffers, inputs); // gbuffers_water falls back to gbuffers_terrain's chain (2.3). @@ -235,6 +260,7 @@ pub fn load_post( } } loader.post.sky = sky; + loader.post.sky_textured = sky_textured; post.config = std::mem::take(&mut post.config).finish(); post } @@ -511,7 +537,8 @@ mod tests { }; let inputs = GameInputs { terrain: Some(inputs.clone()), - sky: Some(inputs), + sky: Some(inputs.clone()), + celestial: Some(inputs), }; let post = load_post(&pack, "", &Properties::default(), ¯os, &inputs); let (terrain, water) = (post.terrain.unwrap(), post.water.unwrap()); @@ -526,6 +553,12 @@ mod tests { Some(TRANSLUCENT_BLEND) ) ); + // gbuffers_skytextured falls back to gbuffers_textured, then gbuffers_basic. + let sun = post.sky_textured.unwrap(); + assert_eq!( + (sun.name.as_str(), sun.blend), + ("gbuffers_textured", Some(CELESTIAL_BLEND)) + ); assert_eq!( (water.group, water.blend), (Group::Translucent, Some(TRANSLUCENT_BLEND)) diff --git a/crates/horizon-shaders/tests/packs/terrain-test/README.md b/crates/horizon-shaders/tests/packs/terrain-test/README.md index 3fc37bf4d..7d2c168cb 100644 --- a/crates/horizon-shaders/tests/packs/terrain-test/README.md +++ b/crates/horizon-shaders/tests/packs/terrain-test/README.md @@ -5,6 +5,7 @@ Horizon's own shader pack for testing gbuffers terrain (written for Horizon, no the lightmap coordinate's sky light (cooler where the sky is hidden); `mc_midTexCoord` marks each face's centre with a dot, and any stage but solid terrain (translucent terrain falls back to it) is red. `gbuffers_skybasic` draws the sky in its vertex colour, a little greener, with magenta -stars and a dark red void. `composite` puts the depth buffer's view-space distance into the blue +stars and a dark red void; `gbuffers_textured` (the fallback of `gbuffers_skytextured`) the sun, +and the moon tinted green. `composite` puts the depth buffer's view-space distance into the blue channel of the far half. Copy the folder into `shaderpacks/` and run the game with `HORIZON_SHADER_PACK=terrain-test`. diff --git a/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_textured.fsh b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_textured.fsh new file mode 100644 index 000000000..563ddeb7c --- /dev/null +++ b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_textured.fsh @@ -0,0 +1,15 @@ +#version 120 + +uniform sampler2D texture; +uniform int renderStage; + +varying vec2 texcoord; +varying vec4 glcolor; + +void main() { + vec4 color = texture2D(texture, texcoord) * glcolor; + // The moon tinted green: the sun and the moon are told apart. + if (renderStage == MC_RENDER_STAGE_MOON) color.rb *= 0.3; + /* DRAWBUFFERS:0 */ + gl_FragData[0] = color; +} diff --git a/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_textured.vsh b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_textured.vsh new file mode 100644 index 000000000..c29b1bba0 --- /dev/null +++ b/crates/horizon-shaders/tests/packs/terrain-test/shaders/gbuffers_textured.vsh @@ -0,0 +1,10 @@ +#version 120 + +varying vec2 texcoord; +varying vec4 glcolor; + +void main() { + gl_Position = ftransform(); + texcoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy; + glcolor = gl_Color; +} diff --git a/crates/horizon-shaders/tests/real_packs.rs b/crates/horizon-shaders/tests/real_packs.rs index a04a31b15..5ed954898 100644 --- a/crates/horizon-shaders/tests/real_packs.rs +++ b/crates/horizon-shaders/tests/real_packs.rs @@ -171,15 +171,17 @@ fn real_packs_read() { }; let inputs = horizon_shaders::GameInputs { terrain: Some(terrain.clone()), - sky: Some(terrain), + sky: Some(terrain.clone()), + celestial: Some(terrain), }; let post = load_post(&pack, &folder, &shaders, &Macros::standard(), &inputs); println!( - " dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, water {:?}, sky {:?}, {} notes, {:.0} ms", + " dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, water {:?}, sky {:?} {:?}, {} notes, {:.0} ms", post.programs.len(), post.terrain.as_ref().map(|t| &t.name), post.water.as_ref().map(|t| &t.name), post.sky.as_ref().map(|t| &t.name), + post.sky_textured.as_ref().map(|t| &t.name), post.notes.len() + post.config.notes.len(), start.elapsed().as_secs_f64() * 1000.0 );