Shader packs, clean room 21: per-draw uniforms (renderStage)

A gbuffers program's renderStage, entityId, blockEntityId and entityColor
(spec 5.3, updated per draw) move to a block of their own at set 2 that
the game picks per draw with a dynamic offset: one slot per render stage.
Terrain draws as TERRAIN_SOLID, translucent terrain as
TERRAIN_TRANSLUCENT. The terrain test pack paints any other stage red.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
5.3, 5.4; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-25 03:29:21 +01:00
parent 5e348aa479
commit b9b47f12da
7 changed files with 150 additions and 7 deletions
+1
View File
@@ -69,6 +69,7 @@ pub mod lightning;
mod lod;
mod occlusion;
mod pack_atlas;
mod pack_draw;
mod pack_post;
mod pack_timing;
pub mod pack_uniforms;
@@ -0,0 +1,67 @@
//! The uniforms a shader pack's gbuffers programs read per draw (`HzDraw` at set 2, the
//! translator's `DRAW_UNIFORMS`): one slot per render stage of a uniform buffer, picked with a
//! dynamic offset at each draw.
use horizon_shaders::{RENDER_STAGES, render_stage};
/// `HzDraw`'s size: `renderStage`, `entityId`, `blockEntityId`, a pad, `entityColor`.
const SIZE: u32 = 32;
pub(super) struct DrawUniforms {
pub layout: wgpu::BindGroupLayout,
group: wgpu::BindGroup,
stride: u32,
}
impl DrawUniforms {
pub fn new(device: &wgpu::Device) -> Self {
let stride = SIZE.max(device.limits().min_uniform_buffer_offset_alignment);
let mut contents = vec![0u8; stride as usize * RENDER_STAGES.len()];
for (i, slot) in contents.chunks_mut(stride as usize).enumerate() {
slot[..4].copy_from_slice(&(i as i32).to_le_bytes());
}
let buffer = wgpu::util::DeviceExt::create_buffer_init(
device,
&wgpu::util::BufferInitDescriptor {
label: Some("Shader pack draws"),
contents: &contents,
usage: wgpu::BufferUsages::UNIFORM,
},
);
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Shader pack draws"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: true,
min_binding_size: wgpu::BufferSize::new(u64::from(SIZE)),
},
count: None,
}],
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Shader pack draws"),
layout: &layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &buffer,
offset: 0,
size: wgpu::BufferSize::new(u64::from(SIZE)),
}),
}],
});
Self {
layout,
group,
stride,
}
}
/// Draws that follow read `renderStage` = `MC_RENDER_STAGE_<stage>`, other values zero.
pub fn bind(&self, pass: &mut wgpu::RenderPass<'_>, stage: &str) {
pass.set_bind_group(2, &self.group, &[self.stride * render_stage(stage)]);
}
}
+24 -1
View File
@@ -15,6 +15,7 @@ use std::collections::HashMap;
use horizon_shaders::{Format, Group, Kind, Post, Val};
use super::pack_draw::DrawUniforms;
use super::pack_uniforms::{self, FrameUniforms, PackInputs};
const BUFFERS: usize = horizon_shaders::BUFFERS;
@@ -139,6 +140,8 @@ struct Pass {
written: u16,
/// Buffers whose mip chain is regenerated right before it (6.1.7).
mipmaps: u16,
/// Reads the per-draw block (`DrawUniforms`).
draw: bool,
groups: HashMap<u16, wgpu::BindGroup>,
}
@@ -186,6 +189,8 @@ pub struct PackPost {
mips_valid: u16,
/// The downsampling pipeline of each format with mipmaps.
down: HashMap<wgpu::TextureFormat, (wgpu::RenderPipeline, wgpu::BindGroupLayout)>,
/// The per-draw uniforms of gbuffers programs.
draws: DrawUniforms,
/// `HORIZON_SHADER_PACK_TIMING`: GPU time of each pass, in the log.
timing: Option<super::pack_timing::PassTiming>,
/// `shaders.properties`' custom uniforms, after the frame's in `uniforms.values`.
@@ -488,6 +493,7 @@ fn build_pass(
notes: &mut Vec<String>,
geometry: Option<&Geometry<'_>>,
custom: &[String],
draws: &wgpu::BindGroupLayout,
) -> Option<Pass> {
let features = device.features();
// The frame's uniforms, then the pack's custom ones.
@@ -499,6 +505,7 @@ fn build_pass(
};
let mask = |flips: &[(u32, bool)]| flips.iter().filter(|f| f.1).fold(0u16, |m, f| m | 1 << f.0);
let interface = &p.program.interface;
let draw = interface.draw;
let mut entries = vec![entry(
0,
wgpu::BindingType::Buffer {
@@ -632,7 +639,11 @@ fn build_pass(
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some(&p.name),
bind_group_layouts: &[Some(&layout), geometry.and_then(|g| g.table)],
bind_group_layouts: &[
Some(&layout),
geometry.and_then(|g| g.table),
draw.then_some(draws),
],
..Default::default()
});
let module = |mut m: naga::Module| {
@@ -712,6 +723,7 @@ fn build_pass(
reads,
written,
mipmaps: p.mipmaps,
draw,
groups: HashMap::new(),
})
}
@@ -748,6 +760,7 @@ impl PackPost {
let mask =
|flips: &[(u32, bool)]| flips.iter().filter(|f| f.1).fold(0u16, |m, f| m | 1 << f.0);
let mut used = 1u16;
let draws = DrawUniforms::new(device);
let mut build = |p: horizon_shaders::PostProgram, geometry: Option<&Geometry<'_>>| {
let pass = build_pass(
device,
@@ -757,6 +770,7 @@ impl PackPost {
&mut notes,
geometry,
&custom_names,
&draws.layout,
)?;
used |= pass.reads | pass.written | pass.flip;
Some(pass)
@@ -910,6 +924,7 @@ impl PackPost {
mipped,
mips_valid: 0,
down,
draws,
timing: super::pack_timing::PassTiming::new(device, queue),
custom,
atlas: world.atlas.as_ref().map(|a| a.0.clone()),
@@ -1133,6 +1148,14 @@ impl PackPost {
});
rp.set_pipeline(&pass.pipeline);
rp.set_bind_group(0, &group, &[]);
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;
+3 -3
View File
@@ -30,7 +30,7 @@ pub use config::{BUFFERS, Buffer, Config, Format, Kind, buffer_index, draw_buffe
pub use custom::{Custom, Val};
pub use discover::{Found, discover};
pub use lang::Lang;
pub use macros::{MC_VERSION, Macros, RENDER_STAGES};
pub use macros::{MC_VERSION, Macros, RENDER_STAGES, render_stage};
pub use options::switches_on;
pub use pack::{Pack, PackError};
pub use post::{
@@ -39,6 +39,6 @@ pub use post::{
pub use preprocess::{Diagnostic, Origin, Preprocessed, preprocess};
pub use properties::{Entry, Note, Properties};
pub use translate::{
Error, GbuffersInputs, Interface, Program, Sampler, Target, Uniform, translate_composite,
translate_gbuffers,
DRAW_UNIFORMS, Error, GbuffersInputs, Interface, Program, Sampler, Target, Uniform,
translate_composite, translate_gbuffers,
};
+8
View File
@@ -60,6 +60,14 @@ pub const RENDER_STAGES: [&str; 24] = [
"HAND_TRANSLUCENT",
];
/// The value of `MC_RENDER_STAGE_<name>` (OQ-7: its index in `RENDER_STAGES`).
pub fn render_stage(name: &str) -> u32 {
RENDER_STAGES
.iter()
.position(|s| *s == name)
.unwrap_or_else(|| panic!("no render stage {name}")) as u32
}
impl Macros {
/// The standard macros that need no renderer (spec 1.5.1): `MC_VERSION`, this system's
/// `MC_OS_*`, the GL and GLSL versions Horizon's translation accepts, the render stages and
+44 -3
View File
@@ -45,8 +45,19 @@ pub struct Interface {
pub samplers: Vec<Sampler>,
/// The fragment stage's output locations.
pub outputs: Vec<u32>,
/// A gbuffers program reads `DRAW_UNIFORMS`: the block at set 2, binding 0, set per draw.
pub draw: bool,
}
/// The uniforms a gbuffers program reads per draw (5.3's "D"), in a block of their own
/// (`HzDraw`, std140: three ints, a pad, a vec4; 32 bytes) the game sets for each draw.
pub const DRAW_UNIFORMS: [(&str, &str); 4] = [
("renderStage", "int"),
("entityId", "int"),
("blockEntityId", "int"),
("entityColor", "vec4"),
];
#[derive(Clone, Debug, PartialEq)]
pub struct Uniform {
pub name: String,
@@ -170,6 +181,17 @@ fn translate(
samplers.insert(name.clone(), ty.clone());
}
}
// Per-draw values move to their own block; another type than the documented one keeps
// the frame's block (and reads zero).
let mut draw = false;
if gbuffers.is_some() {
for (name, ty) in DRAW_UNIFORMS {
if uniforms.get(name).is_some_and(|t| t == ty) {
uniforms.remove(name);
draw = true;
}
}
}
let samplers: Vec<Sampler> = samplers
.into_iter()
.enumerate()
@@ -203,6 +225,12 @@ fn translate(
.unwrap();
}
h.push_str(" };\n");
if draw {
h.push_str(
"layout(set = 2, binding = 0) uniform HzDraw { int renderStage; int entityId; \
int blockEntityId; int hz_draw_pad; vec4 entityColor; };\n",
);
}
for s in &samplers {
let (texture, sampler) = split_sampler(&s.ty);
writeln!(
@@ -327,6 +355,7 @@ fn translate(
uniforms,
samplers,
outputs,
draw,
},
})
}
@@ -394,7 +423,11 @@ fn compile(stage: &Stage, text: &str, header_lines: usize) -> Result<naga::Modul
/// The uniform block's size and member offsets, from naga's layout.
fn block_layout(module: &naga::Module) -> (u32, Vec<(String, u32)>) {
for (_, var) in module.global_variables.iter() {
if var.space != naga::AddressSpace::Uniform {
let frame = var
.binding
.as_ref()
.is_some_and(|b| b.group == 0 && b.binding == 0);
if var.space != naga::AddressSpace::Uniform || !frame {
continue;
}
if let naga::TypeInner::Struct { members, span } = &module.types[var.ty].inner {
@@ -546,9 +579,9 @@ mod tests {
light = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy;\n color = gl_Color;\n \
normal = normalize(gl_NormalMatrix * gl_Normal);\n id = mc_Entity.x + mc_midTexCoord.x;\n}\n";
let fsh = "#version 120\nuniform sampler2D texture;\nuniform sampler2D lightmap;\nuniform mat4 gbufferModelView;\n\
varying vec2 uv;\nvarying vec2 light;\nvarying vec4 color;\nvarying vec3 normal;\nvarying float id;\n\
uniform int renderStage;\nvarying vec2 uv;\nvarying vec2 light;\nvarying vec4 color;\nvarying vec3 normal;\nvarying float id;\n\
void main() {\n vec4 c = texture2D(texture, uv) * texture2D(lightmap, light) * color;\n \
/* DRAWBUFFERS:02 */\n gl_FragData[0] = c * gl_FragCoord.z;\n \
/* DRAWBUFFERS:02 */\n gl_FragData[0] = c * gl_FragCoord.z * float(renderStage);\n \
gl_FragData[1] = vec4(normal * 0.5 + 0.5, id);\n}\n";
let files: Vec<(String, &str)> =
[("gbuffers_terrain.vsh", vsh), ("gbuffers_terrain.fsh", fsh)]
@@ -586,6 +619,14 @@ mod tests {
assert!(names.contains(&name), "{name} missing from {names:?}");
}
assert_eq!(p.interface.outputs, vec![0, 1]);
// renderStage is set per draw, in its own block.
assert!(p.interface.draw && !names.contains(&"renderStage"));
let per_draw = p.fragment.global_variables.iter().any(|(_, v)| {
v.binding
.as_ref()
.is_some_and(|b| b.group == 2 && b.binding == 0)
});
assert!(per_draw);
let inputs: Vec<&str> = p.vertex.entry_points[0]
.function
.arguments
@@ -3,6 +3,7 @@
uniform sampler2D texture;
uniform sampler2D lightmap;
uniform ivec2 atlasSize;
uniform int renderStage;
varying vec2 texcoord;
varying vec2 lmcoord;
@@ -17,6 +18,8 @@ void main() {
color.rgb = mix(color.rgb * vec3(0.6, 0.7, 1.2), color.rgb, lmcoord.y);
// A dot at the face's centre, one texel wide.
if (length((texcoord - mid) * vec2(atlasSize)) < 1.0) color.rgb = vec3(1.0, 0.0, 1.0);
// Any other stage than solid terrain (translucent terrain falls back here): red.
if (renderStage != MC_RENDER_STAGE_TERRAIN_SOLID) color.rgb = vec3(1.0, 0.0, 0.0);
/* DRAWBUFFERS:0 */
gl_FragData[0] = color;
}