Merge pull request #1655 from ludovic111/feat/shader-packs-uniforms

Shader packs, clean room 9: frame uniforms, and gl_FragCoord in buffer passes
This commit is contained in:
Ludovic Marie
2026-10-25 14:20:32 +01:00
committed by GitHub
6 changed files with 409 additions and 3 deletions
+8
View File
@@ -141,6 +141,7 @@ mod sculk;
mod sculk_fixture;
mod server_packs;
mod server_travel;
mod shader_packs;
mod shield;
mod sign_edit;
mod sniffers;
@@ -10085,6 +10086,11 @@ impl Game<'_> {
} else {
self.gather_dynamic_lights(camera, alpha);
}
let pack_inputs = if title {
Default::default()
} else {
self.shader_pack_inputs(camera, alpha as f32)
};
let frame = Frame {
weather: &weather,
weather_time: horizon_client::weather::Time::new(self.world.game_time, alpha as f32),
@@ -10168,6 +10174,7 @@ impl Game<'_> {
hand: &hand,
hand_fov_degrees: self.hud_fov_degrees(camera_alpha as f32, camera.to_array()),
screen: &screen,
pack: pack_inputs,
border,
game_time: self.world.game_time as f32,
shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0,
@@ -12716,6 +12723,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
hand: &[],
hand_fov_degrees: 70.0,
screen: &[],
pack: Default::default(),
border: None,
game_time: 0.0,
shader_game_time: 0.0,
+1 -1
View File
@@ -74,7 +74,7 @@ impl Game<'_> {
})
}
/// The fluid at the camera, as `Camera.getFluidInCamera` reports it.
fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid {
pub(super) fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid {
match fog_type(&self.world, self.res.facts(), camera, self.forward()) {
FogType::Water => CameraFluid::Water,
FogType::Lava => CameraFluid::Lava,
@@ -0,0 +1,34 @@
//! Shader packs, for development until the Shader Packs page exists: `HORIZON_SHADER_PACK=<name>`
//! (the runtime that uses it comes next). What the pack's uniforms need from the game.
use horizon_client::camera::CameraFluid;
use horizon_client::gfx::pack_uniforms::PackInputs;
use super::Game;
impl Game<'_> {
/// This frame's inputs to the pack's uniforms.
pub(super) fn shader_pack_inputs(&mut self, camera: glam::DVec3, partial: f32) -> PackInputs {
if std::env::var_os("HORIZON_SHADER_PACK").is_none() {
return PackInputs::default();
}
let lerp = |(old, new): (f32, f32)| old + (new - old) * partial;
let at = camera.floor().as_ivec3();
let light = self.world.light(at.x, at.y, at.z);
PackInputs {
day_time: self.world.day_time,
rain: lerp(self.world.weather.rain_level),
thunder: lerp(self.world.weather.thunder_level),
eye_in: match self.camera_fluid(camera.to_array()) {
CameraFluid::None => 0,
CameraFluid::Water => 1,
CameraFluid::Lava => 2,
CameraFluid::PowderSnow => 3,
},
blindness: f32::from(u8::from(self.potions.effects.get("blindness").is_some())),
eye_light: [i32::from(light & 15), i32::from(light >> 4)],
hide_gui: self.ui.hide_gui,
brightness: self.settings.gamma,
}
}
}
+3
View File
@@ -68,6 +68,7 @@ mod flat;
pub mod lightning;
mod lod;
mod occlusion;
pub mod pack_uniforms;
mod page_runs;
pub mod panorama;
mod resident;
@@ -249,6 +250,8 @@ pub struct Frame<'a> {
pub hand_fov_degrees: f32,
/// Full-screen camera effects drawn over the world and hand, under the HUD.
pub screen: &'a [crate::screen_effects::ScreenQuad],
/// What a shader pack's uniforms need from the game.
pub pack: pack_uniforms::PackInputs,
/// The world border wall, when near enough to be drawn.
pub border: Option<BorderDraw>,
pub game_time: f32,
@@ -0,0 +1,329 @@
//! The uniforms a shader pack's post-processing programs read once per frame (spec 5.2, class
//! F), from the renderer's `Frame` and the few values only the game knows (`PackInputs`).
//! Matrices follow GL's conventions (5.5): `gbufferProjection` maps view depth to clip z in
//! [-w, w], and the depth buffers packs read hold GL window depth.
use glam::{Mat4, Vec3, Vec4};
use super::Frame;
/// What the game passes for the pack's uniforms, beyond what `Frame` carries.
#[derive(Clone, Copy, Debug, Default)]
pub struct PackInputs {
/// `Level.getDayTime`.
pub day_time: i64,
/// The interpolated rain and thunder levels, 0..1.
pub rain: f32,
pub thunder: f32,
/// The fluid at the camera: 0 none, 1 water, 2 lava, 3 powder snow.
pub eye_in: i32,
pub blindness: f32,
/// Block and sky light at the camera, 0..15.
pub eye_light: [i32; 2],
pub hide_gui: bool,
/// The brightness option, 0..1.
pub brightness: f32,
}
/// One uniform's value: up to 16 floats or 3 integers.
#[derive(Clone, Copy, Debug)]
pub enum Value {
F([f32; 16]),
I([i32; 3]),
}
impl Value {
fn f(v: &[f32]) -> Self {
let mut a = [0.0; 16];
a[..v.len()].copy_from_slice(v);
Value::F(a)
}
fn i(v: &[i32]) -> Self {
let mut a = [0; 3];
a[..v.len()].copy_from_slice(v);
Value::I(a)
}
/// Writes the value as the type the pack declared, at `offset` of a std140 block.
pub fn write(&self, ty: &str, out: &mut [u8], offset: usize) {
let ints = matches!(ty, "int" | "bool" | "uint") || ty.starts_with(['i', 'u']);
let (floats, integers): ([f32; 16], [i32; 16]) = match *self {
Value::F(f) => (f, f.map(|v| v as i32)),
Value::I(i) => {
let mut f = [0.0; 16];
let mut v = [0; 16];
for k in 0..3 {
f[k] = i[k] as f32;
v[k] = i[k];
}
(f, v)
}
};
let count = match ty {
"mat4" => 16,
"mat3" => {
// std140: three columns, each padded to a vec4, from the mat4's upper left.
for c in 0..3 {
let column: [f32; 3] = std::array::from_fn(|r| floats[c * 4 + r]);
put(out, offset + c * 16, bytemuck::cast_slice(&column));
}
return;
}
t => match t.as_bytes().last() {
Some(n @ b'2'..=b'4') if t.contains("vec") => (n - b'0') as usize,
_ => 1,
},
};
if ints {
put(out, offset, bytemuck::cast_slice(&integers[..count]));
} else {
put(out, offset, bytemuck::cast_slice(&floats[..count]));
}
}
}
fn put(out: &mut [u8], offset: usize, bytes: &[u8]) {
if let Some(dst) = out.get_mut(offset..offset + bytes.len()) {
dst.copy_from_slice(bytes);
}
}
/// The uniforms provided, in the order of [`FrameUniforms::values`].
pub const NAMES: &[&str] = &[
"cameraPosition",
"previousCameraPosition",
"eyeAltitude",
"upPosition",
"sunPosition",
"moonPosition",
"shadowLightPosition",
"sunAngle",
"shadowAngle",
"worldTime",
"worldDay",
"moonPhase",
"frameCounter",
"frameTime",
"frameTimeCounter",
"viewWidth",
"viewHeight",
"aspectRatio",
"near",
"far",
"rainStrength",
"wetness",
"thunderStrength",
"fogColor",
"skyColor",
"fogMode",
"fogStart",
"fogEnd",
"fogDensity",
"fogShape",
"isEyeInWater",
"blindness",
"nightVision",
"darknessFactor",
"darknessLightFactor",
"screenBrightness",
"hideGUI",
"eyeBrightness",
"eyeBrightnessSmooth",
"heldItemId",
"heldItemId2",
"heldBlockLightValue",
"heldBlockLightValue2",
"renderStage",
"gbufferModelView",
"gbufferModelViewInverse",
"gbufferProjection",
"gbufferProjectionInverse",
"gbufferPreviousModelView",
"gbufferPreviousProjection",
];
/// Values carried from frame to frame.
pub struct FrameUniforms {
pub values: Vec<Value>,
start: std::time::Instant,
last: Option<std::time::Instant>,
frame: u32,
previous: Option<(Vec3, Mat4, Mat4)>,
wetness: f32,
eye_smooth: [f32; 2],
}
impl Default for FrameUniforms {
fn default() -> Self {
Self {
values: Vec::new(),
start: std::time::Instant::now(),
last: None,
frame: 0,
previous: None,
wetness: 0.0,
eye_smooth: [0.0; 2],
}
}
}
/// `(0, 100, 0)` on the frame the sky draws a body on: Y -90°, then X by its angle in degrees.
fn body(angle: f32) -> Vec3 {
(Mat4::from_rotation_y((-90.0f32).to_radians()) * Mat4::from_rotation_x(angle.to_radians()))
.transform_vector3(Vec3::new(0.0, 100.0, 0.0))
}
/// `value` moved toward `target` with a half-life of `half_life` seconds over `dt` (5.6).
fn smooth(value: f32, target: f32, half_life: f32, dt: f32) -> f32 {
target + (value - target) * 0.5f32.powf(dt / half_life)
}
impl FrameUniforms {
/// This frame's values for a render size of `size` pixels.
pub fn update(&mut self, frame: &Frame, inputs: &PackInputs, size: [u32; 2]) {
let now = std::time::Instant::now();
let dt = self.last.map_or(0.0, |l| (now - l).as_secs_f32());
self.last = Some(now);
let aspect = size[0] as f32 / size[1].max(1) as f32;
let view = crate::camera::view_matrix(frame.yaw, frame.pitch);
let projection = Mat4::perspective_rh_gl(
frame.fov_degrees.to_radians(),
aspect,
0.05,
frame.depth_far,
) * frame.bob;
let camera = frame.camera.as_vec3();
let (previous_camera, previous_view, previous_projection) =
self.previous
.unwrap_or((Vec3::ZERO, Mat4::ZERO, Mat4::ZERO));
self.previous = Some((camera, view, projection));
let to_view = |v: Vec3| view.transform_vector3(v);
let sun_angle = (frame.sky.sun_angle / 360.0 + 0.25).rem_euclid(1.0);
let day = sun_angle < 0.5;
let sun = to_view(body(frame.sky.sun_angle));
let moon = to_view(body(frame.sky.moon_angle));
// Half-lives are given in ticks (7.2); smoothing runs per frame in seconds (OQ-26).
let half_life = if inputs.rain > self.wetness {
600.0
} else {
200.0
};
self.wetness = smooth(self.wetness, inputs.rain, half_life / 20.0, dt);
let eye = inputs.eye_light.map(|l| (l * 16) as f32);
for (smoothed, target) in self.eye_smooth.iter_mut().zip(eye) {
*smoothed = smooth(*smoothed, target, 10.0 / 20.0, dt);
}
let (fog_color, fog_start, fog_end) = match &frame.fog {
Some(f) => (
[f.color[0], f.color[1], f.color[2]],
f.environmental_start.min(f.render_distance_start),
f.environmental_end.min(f.render_distance_end),
),
None => (frame.sky.fog_color, frame.distance * 0.9, frame.distance),
};
let day_time = inputs.day_time.rem_euclid(24000) as i32;
let world_day = inputs.day_time.div_euclid(24000);
let seconds = (now - self.start).as_secs_f32() % 3600.0;
let value = |name: &str| -> Value {
let v3 = |v: Vec3| Value::f(&v.to_array());
let m4 = |m: Mat4| Value::f(&m.to_cols_array());
match name {
"cameraPosition" => v3(camera),
"previousCameraPosition" => v3(previous_camera),
"eyeAltitude" => Value::f(&[frame.camera.y as f32]),
"upPosition" => v3(to_view(Vec3::new(0.0, 100.0, 0.0))),
"sunPosition" => v3(sun),
"moonPosition" => v3(moon),
"shadowLightPosition" => v3(if day { sun } else { moon }),
"sunAngle" => Value::f(&[sun_angle]),
"shadowAngle" => Value::f(&[if day { sun_angle } else { sun_angle - 0.5 }]),
"worldTime" => Value::i(&[day_time]),
"worldDay" => Value::i(&[world_day as i32]),
"moonPhase" => Value::i(&[world_day.rem_euclid(8) as i32]),
"frameCounter" => Value::i(&[self.frame as i32]),
"frameTime" => Value::f(&[dt]),
"frameTimeCounter" => Value::f(&[seconds]),
"viewWidth" => Value::f(&[size[0] as f32]),
"viewHeight" => Value::f(&[size[1] as f32]),
"aspectRatio" => Value::f(&[aspect]),
"near" => Value::f(&[0.05]),
"far" => Value::f(&[frame.distance]),
"rainStrength" => Value::f(&[inputs.rain]),
"wetness" => Value::f(&[self.wetness]),
"thunderStrength" => Value::f(&[inputs.thunder]),
"fogColor" => Value::f(&fog_color),
"skyColor" => Value::f(&frame.sky.sky_color),
// GL_LINEAR: vanilla's fog is linear.
"fogMode" => Value::i(&[9729]),
"fogStart" => Value::f(&[fog_start]),
"fogEnd" => Value::f(&[fog_end]),
"fogDensity" => Value::f(&[1.0]),
"fogShape" => Value::i(&[0]),
"isEyeInWater" => Value::i(&[inputs.eye_in]),
"blindness" => Value::f(&[inputs.blindness]),
"nightVision" => Value::f(&[frame.night_vision]),
"darknessFactor" => Value::f(&[frame.darkness.0]),
"darknessLightFactor" => Value::f(&[frame.darkness.1]),
"screenBrightness" => Value::f(&[inputs.brightness]),
"hideGUI" => Value::i(&[inputs.hide_gui as i32]),
"eyeBrightness" => Value::i(&eye.map(|v| v as i32)),
"eyeBrightnessSmooth" => Value::i(&self.eye_smooth.map(|v| v.round() as i32)),
"gbufferModelView" => m4(view),
"gbufferModelViewInverse" => m4(view.inverse()),
"gbufferProjection" => m4(projection),
"gbufferProjectionInverse" => m4(projection.inverse()),
"gbufferPreviousModelView" => m4(previous_view),
"gbufferPreviousProjection" => m4(previous_projection),
// Held items wait for `item.properties` (5.3: 0 without the file); renderStage
// is NONE outside gbuffers draws.
_ => Value::i(&[0]),
}
};
self.values = NAMES.iter().map(|n| value(n)).collect();
self.frame = (self.frame + 1) % 720_720;
}
/// `hz_fog_color` and `hz_fog` of the translator's block (the compatibility `gl_Fog`).
pub fn fog(&self) -> [Vec4; 2] {
let get = |name| match index(name).and_then(|i| self.values.get(i)) {
Some(Value::F(f)) => *f,
_ => [0.0; 16],
};
let (color, start, end) = (get("fogColor"), get("fogStart")[0], get("fogEnd")[0]);
[
Vec4::new(color[0], color[1], color[2], 1.0),
Vec4::new(1.0, start, end, 1.0 / (end - start).max(1e-3)),
]
}
}
/// The position of `name` in [`NAMES`].
pub fn index(name: &str) -> Option<usize> {
NAMES.iter().position(|n| *n == name)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn values_follow_the_declared_type() {
let mut out = vec![0u8; 64];
Value::i(&[7]).write("float", &mut out, 0);
assert_eq!(f32::from_ne_bytes(out[0..4].try_into().unwrap()), 7.0);
Value::f(&[1.5, 2.5]).write("ivec2", &mut out, 4);
assert_eq!(i32::from_ne_bytes(out[8..12].try_into().unwrap()), 2);
Value::i(&[1]).write("bool", &mut out, 16);
assert_eq!(i32::from_ne_bytes(out[16..20].try_into().unwrap()), 1);
Value::f(&[1.0; 16]).write("mat4", &mut out, 60);
assert_eq!(out[60..64], [0; 4], "a value past the block is dropped");
}
#[test]
fn noon_is_straight_up_and_the_sun_sets_in_the_west() {
assert!(body(0.0).abs_diff_eq(Vec3::new(0.0, 100.0, 0.0), 1e-3));
assert!(body(90.0).abs_diff_eq(Vec3::new(-100.0, 0.0, 0.0), 1e-3));
}
}
+34 -2
View File
@@ -193,8 +193,11 @@ pub fn translate_composite(
.unwrap();
let mut fragment_main = String::from("\nvoid main() {\n");
fragment_main.push_str(fog);
if target == Target::Window && f.frag_coord {
fragment_main.push_str(" hz_FragCoord = vec4(gl_FragCoord.x, hz_target.y - gl_FragCoord.y, gl_FragCoord.zw);\n");
if f.frag_coord {
fragment_main.push_str(match target {
Target::Window => " hz_FragCoord = vec4(gl_FragCoord.x, hz_target.y - gl_FragCoord.y, gl_FragCoord.zw);\n",
Target::Buffers => " hz_FragCoord = gl_FragCoord;\n",
});
}
for name in &f.inits {
writeln!(fragment_main, " {name} = hz_init_{name}();").unwrap();
@@ -412,6 +415,35 @@ mod tests {
);
}
#[test]
fn frag_coord_is_set_for_every_target() {
let fsh = "#version 120\nvoid main() { gl_FragColor = vec4(gl_FragCoord.x); }\n";
for target in [Target::Buffers, Target::Window] {
let p = program(
&[("composite.vsh", VSH_120), ("composite.fsh", fsh)],
target,
)
.unwrap();
let m = &p.fragment;
let (handle, _) = m
.global_variables
.iter()
.find(|(_, g)| g.name.as_deref() == Some("hz_FragCoord"))
.unwrap();
// naga calls our `main` from its entry point: look in every function.
let functions = m.functions.iter().map(|(_, f)| f);
let stores = functions.chain([&m.entry_points[0].function]).any(|f| {
f.body.iter().any(|s| match s {
naga::Statement::Store { pointer, .. } => {
matches!(f.expressions[*pointer], naga::Expression::GlobalVariable(h) if h == handle)
}
_ => false,
})
});
assert!(stores, "{target:?}: main does not set hz_FragCoord");
}
}
#[test]
fn errors_point_at_the_pack_file_and_line() {
let fsh =