Merge pull request #1786 from ludovic111/feat/shader-packs-weather

🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
This commit is contained in:
Ludovic Marie
2026-10-26 03:16:38 +01:00
committed by GitHub
5 changed files with 433 additions and 5 deletions
+35 -2
View File
@@ -75,6 +75,7 @@ mod pack_post;
mod pack_sky;
mod pack_timing;
pub mod pack_uniforms;
mod pack_weather;
mod page_runs;
pub mod panorama;
mod resident;
@@ -496,6 +497,8 @@ pub struct Renderer {
pack_entity_rest: Vec<Vertex>,
/// Set 1 of the cloud pipeline, for a shader pack's `gbuffers_clouds`.
cloud_bindings: wgpu::BindGroupLayout,
/// Rain and snow handed to a shader pack's `gbuffers_weather`, once a pack draws them.
pack_weather: Option<pack_weather::PackWeather>,
/// The block sprites as one atlas, while a shader pack is loaded.
pack_atlas: Option<pack_atlas::PackAtlas>,
/// The pack's terrain program reads flat draws' vertices (`pack_terrain_inputs`).
@@ -1514,7 +1517,10 @@ impl Renderer {
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
// COPY_SRC: a shader pack's weather copies the rain and snow sprites out.
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_DST
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
@@ -2397,6 +2403,7 @@ impl Renderer {
pack_post: None,
pack_entity_rest: Vec::new(),
cloud_bindings,
pack_weather: None,
pack_atlas: None,
pack_terrain_flat: false,
hud,
@@ -2873,6 +2880,7 @@ impl Renderer {
.as_ref()
.map(|t| t.create_view(&Default::default())),
clouds: Some(&self.cloud_bindings),
weather: true,
};
pack_post::PackPost::new(
&self.device,
@@ -2898,6 +2906,7 @@ impl Renderer {
celestial: Some(pack_sky::celestial_inputs()),
entities: Some(pack_entities::inputs()),
clouds: Some(pack_entities::cloud_inputs()),
weather: Some(pack_weather::inputs()),
}
}
@@ -3857,6 +3866,12 @@ impl Renderer {
.as_ref()
.and_then(|p| p.1.as_ref())
.is_some_and(|p| p.has_clouds());
let pack_draws_weather = pack_post
&& self
.pack_post
.as_ref()
.and_then(|p| p.1.as_ref())
.is_some_and(|p| p.has_weather());
let scaled = self.world_post.prepare(
&self.device,
[self.config.width, self.config.height],
@@ -4022,7 +4037,9 @@ impl Renderer {
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
self.weather.draw(&mut pass, &self.entity_group);
if !pack_draws_weather {
self.weather.draw(&mut pass, &self.entity_group);
}
pass.set_bind_group(0, &self.group, &[]);
if crumbling_quads > 0 {
pass.set_pipeline(&self.crumbling_pipeline);
@@ -4177,6 +4194,22 @@ impl Renderer {
&& let Some((dimension, Some(mut post))) = self.pack_post.take()
{
let size = self.world_post.size().unwrap_or([1, 1]);
let weather = match &self.hud.atlas_texture {
Some(atlas) if pack_draws_weather => self
.pack_weather
.get_or_insert_with(|| pack_weather::PackWeather::new(&self.device))
.prepare(
&self.device,
&mut encoder,
&mut self.uploads,
atlas,
frame.weather,
frame.weather_time,
&self.indices,
),
_ => None,
};
post.set_weather(weather);
let flat = self.flat.as_ref().filter(|_| flat_frame);
let pages: Vec<(u32, wgpu::Buffer)> = match flat {
Some(_) if pack_draws_terrain => self
+97 -1
View File
@@ -39,6 +39,7 @@ enum Source {
Lightmap,
}
#[derive(Clone)]
struct Binding {
source: Source,
binding: u32,
@@ -140,6 +141,7 @@ struct Entities {
late: [bool; PROGRAMS],
}
#[derive(Clone)]
struct Pass {
name: String,
group: Group,
@@ -204,6 +206,8 @@ pub(super) struct World<'a> {
pub celestial: Option<wgpu::TextureView>,
/// Set 1 of the clouds' draw: their offset and palette.
pub clouds: Option<&'a wgpu::BindGroupLayout>,
/// The game can hand its rain and snow to the pack.
pub weather: bool,
}
/// This frame's clouds, when the pack draws them: their vertices, uniform, quad indices and
@@ -215,6 +219,16 @@ pub(super) struct Clouds {
pub quads: u32,
}
/// This frame's rain and snow, when the pack draws them: their vertices, the quad indices, the
/// quads of each kind (rain, snow), each kind's sprite, and a number that changes with them.
pub(super) struct Weather {
pub vertices: wgpu::Buffer,
pub indices: wgpu::Buffer,
pub quads: [std::ops::Range<u32>; 2],
pub sprites: [Option<wgpu::TextureView>; 2],
pub generation: u64,
}
pub struct PackPost {
pub notes: Vec<String>,
passes: Vec<Pass>,
@@ -232,6 +246,11 @@ pub struct PackPost {
/// The pack has `gbuffers_clouds`, even one that writes nothing (a pack drawing its own
/// clouds discards vanilla's): the game's clouds are not drawn.
hides_clouds: bool,
/// What draws rain and snow (the same program, each with its kind's sprite as `texture`),
/// after translucent terrain, this frame's weather and the sprites' generation bound.
weather: Option<[Pass; 2]>,
weather_draw: Option<Weather>,
weather_generation: u64,
/// A program after translucent terrain reads `depthtex1`: it is copied before water.
depth1: bool,
/// Buffers with mipmaps (filterable ones a program asks them for).
@@ -970,6 +989,23 @@ impl PackPost {
cull: false,
});
let hides_clouds = post.clouds.is_some() && cloud_geometry.is_some();
let weather_geometry = world.weather.then(|| Geometry {
buffers: &entity_buffers,
table: None,
depth_write: true,
atlas: None,
ids: None,
cull: false,
});
let weather = post
.weather
.zip(weather_geometry.as_ref())
.and_then(|(p, g)| build(p, Some(g)))
.map(|rain| {
let mut snow = rain.clone();
snow.name = format!("{} (snow)", rain.name);
[rain, snow]
});
let clouds = post
.clouds
.zip(cloud_geometry.as_ref())
@@ -1005,6 +1041,9 @@ impl PackPost {
if let Some(c) = &clouds {
notes.push(format!("clouds draw with {}", c.name));
}
if let Some([w, _]) = &weather {
notes.push(format!("rain and snow draw with {}", w.name));
}
for (part, pass) in entities.iter().flat_map(|e| parts.iter().zip(&e.passes)) {
if let Some(p) = pass {
notes.push(format!("{part} draw with {}", p.name));
@@ -1015,6 +1054,7 @@ impl PackPost {
.iter()
.filter(|p| matches!(p.group, Group::Composite | Group::Final))
.chain(&water)
.chain(weather.iter().take(1).flatten())
.any(|p| p.samplers.iter().any(|s| s.source == Source::Depth1));
// A clear only matters when a program reads the buffer before one writes all of it
// (composite passes cover their whole target, terrain does not); the others are skipped.
@@ -1030,6 +1070,7 @@ impl PackPost {
.chain(entities.iter().flat_map(|e| e.passes.iter().flatten()))
.chain(&clouds)
.chain(&water)
.chain(weather.iter().take(1).flatten())
.find(touched)
.map(|_| true)
.or_else(|| {
@@ -1046,6 +1087,7 @@ impl PackPost {
|| sky.is_some()
|| entities.is_some()
|| clouds.is_some()
|| weather.is_some()
|| passes.iter().any(|p| {
p.samplers
.iter()
@@ -1145,6 +1187,9 @@ impl PackPost {
clouds,
cloud_draw: None,
hides_clouds,
weather,
weather_draw: None,
weather_generation: 0,
depth1,
mipped,
mips_valid: 0,
@@ -1613,6 +1658,57 @@ impl PackPost {
) {
self.draw_terrain(device, queue, encoder, size, true, terrain);
self.draw_entities(device, queue, encoder, size, true);
self.draw_weather(device, queue, encoder, size);
}
/// The rain, then the snow, `set_weather` gave for this frame, with `gbuffers_weather`.
fn draw_weather(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
size: [u32; 2],
) {
let (Some(mut passes), Some(weather)) = (self.weather.take(), self.weather_draw.take())
else {
return;
};
if weather.generation != self.weather_generation {
self.weather_generation = weather.generation;
for (pass, sprite) in passes.iter_mut().zip(&weather.sprites) {
pass.atlas = sprite.clone();
pass.groups.clear();
}
}
for (pass, quads) in passes.iter_mut().zip(weather.quads.clone()) {
if quads.is_empty() {
continue;
}
let group = self.bind(device, queue, pass, size);
{
let mut rp = self.begin(encoder, pass);
rp.set_pipeline(&pass.pipeline);
rp.set_bind_group(0, &group, &[]);
if pass.draw {
self.draws.bind(&mut rp, "RAIN_SNOW");
}
rp.set_vertex_buffer(0, weather.vertices.slice(..));
rp.set_index_buffer(weather.indices.slice(..), wgpu::IndexFormat::Uint32);
rp.draw_indexed(quads.start * 6..quads.end * 6, 0, 0..1);
}
self.mips_valid &= !pass.written;
}
self.weather = Some(passes);
}
/// Whether the pack draws rain and snow itself.
pub fn has_weather(&self) -> bool {
self.weather.is_some()
}
/// The rain and snow to draw this frame (`None`: none).
pub fn set_weather(&mut self, weather: Option<Weather>) {
self.weather_draw = weather;
}
/// Regenerates the mip chain of buffer `b`'s side that programs read.
@@ -1929,7 +2025,7 @@ impl PackPost {
.zip(e.late)
.any(|(p, late)| p.is_some() && late)
});
let mut water_drawn = self.water.is_none() && !late_entities;
let mut water_drawn = self.water.is_none() && self.weather.is_none() && !late_entities;
for pass in &mut passes {
if !terrain_drawn && pass.group != Group::Prepare {
terrain_drawn = true;
@@ -0,0 +1,264 @@
//! Rain and snow drawn by a shader pack's `gbuffers_weather` (spec 2.3): the game's weather
//! quads as entity vertices, their UV animation applied here rather than in Horizon's weather
//! shader, each kind textured from its own copy of its sprite so that the pack's `texture`
//! repeats it across the column as a standalone rain or snow texture would.
use crate::weather::{Time, Vertex as WeatherVertex};
use super::Vertex;
use super::pack_post::Weather;
/// What `gbuffers_weather` reads from a weather vertex: camera-relative position, the UV in
/// repeats of the sprite, colour (with vanilla's fade) and light. Weather has no normal; the
/// pack sees straight up.
pub fn inputs() -> horizon_shaders::GbuffersInputs {
let declarations =
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\
layout(location = 2) in uint hz_v_overlay;\nlayout(location = 3) in vec4 hz_v_color;\n\
layout(location = 4) in uvec4 hz_v_light;\nlayout(location = 5) in vec4 hz_v_normal;\n"
.to_owned();
let body = " hz_Vertex = vec4(hz_v_pos, 1.0);\n \
hz_MultiTexCoord0 = vec4(hz_v_uv, 0.0, 1.0);\n \
hz_MultiTexCoord1 = vec4(float(hz_v_light.y), float(hz_v_light.x), 0.0, 1.0);\n \
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
hz_Color = hz_v_color;\n \
hz_Normal = vec3(0.0, 1.0, 0.0);\n"
.to_owned();
let attributes = [
("vaPosition", "hz_Vertex.xyz"),
("vaUV0", "hz_v_uv"),
("vaUV2", "ivec2(hz_MultiTexCoord1.xy)"),
("vaColor", "hz_Color"),
("vaNormal", "hz_Normal"),
];
horizon_shaders::GbuffersInputs {
declarations,
body,
attributes: attributes
.iter()
.map(|&(n, v)| (n.to_owned(), v.to_owned()))
.collect(),
after: String::new(),
// Vanilla's weather drops texels below 0.1, as Horizon's own weather shader does.
alpha_test: Some(horizon_shaders::AlphaTest {
op: ">",
reference: 0.1,
}),
}
}
/// The UV phase of `v` at `time`: `weather_phase` of entity.wgsl, on the CPU.
pub fn phase(v: &WeatherVertex, time: Time) -> [f32; 2] {
let [ticks, fall_ticks, partial, _] = time.values;
let a = v.animation;
if v.snow == 0 {
let t = ticks + a[1] + partial;
return [0.0, (-t / 32.0 * a[0]) % 32.0];
}
let t = ticks + partial;
let du = t * 0.01 * a[2];
let dv = t * a[3] * 0.001;
let base = |lo: u32, hi: u32| f64::from_bits(u64::from(lo) | u64::from(hi) << 32);
let u = (base(v.bases[0], v.bases[1]) + f64::from(du)) as f32;
let v_base = (base(v.bases[2], v.bases[3]) + f64::from(dv)) as f32;
[u, -(fall_ticks + partial) / 512.0 + v_base]
}
/// One kind's sprite copied out of the shared atlas: the sprite's rectangle (bits) and its view.
type Sprite = Option<([u32; 4], wgpu::TextureView)>;
/// The pack's weather vertices and the rain and snow sprites, kept across frames.
pub struct PackWeather {
vertices: wgpu::Buffer,
capacity: usize,
scratch: Vec<Vertex>,
sprites: [Sprite; 2],
/// Bumped when a sprite is copied again.
generation: u64,
}
impl PackWeather {
pub fn new(device: &wgpu::Device) -> Self {
Self {
vertices: Self::buffer(device, 64),
capacity: 64,
scratch: Vec::new(),
sprites: [None, None],
generation: 0,
}
}
fn buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack weather"),
size: (capacity * std::mem::size_of::<Vertex>()) as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}
/// This frame's rain then snow (the game emits them in that order) as entity vertices, and
/// the sprites they read. `None` when there is none.
pub fn prepare(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
uploads: &mut super::upload::Uploads,
atlas: &wgpu::Texture,
weather: &[WeatherVertex],
time: Time,
indices: &wgpu::Buffer,
) -> Option<Weather> {
if weather.is_empty() {
return None;
}
let rain = weather.iter().take_while(|v| v.snow == 0).count() as u32 / 4;
let snow = weather.len() as u32 / 4 - rain;
for (kind, first) in [(0, weather.first()), (1, weather.get(rain as usize * 4))] {
let Some(first) = first.filter(|v| v.snow as usize == kind) else {
continue;
};
let key = first.rect.map(f32::to_bits);
if self.sprites[kind].as_ref().is_none_or(|s| s.0 != key) {
let view = copy_sprite(device, encoder, atlas, first.rect);
self.sprites[kind] = Some((key, view));
self.generation += 1;
}
}
self.scratch.clear();
self.scratch.extend(weather.iter().map(|v| {
let [du, dv] = phase(v, time);
Vertex {
pos: v.pos,
uv: [v.uv[0] + du, v.uv[1] + dv],
layer: 0,
color: v.color,
light: v.light,
normal: [0; 4],
}
}));
if self.scratch.len() > self.capacity {
self.capacity = self.scratch.len().next_power_of_two();
self.vertices = Self::buffer(device, self.capacity);
}
uploads.buffer(
encoder,
&self.vertices,
0,
bytemuck::cast_slice(&self.scratch),
);
let view = |k: usize| self.sprites[k].as_ref().map(|s| s.1.clone());
Some(Weather {
vertices: self.vertices.clone(),
indices: indices.clone(),
quads: [0..rain, rain..rain + snow],
sprites: [view(0), view(1)],
generation: self.generation,
})
}
}
/// A texture holding the atlas's texels under `rect` (normalised x, y, width, height), as
/// Horizon's weather shader reads them (`weather_texel`).
fn copy_sprite(
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
atlas: &wgpu::Texture,
rect: [f32; 4],
) -> wgpu::TextureView {
let size = [atlas.width() as f32, atlas.height() as f32];
let origin = [0, 1].map(|i| (rect[i] * size[i]).round() as u32);
let extent = [0, 1].map(|i| ((rect[i + 2] * size[i]).round() as u32).max(1));
let extent = [0, 1].map(|i| {
extent[i].min(
[atlas.width(), atlas.height()][i]
.saturating_sub(origin[i])
.max(1),
)
});
let size = wgpu::Extent3d {
width: extent[0],
height: extent[1],
depth_or_array_layers: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Shader pack weather sprite"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: atlas.format(),
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
texture: atlas,
mip_level: 0,
origin: wgpu::Origin3d {
x: origin[0],
y: origin[1],
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
size,
);
texture.create_view(&Default::default())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::weather::Parameters;
/// The CPU phase matches the game's own weather columns (`Parameters::column`), which
/// Horizon's weather shader is tested against.
#[test]
fn phase_matches_the_weather_columns() {
for i in 0..512i32 {
let x = i.wrapping_mul(45_238_971);
let z = i.wrapping_mul(-418_711).wrapping_add(i32::MIN);
let p = Parameters::new(x, z);
let bases = p.snow_base.map(f64::to_bits);
for ticks in [0, 511, 512, 131_071, 131_072, 1_000_003] {
let partial = [0.0, 0.5, 0.999][i as usize % 3];
for snow in [false, true] {
let column = p.column(snow, ticks, x, -64, 320, z, 0, partial);
let v = WeatherVertex {
pos: [0.0; 3],
uv: [0.0; 2],
rect: [0.0; 4],
animation: [
p.rain_speed,
p.rain_tick_offset,
p.snow_drift[0],
p.snow_drift[1],
],
bases: [
bases[0] as u32,
(bases[0] >> 32) as u32,
bases[1] as u32,
(bases[1] >> 32) as u32,
],
color: 0,
light: 0,
snow: u32::from(snow),
};
let [u, v] = phase(&v, Time::new(ticks, partial));
assert_eq!(
[u.to_bits(), v.to_bits()],
[column.u_offset.to_bits(), column.v_offset.to_bits()],
"x {x} z {z} ticks {ticks} snow {snow}"
);
}
}
}
}
}
+35 -1
View File
@@ -123,6 +123,14 @@ const BLOCK: [&str; 5] = [
/// `gbuffers_clouds`: no fallback, the game draws its clouds otherwise (OQ-3).
const CLOUDS: [&str; 1] = ["gbuffers_clouds"];
/// `gbuffers_weather` and its fallbacks (2.3).
const WEATHER: [&str; 4] = [
"gbuffers_weather",
"gbuffers_textured_lit",
"gbuffers_textured",
"gbuffers_basic",
];
/// `gbuffers_entities_translucent` and its fallbacks (2.3).
const ENTITIES_TRANSLUCENT: [&str; 5] = [
"gbuffers_entities_translucent",
@@ -196,6 +204,8 @@ pub struct Post {
pub particles: Option<PostProgram>,
/// What draws the game's clouds.
pub clouds: Option<PostProgram>,
/// What draws rain and snow, after deferred.
pub weather: Option<PostProgram>,
/// Translucent entities draw after deferred (`separateEntityDraws`, 3.2).
pub translucent_late: bool,
/// Particles draw after deferred (`particles.ordering`, `particles.before.deferred`, 3.2).
@@ -229,6 +239,8 @@ pub struct GameInputs {
pub entities: Option<GbuffersInputs>,
/// The clouds' mesh.
pub clouds: Option<GbuffersInputs>,
/// Rain and snow.
pub weather: Option<GbuffersInputs>,
}
/// Loads the post-processing programs of `folder` and, for the geometry `inputs` describes, the
@@ -254,6 +266,7 @@ pub fn load_post(
entities_translucent: None,
particles: None,
clouds: None,
weather: None,
translucent_late: false,
particles_late: false,
custom: Custom::parse(properties),
@@ -359,6 +372,15 @@ pub fn load_post(
p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_BLEND));
p
});
// Rain and snow draw after deferred and blend, as vanilla's do (OQ-23).
let weather = inputs
.weather
.as_ref()
.and_then(|i| gbuffers(&WEATHER, Group::Translucent, i));
let weather = weather.map(|mut p| {
p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_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).
@@ -379,6 +401,7 @@ pub fn load_post(
loader.post.entities_translucent = entities_translucent;
loader.post.particles = particles;
loader.post.clouds = clouds;
loader.post.weather = weather;
let flag = |key: &str| properties.get(key).map(|v| v.trim() == "true");
loader.post.translucent_late = flag("separateEntityDraws").unwrap_or(false);
// `after` when the pack has a deferred program, else `mixed`; ours are all translucent, so
@@ -667,7 +690,8 @@ mod tests {
sky: Some(inputs.clone()),
celestial: Some(inputs.clone()),
entities: Some(inputs.clone()),
clouds: Some(inputs),
clouds: Some(inputs.clone()),
weather: Some(inputs),
};
let post = load_post(&pack, "", &Properties::default(), &macros, &inputs);
let (terrain, water) = (post.terrain.unwrap(), post.water.unwrap());
@@ -717,6 +741,16 @@ mod tests {
assert!(post.particles_late && !post.translucent_late);
// gbuffers_clouds has no fallback (OQ-3): without it the game draws its clouds.
assert!(post.clouds.is_none());
// Weather falls back to gbuffers_textured, after deferred, blended.
let weather = post.weather.as_ref().unwrap();
assert_eq!(
(weather.name.as_str(), weather.group, weather.blend),
(
"gbuffers_textured",
Group::Translucent,
Some(TRANSLUCENT_BLEND)
)
);
let ordering = Properties::parse(
"particles.ordering = before\nseparateEntityDraws = true\n",
&macros,
+2 -1
View File
@@ -174,7 +174,8 @@ fn real_packs_read() {
sky: Some(terrain.clone()),
celestial: Some(terrain.clone()),
entities: Some(terrain.clone()),
clouds: Some(terrain),
clouds: Some(terrain.clone()),
weather: Some(terrain),
};
let post = load_post(&pack, &folder, &shaders, &Macros::standard(), &inputs);
println!(