Shader packs, clean room 25: terrain normals and tangents

Flat terrain's vertex stage reads its quad's first three corners from the
arena page (bound per page at set 3, beside mc_Entity's table) and gives
gl_Normal / vaNormal the face normal and at_tangent the tangent along
the texture's u, with w the handedness of bitangent = cross(tangent,
normal) (spec 5.1). The pack's terrain and water pipelines cull back
faces as the game's own terrain does (clockwise front faces, rows being
flipped to GL's): water's surface no longer shows its downward copy.

Flat draws call a hook per arena page (Flat::draw_with); the arena lists
its page buffers.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
5.1; 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 05:16:38 +01:00
parent 441f749c25
commit 732efe69bb
5 changed files with 162 additions and 63 deletions
+37 -24
View File
@@ -2799,6 +2799,7 @@ impl Renderer {
depth_write: true,
atlas: None,
ids: None,
cull: true,
}),
block_ids,
celestial: self
@@ -4070,31 +4071,42 @@ impl Renderer {
{
let size = self.world_post.size().unwrap_or([1, 1]);
let flat = self.flat.as_ref().filter(|_| flat_frame);
let mut terrain = |rp: &mut wgpu::RenderPass<'_>, translucent: bool| {
if !pack_draws_terrain {
return;
}
match flat {
Some(flat) => {
let calls = if translucent {
&flat.calls[flat.solid_calls..]
} else {
&flat.calls[..flat.solid_calls]
};
flat.draw(rp, calls, |p| self.arena.buffer(p));
}
None => {
rp.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
rp.set_vertex_buffer(1, self.instances.slice(..));
let (first, count) = if translucent {
(solid_draws, translucent_draws)
} else {
(0, solid_draws)
};
self.draw_sections(rp, &self.indirect, 0, first, count);
}
}
let pages: Vec<(u32, wgpu::Buffer)> = match flat {
Some(_) if pack_draws_terrain => self
.arena
.page_buffers()
.map(|(p, b)| (p, b.clone()))
.collect(),
_ => Vec::new(),
};
let mut terrain =
|rp: &mut wgpu::RenderPass<'_>,
translucent: bool,
page: &dyn Fn(&mut wgpu::RenderPass<'_>, u32)| {
if !pack_draws_terrain {
return;
}
match flat {
Some(flat) => {
let calls = if translucent {
&flat.calls[flat.solid_calls..]
} else {
&flat.calls[..flat.solid_calls]
};
flat.draw_with(rp, calls, |p| self.arena.buffer(p), page);
}
None => {
rp.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
rp.set_vertex_buffer(1, self.instances.slice(..));
let (first, count) = if translucent {
(solid_draws, translucent_draws)
} else {
(0, solid_draws)
};
self.draw_sections(rp, &self.indirect, 0, first, count);
}
}
};
post.run(
&self.device,
&self.queue,
@@ -4106,6 +4118,7 @@ impl Renderer {
&frame.pack,
size,
[self.config.width, self.config.height],
&pages,
&mut terrain,
);
self.pack_post = Some((dimension, Some(post)));
+5
View File
@@ -155,6 +155,11 @@ impl Arena {
pub fn has_page(&self, page: u32) -> bool {
self.pages.get(page as usize).is_some_and(Option::is_some)
}
/// Each live page's buffer, by page.
pub fn page_buffers(&self) -> impl Iterator<Item = (u32, &wgpu::Buffer)> {
let pages = self.pages.iter().enumerate();
pages.filter_map(|(i, p)| Some((i as u32, &p.as_ref()?.buffer)))
}
pub fn buffer(&self, page: u32) -> &wgpu::Buffer {
&self.pages[page as usize]
.as_ref()
+12
View File
@@ -649,10 +649,22 @@ impl Flat {
pass: &mut wgpu::RenderPass<'_>,
calls: &[Call],
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
) {
self.draw_with(pass, calls, vertices, |_, _| {});
}
/// `draw`, calling `page` before each run of calls from one arena page (a shader pack binds
/// that page's vertices for reading).
pub fn draw_with<'a>(
&self,
pass: &mut wgpu::RenderPass<'_>,
calls: &[Call],
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
page: impl Fn(&mut wgpu::RenderPass<'_>, u32),
) {
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
for call in calls {
self.bind_page(pass, call.page, &vertices);
page(pass, call.page);
pass.draw_indexed(call.first..call.first + call.count, 0, 0..1);
}
}
+36 -5
View File
@@ -113,6 +113,30 @@ impl PackAtlas {
}
}
/// GLSL: the face normal and tangent of a flat-drawn vertex, from its quad's first three corners
/// (quads are four consecutive vertices of the page; position words 0-2, UV word 3).
const FACE: &str = " uint hz_q = (uint(gl_VertexIndex) & ~3u) * 6u;\n \
vec3 hz_p0 = uintBitsToFloat(uvec3(hz_vertices[hz_q], hz_vertices[hz_q + 1u], hz_vertices[hz_q + 2u]));\n \
vec3 hz_p1 = uintBitsToFloat(uvec3(hz_vertices[hz_q + 6u], hz_vertices[hz_q + 7u], hz_vertices[hz_q + 8u]));\n \
vec3 hz_p2 = uintBitsToFloat(uvec3(hz_vertices[hz_q + 12u], hz_vertices[hz_q + 13u], hz_vertices[hz_q + 14u]));\n \
uvec3 hz_w = uvec3(hz_vertices[hz_q + 3u], hz_vertices[hz_q + 9u], hz_vertices[hz_q + 15u]);\n \
vec2 hz_t0 = vec2(hz_w.x & 65535u, hz_w.x >> 16u);\n \
vec2 hz_d1 = vec2(hz_w.y & 65535u, hz_w.y >> 16u) - hz_t0;\n \
vec2 hz_d2 = vec2(hz_w.z & 65535u, hz_w.z >> 16u) - hz_t0;\n \
vec3 hz_e1 = hz_p1 - hz_p0;\n \
vec3 hz_e2 = hz_p2 - hz_p0;\n \
vec3 hz_n = cross(hz_e1, hz_e2);\n \
if (dot(hz_n, hz_n) > 1e-12) {\n \
hz_Normal = normalize(hz_n);\n \
float hz_r = hz_d1.x * hz_d2.y - hz_d2.x * hz_d1.y;\n \
vec3 hz_t = (hz_e1 * hz_d2.y - hz_e2 * hz_d1.y) * sign(hz_r);\n \
vec3 hz_b = (hz_e2 * hz_d1.x - hz_e1 * hz_d2.x) * sign(hz_r);\n \
if (dot(hz_t, hz_t) > 1e-12) {\n \
hz_t = normalize(hz_t - hz_Normal * dot(hz_Normal, hz_t));\n \
hz_tangent = vec4(hz_t, dot(cross(hz_t, hz_Normal), hz_b) < 0.0 ? -1.0 : 1.0);\n \
}\n \
}\n";
impl PackAtlas {
/// The vertex inputs of a gbuffers program drawing terrain (`TerrainVertex`, terrain.wgsl's
/// `vs_terrain` or, for `flat` draws, `vs_terrain_flat`), in atlas coordinates.
@@ -127,9 +151,11 @@ impl PackAtlas {
"layout(set = 1, binding = 0) readonly buffer HzBlockSlots { uint hz_block_slots[]; };\n\
layout(set = 1, binding = 1) readonly buffer HzSlotOrigins { vec4 hz_slot_origins[]; };\n",
);
// `mc_Entity` of each sprite layer: id, then 1 for fluids or -1 (the game's table).
// `mc_Entity` of each sprite layer: id, then 1 for fluids or -1 (the game's table),
// and the arena page's vertices (`TerrainVertex`, six words each).
declarations.push_str(
"layout(set = 3, binding = 0) readonly buffer HzBlockIds { int hz_block_ids[]; };\n",
"layout(set = 3, binding = 0) readonly buffer HzBlockIds { int hz_block_ids[]; };\n\
layout(set = 3, binding = 1) readonly buffer HzVertices { uint hz_vertices[]; };\n",
);
"hz_slot_origins[hz_block_slots[uint(gl_VertexIndex) >> 8u]]"
} else {
@@ -153,10 +179,15 @@ impl PackAtlas {
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",
hz_Normal = vec3(0.0, 1.0, 0.0);\n \
hz_tangent = vec4(1.0, 0.0, 0.0, 1.0);\n",
scale[0], scale[1],
);
declarations.push_str("vec2 hz_cell; vec2 hz_scale;\n");
let mut body = body;
if flat {
body.push_str(FACE);
}
declarations.push_str("vec2 hz_cell; vec2 hz_scale; vec4 hz_tangent;\n");
let entity = if flat {
"vec4(float(hz_block_ids[2u * hz_layer]), float(hz_block_ids[2u * hz_layer + 1u]), 0.0, 0.0)"
} else {
@@ -168,7 +199,7 @@ impl PackAtlas {
"mc_midTexCoord",
"vec4((hz_cell + 0.5) * hz_scale, 0.0, 1.0)",
),
("at_tangent", "vec4(1.0, 0.0, 0.0, 1.0)"),
("at_tangent", "hz_tangent"),
("vaPosition", "hz_Vertex.xyz"),
("vaUV0", "hz_MultiTexCoord0.xy"),
("vaUV2", "hz_MultiTexCoord1.xy"),
+72 -34
View File
@@ -211,8 +211,10 @@ pub struct PackPost {
down: HashMap<wgpu::TextureFormat, (wgpu::RenderPipeline, wgpu::BindGroupLayout)>,
/// The per-draw uniforms of gbuffers programs.
draws: DrawUniforms,
/// `mc_Entity`'s table of flat terrain, and its bind group.
block_ids: Option<(wgpu::BindGroupLayout, wgpu::BindGroup)>,
/// Set 3 of flat terrain (`mc_Entity`'s table) and its bind group for each arena page,
/// with the page buffer it was made for.
block_ids: Option<(wgpu::BindGroupLayout, wgpu::Buffer)>,
page_groups: HashMap<u32, (wgpu::Buffer, wgpu::BindGroup)>,
/// `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`.
@@ -498,8 +500,14 @@ fn attach(
})
}
/// `mc_Entity`'s table as a storage buffer (vertex stage) at set 3; -1 pairs when empty.
fn block_ids(device: &wgpu::Device, table: &[i32]) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
/// Draws the game's terrain (`true`: translucent) into a pass; calls its third argument with
/// each arena page before drawing from it.
pub(super) type TerrainDraw<'a> =
dyn FnMut(&mut wgpu::RenderPass<'_>, bool, &dyn Fn(&mut wgpu::RenderPass<'_>, u32)) + 'a;
/// Set 3 of flat terrain, read by the vertex stage: `mc_Entity`'s table (-1 pairs when empty)
/// and, per arena page, the page's vertices (a vertex reads its quad's corners for its normal).
fn block_ids(device: &wgpu::Device, table: &[i32]) -> (wgpu::BindGroupLayout, wgpu::Buffer) {
let empty = [-1, -1];
let table = if table.is_empty() { &empty[..] } else { table };
let buffer = wgpu::util::DeviceExt::create_buffer_init(
@@ -510,28 +518,21 @@ fn block_ids(device: &wgpu::Device, table: &[i32]) -> (wgpu::BindGroupLayout, wg
usage: wgpu::BufferUsages::STORAGE,
},
);
let storage = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Shader pack block ids"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: Some("Shader pack terrain"),
entries: &[storage(0), storage(1)],
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Shader pack block ids"),
layout: &layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
}],
});
(layout, group)
(layout, buffer)
}
/// The game's geometry a gbuffers program draws: its vertex buffers and, for flat draws
@@ -545,6 +546,8 @@ pub(super) struct Geometry<'a> {
pub atlas: Option<wgpu::TextureView>,
/// `mc_Entity`'s table at set 3 (flat terrain).
pub ids: Option<&'a wgpu::BindGroupLayout>,
/// Back faces are culled, as for the game's own terrain.
pub cull: bool,
}
/// The pass of program `p`: a quad, or `geometry` drawn by the game. `None` (with a note) when
@@ -728,7 +731,12 @@ fn build_pass(
compilation_options: Default::default(),
buffers: geometry.map_or(&[], |g| g.buffers),
},
primitive: Default::default(),
// Rows flipped to GL's turn front faces clockwise.
primitive: wgpu::PrimitiveState {
front_face: wgpu::FrontFace::Cw,
cull_mode: geometry.filter(|g| g.cull).map(|_| wgpu::Face::Back),
..Default::default()
},
depth_stencil: geometry.map(|g| wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(g.depth_write),
@@ -854,6 +862,7 @@ impl PackPost {
depth_write: g.depth_write,
atlas: g.atlas.clone(),
ids: block_ids.as_ref().map(|i| &i.0),
cull: g.cull,
});
let terrain = post
.terrain
@@ -871,6 +880,7 @@ impl PackPost {
depth_write: false,
atlas: None,
ids: None,
cull: false,
};
let basic = post.sky.and_then(|p| build(p, Some(&basic)));
let textured = Geometry {
@@ -879,6 +889,7 @@ impl PackPost {
depth_write: false,
atlas: world.celestial.clone(),
ids: None,
cull: false,
};
let textured = post.sky_textured.and_then(|p| build(p, Some(&textured)));
Sky {
@@ -1043,6 +1054,7 @@ impl PackPost {
down,
draws,
block_ids,
page_groups: HashMap::new(),
timing: super::pack_timing::PassTiming::new(device, queue),
custom,
atlas: world.atlas.as_ref().map(|a| a.0.clone()),
@@ -1253,7 +1265,7 @@ impl PackPost {
encoder: &mut wgpu::CommandEncoder,
size: [u32; 2],
translucent: bool,
draw: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool),
draw: &mut TerrainDraw<'_>,
) {
let slot = if translucent {
&mut self.water
@@ -1278,11 +1290,6 @@ impl PackPost {
let mut rp = self.begin(encoder, &pass);
rp.set_pipeline(&pass.pipeline);
rp.set_bind_group(0, &group, &[]);
if pass.ids
&& let Some((_, ids)) = &self.block_ids
{
rp.set_bind_group(3, ids, &[]);
}
if pass.draw {
let stage = if translucent {
"TERRAIN_TRANSLUCENT"
@@ -1291,7 +1298,13 @@ impl PackPost {
};
self.draws.bind(&mut rp, stage);
}
draw(&mut rp, translucent);
let (groups, ids) = (&self.page_groups, pass.ids);
let page = |rp: &mut wgpu::RenderPass<'_>, page: u32| {
if let Some((_, group)) = groups.get(&page).filter(|_| ids) {
rp.set_bind_group(3, group, &[]);
}
};
draw(&mut rp, translucent, &page);
}
self.mips_valid &= !pass.written;
if translucent {
@@ -1362,7 +1375,7 @@ impl PackPost {
encoder: &mut wgpu::CommandEncoder,
size: [u32; 2],
frame: &super::Frame,
terrain: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool),
terrain: &mut TerrainDraw<'_>,
) {
if super::sky_visible(frame) {
self.draw_sky(device, queue, encoder, size, frame);
@@ -1533,9 +1546,34 @@ impl PackPost {
inputs: &PackInputs,
size: [u32; 2],
window: [u32; 2],
terrain: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool),
pages: &[(u32, wgpu::Buffer)],
terrain: &mut TerrainDraw<'_>,
) {
self.resize(device, size);
if let Some((layout, ids)) = &self.block_ids {
// A page that grew has a new buffer.
self.page_groups
.retain(|p, (b, _)| pages.iter().any(|(q, c)| q == p && c == b));
for (page, buffer) in pages {
self.page_groups.entry(*page).or_insert_with(|| {
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Shader pack terrain"),
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: ids.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: buffer.as_entire_binding(),
},
],
});
(buffer.clone(), group)
});
}
}
if let Some(t) = &mut self.timing {
t.begin(device, queue);
}