Merge pull request #1785 from ludovic111/feat/shader-packs-clouds

🤖 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:12:49 +01:00
committed by GitHub
15 changed files with 1075 additions and 24 deletions
+3 -3
View File
@@ -6876,12 +6876,11 @@ impl Game<'_> {
self.fangs_geometry(camera, alpha, &mut out);
let mut see_through = std::mem::take(&mut self.see_through_vertices);
see_through.clear();
self.mark_entity(out.len(), "minecraft:name_tag");
self.name_tag_geometry(camera, alpha, &mut out, &mut see_through);
self.text_display_geometry(camera, alpha, &mut out, &mut see_through);
self.see_through_vertices = see_through;
// Entity shadows (EntityRenderer.extractShadow).
self.mark_entity(out.len(), "minecraft:entity_shadow");
self.mark_translucent_entity(out.len(), "minecraft:entity_shadow");
if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() {
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
let darken = self.sky_darken();
@@ -7109,7 +7108,8 @@ impl Game<'_> {
self.boat_geometry(camera, alpha, &mut out);
self.mark_entity(out.len(), "minecraft:minecart");
self.cart_geometry(camera, alpha, &mut out);
self.mark_stage(out.len(), "BLOCK_ENTITIES");
// Beams: `gbuffers_beaconbeam`, not a block entity's program (5.4 has no stage for them).
self.mark_stage(out.len(), "NONE");
self.beacon_geometry(camera, alpha, &mut out);
self.mark_entity(out.len(), "minecraft:fishing_bobber");
self.fishing_geometry(camera, alpha, &mut out);
+4
View File
@@ -293,12 +293,16 @@ impl Game<'_> {
const FADED: u32 = 0x7F;
for tag in self.name_tags(camera, alpha) {
let o = tag.at - camera;
// `gbuffers_entities` draws name tag text (2.3); a sneaking player's faded tag, on its
// background, blends.
if tag.discrete {
self.mark_translucent_entity(out.len(), "minecraft:name_tag");
self.name_tag_quads(o, &tag.lines, FADED, true, 0, vertex_light(tag.light), out);
continue;
}
// LightCoordsUtil.lightCoordsWithEmission(lightCoords, 2).
let lit = (tag.light >> 4).max(2) << 4 | (tag.light & 15).max(2);
self.mark_entity(out.len(), "minecraft:name_tag");
self.name_tag_quads(o, &tag.lines, 0xFF, false, 0, vertex_light(lit), out);
// RenderPipelines.TEXT_SEE_THROUGH: no depth test, no lightmap.
self.name_tag_quads(o, &tag.lines, FADED, true, 2, 0, see_through);
@@ -146,9 +146,21 @@ impl Game<'_> {
/// Starts a span of the entity geometry at vertex `start` for entity type `name`
/// (`minecraft:zombie`; "" for one the pack cannot name). Nothing without a pack.
pub(super) fn mark_entity(&self, start: usize, name: &str) {
self.mark_entity_part(start, name, false);
}
/// Starts a span for entity geometry that blends (name tags, shadows).
pub(super) fn mark_translucent_entity(&self, start: usize, name: &str) {
self.mark_entity_part(start, name, true);
}
fn mark_entity_part(&self, start: usize, name: &str, translucent: bool) {
if let Some(ids) = &self.pack_ids {
let id = ids.entities.get(name).copied();
self.push_span(start, "ENTITIES", id.unwrap_or(ids.missing_entity));
if let Some(last) = self.entity_spans.borrow_mut().last_mut() {
last.translucent = translucent;
}
}
}
@@ -185,6 +197,7 @@ impl Game<'_> {
start: start as u32,
stage: horizon_shaders::render_stage(stage),
id,
translucent: false,
};
// A span that drew nothing gives way to the next.
match spans.last_mut() {
+42 -7
View File
@@ -70,6 +70,7 @@ mod lod;
mod occlusion;
mod pack_atlas;
pub mod pack_draw;
mod pack_entities;
mod pack_post;
mod pack_sky;
mod pack_timing;
@@ -491,6 +492,10 @@ pub struct Renderer {
world_post: world_post::Post,
/// The shader pack's post-processing, and the dimension (legacy id) it was loaded for.
pack_post: Option<(i32, Option<pack_post::PackPost>)>,
/// The entity vertices Horizon draws itself while a shader pack draws the others.
pack_entity_rest: Vec<Vertex>,
/// Set 1 of the cloud pipeline, for a shader pack's `gbuffers_clouds`.
cloud_bindings: wgpu::BindGroupLayout,
/// 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`).
@@ -2390,6 +2395,8 @@ impl Renderer {
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
world_post,
pack_post: None,
pack_entity_rest: Vec::new(),
cloud_bindings,
pack_atlas: None,
pack_terrain_flat: false,
hud,
@@ -2865,6 +2872,7 @@ impl Renderer {
.atlas_texture
.as_ref()
.map(|t| t.create_view(&Default::default())),
clouds: Some(&self.cloud_bindings),
};
pack_post::PackPost::new(
&self.device,
@@ -2888,6 +2896,8 @@ impl Renderer {
terrain: self.pack_terrain_inputs(),
sky: Some(pack_sky::inputs()),
celestial: Some(pack_sky::celestial_inputs()),
entities: Some(pack_entities::inputs()),
clouds: Some(pack_entities::cloud_inputs()),
}
}
@@ -3567,6 +3577,22 @@ impl Renderer {
self.uploads
.buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines));
}
// While a shader pack draws entities, the runs of `entity_spans` its programs draw are
// left out of Horizon's own entity draw.
let mut entities = frame.entities;
if !frame.title
&& let Some((_, Some(post))) = &mut self.pack_post
&& post.has_entities()
{
post.prepare_entities(
&self.device,
&self.queue,
frame.entities,
frame.entity_spans,
&mut self.pack_entity_rest,
);
entities = &self.pack_entity_rest;
}
let [
entity_quads,
crumbling_quads,
@@ -3574,12 +3600,9 @@ impl Renderer {
water_mask_quads,
shadow_quads,
translucent_particle_quads,
] = self.entity_batch.update(
frame.entities,
frame.additive,
frame.hand,
frame.see_through,
);
] = self
.entity_batch
.update(entities, frame.additive, frame.hand, frame.see_through);
let weather_quads = frame.weather.len() as u32 / 4;
let world_quads = entity_quads
+ crumbling_quads
@@ -3828,6 +3851,12 @@ impl Renderer {
.as_ref()
.and_then(|p| p.1.as_ref())
.is_some_and(|p| p.has_water());
let pack_draws_clouds = pack_post
&& self
.pack_post
.as_ref()
.and_then(|p| p.1.as_ref())
.is_some_and(|p| p.has_clouds());
let scaled = self.world_post.prepare(
&self.device,
[self.config.width, self.config.height],
@@ -4124,7 +4153,7 @@ impl Renderer {
0..1,
);
}
if cloud_quads > 0 {
if cloud_quads > 0 && !pack_draws_clouds {
pass.set_pipeline(&self.cloud_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_bind_group(1, &self.cloud_group, &[]);
@@ -4185,6 +4214,12 @@ impl Renderer {
}
}
};
post.set_clouds(pack_draws_clouds.then(|| pack_post::Clouds {
vertices: self.cloud_buffer.clone(),
group: self.cloud_group.clone(),
indices: self.indices.clone(),
quads: cloud_quads,
}));
post.run(
&self.device,
&self.queue,
@@ -214,6 +214,7 @@ impl PackAtlas {
.map(|&(n, v)| (n.to_owned(), v.to_owned()))
.collect(),
after: String::new(),
alpha_test: None,
}
}
}
@@ -16,6 +16,8 @@ pub struct EntitySpan {
pub stage: u32,
/// `entityId` for entities, `blockEntityId` for block entities (5.3), else 0.
pub id: i32,
/// An entity part that blends (a name tag, a shadow): `gbuffers_entities_translucent`.
pub translucent: bool,
}
/// `HzDraw`'s size: `renderStage`, `entityId`, `blockEntityId`, a pad, `entityColor`.
@@ -0,0 +1,462 @@
//! Entities, block entities, translucent entity parts and particles drawn by a shader pack's
//! `gbuffers_entities`, `gbuffers_block`, `gbuffers_entities_translucent` and
//! `gbuffers_particles` (spec 2.3, 5.3, 5.4): the runs of `Frame::entities` the game marked (`EntitySpan`), each its
//! own draw with its `entityId` or `blockEntityId` and `entityColor` in a per-draw slot of
//! `HzDraw` (set 2). Horizon draws whatever the pack does not.
use std::ops::Range;
use horizon_shaders::render_stage;
use super::Vertex;
use super::pack_draw::EntitySpan;
/// `HzDraw`'s size (pack_draw.rs).
const SLOT: u64 = 32;
const ATTRIBUTES: [wgpu::VertexAttribute; 6] = wgpu::vertex_attr_array![
0 => Float32x3, 1 => Float32x2, 2 => Uint32, 3 => Unorm8x4, 4 => Uint8x4, 5 => Snorm8x4
];
/// The entity vertex: Horizon's own (`Vertex`).
pub fn buffers() -> [Option<wgpu::VertexBufferLayout<'static>>; 1] {
[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &ATTRIBUTES,
})]
}
/// What `gbuffers_entities` and `gbuffers_block` read from an entity vertex: camera-relative
/// position, the shared atlas's UV, colour, light (block, sky in 16ths) and the world-oriented
/// normal. The quad's corners, read from the same vertices at set 1, give the face normal where
/// the vertex has none (block entities) and `at_tangent` along the texture's u, as for terrain.
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\
layout(set = 1, binding = 0) readonly buffer HzEntityVertices { uint hz_entity_vertices[]; };\n\
vec4 hz_tangent; vec2 hz_mid;\n"
.to_owned();
let words = std::mem::size_of::<Vertex>() / 4;
let corner = |k: usize, field: &str| {
let at = |o: usize| format!("hz_entity_vertices[hz_q + {}u]", k * words + o);
match field {
"pos" => format!("uintBitsToFloat(uvec3({}, {}, {}))", at(0), at(1), at(2)),
_ => format!("uintBitsToFloat(uvec2({}, {}))", at(3), at(4)),
}
};
let body = format!(
" uint hz_q = (uint(gl_VertexIndex) & ~3u) * {words}u;\n \
vec3 hz_e1 = {p1} - {p0};\n \
vec3 hz_e2 = {p2} - {p0};\n \
vec2 hz_t0 = {t0};\n \
vec2 hz_d1 = {t1} - hz_t0;\n \
vec2 hz_d2 = {t2} - hz_t0;\n \
hz_mid = (hz_t0 + {t2}) * 0.5;\n \
vec3 hz_n = cross(hz_e1, hz_e2);\n \
hz_Normal = dot(hz_v_normal.xyz, hz_v_normal.xyz) > 0.01 ? normalize(hz_v_normal.xyz)\n \
: dot(hz_n, hz_n) > 1e-12 ? normalize(hz_n) : vec3(0.0, 1.0, 0.0);\n \
hz_tangent = vec4(1.0, 0.0, 0.0, 1.0);\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 \
hz_t -= hz_Normal * dot(hz_Normal, hz_t);\n \
if (dot(hz_t, hz_t) > 1e-12) {{\n \
hz_t = normalize(hz_t);\n \
hz_tangent = vec4(hz_t, dot(cross(hz_t, hz_Normal), hz_b) < 0.0 ? -1.0 : 1.0);\n \
}}\n \
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",
p0 = corner(0, "pos"),
p1 = corner(1, "pos"),
p2 = corner(2, "pos"),
t0 = corner(0, "uv"),
t1 = corner(1, "uv"),
t2 = corner(2, "uv"),
);
let attributes = [
("at_tangent", "hz_tangent"),
("mc_midTexCoord", "vec4(hz_mid, 0.0, 1.0)"),
("vaPosition", "hz_Vertex.xyz"),
("vaUV0", "hz_v_uv"),
("vaUV1", "ivec2(0, 10)"),
("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(),
// Cutout, as vanilla's entity types mostly are (OQ-23): the loader's test at 0.1.
alpha_test: Some(horizon_shaders::AlphaTest {
op: ">",
reference: 0.1,
}),
}
}
/// What `gbuffers_clouds` reads from the clouds' mesh (entity vertices, `vs_cloud`): the
/// position moved by the clouds' offset, the colour of the face's shade from their palette,
/// full sky light. Set 1 holds the clouds' uniform (`clouds::Uniform`).
pub fn cloud_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\
layout(set = 1, binding = 0) uniform HzCloud { vec4 hz_cloud_offset; vec4 hz_cloud_colors[4]; };\n"
.to_owned();
let body = " hz_Vertex = vec4(hz_v_pos + hz_cloud_offset.xyz, 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_cloud_colors[min(hz_v_light.x, 3u)];\n \
hz_Normal = dot(hz_v_normal.xyz, hz_v_normal.xyz) > 0.01 ? normalize(hz_v_normal.xyz) : vec3(0.0, 1.0, 0.0);\n"
.to_owned();
let attributes = [
("vaPosition", "hz_Vertex.xyz"),
("vaUV0", "hz_v_uv"),
("vaUV2", "ivec2(0, 240)"),
("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(),
alpha_test: None,
}
}
/// `entityColor` for a run whose first quad carries overlay code `overlay`: the hurt red or a
/// white flash, its alpha how much of that colour shows over the entity (vanilla mixes the
/// overlay texel's colour in by one minus the texel's alpha).
pub fn entity_color(overlay: u32) -> [f32; 4] {
let [r, g, b, a] = crate::overlay::HURT_TEXEL.map(|v| f32::from(v) / 255.0);
let white = |u: u32| {
let a = f32::from(crate::overlay::white_alpha(u)) / 255.0;
[1.0, 1.0, 1.0, 1.0 - a]
};
match overlay {
1 | 8 => [r, g, b, 1.0 - a],
5 => white(15),
16..32 => white(overlay - crate::overlay::WHITE),
_ => [0.0; 4],
}
}
/// One draw: its quads in `PackEntities`' buffer, its program and its slot of `HzDraw`.
pub(super) struct Draw {
/// The first vertex.
pub base: u32,
pub quads: u32,
/// The program that draws it (`ENTITY`, `BLOCK`, `TRANSLUCENT`, `PARTICLE`).
pub program: usize,
pub slot: u32,
}
/// The vertices and per-draw uniforms of the runs a pack draws, rebuilt each frame.
pub(super) struct PackEntities {
vertices: wgpu::Buffer,
/// Set 1: the vertices again, for the quads' corners.
pub table: wgpu::BindGroupLayout,
pub table_group: wgpu::BindGroup,
slots: wgpu::Buffer,
pub group: wgpu::BindGroup,
stride: u64,
/// Two triangles per quad, for `quads` quads.
pub indices: wgpu::Buffer,
quads: u32,
scratch: Vec<Vertex>,
uniforms: Vec<u8>,
pub draws: Vec<Draw>,
}
impl PackEntities {
pub fn new(device: &wgpu::Device, layout: &wgpu::BindGroupLayout) -> Self {
let stride = SLOT.max(u64::from(
device.limits().min_uniform_buffer_offset_alignment,
));
let table = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Shader pack entity vertices"),
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,
}],
});
let (vertices, table_group) = Self::vertex_buffer(device, &table, 4096);
let (slots, group) = Self::slot_buffer(device, layout, 64, stride);
Self {
vertices,
table,
table_group,
slots,
group,
stride,
indices: quad_indices(device, 1024),
quads: 1024,
scratch: Vec::new(),
uniforms: Vec::new(),
draws: Vec::new(),
}
}
fn vertex_buffer(
device: &wgpu::Device,
table: &wgpu::BindGroupLayout,
vertices: u64,
) -> (wgpu::Buffer, wgpu::BindGroup) {
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack entity vertices"),
size: vertices * std::mem::size_of::<Vertex>() as u64,
usage: wgpu::BufferUsages::VERTEX
| wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Shader pack entity vertices"),
layout: table,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
}],
});
(buffer, group)
}
fn slot_buffer(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
slots: u64,
stride: u64,
) -> (wgpu::Buffer, wgpu::BindGroup) {
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack entity draws"),
size: slots * stride,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Shader pack entity draws"),
layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &buffer,
offset: 0,
size: wgpu::BufferSize::new(SLOT),
}),
}],
});
(buffer, group)
}
pub fn vertices(&self) -> wgpu::BufferSlice<'_> {
self.vertices.slice(..)
}
/// The dynamic offset of draw slot `slot`.
pub fn offset(&self, slot: u32) -> u32 {
(u64::from(slot) * self.stride) as u32
}
/// Splits `entities` between the pack, which draws the runs of `spans` its programs cover
/// (`drawn`: whether it has `gbuffers_entities`, `gbuffers_block` or their fallbacks), and
/// Horizon, which draws the rest (`rest`). Uploads the pack's part.
#[allow(clippy::too_many_arguments)]
pub fn prepare(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
layout: &wgpu::BindGroupLayout,
entities: &[Vertex],
spans: &[EntitySpan],
drawn: [bool; PROGRAMS],
rest: &mut Vec<Vertex>,
) {
self.draws.clear();
self.scratch.clear();
self.uniforms.clear();
rest.clear();
let first = spans.first().map_or(entities.len(), |s| s.start as usize);
rest.extend_from_slice(&entities[..first.min(entities.len())]);
for (span, range) in runs(entities.len(), spans) {
let run = &entities[range];
let Some(program) = drawn_by_pack(&span, drawn).filter(|_| plain(run)) else {
rest.extend_from_slice(run);
continue;
};
if run.is_empty() {
continue;
}
let start = self.scratch.len() as u32;
self.scratch.extend_from_slice(run);
let (entity_id, block_id) = match program {
BLOCK => (0, span.id),
_ => (span.id, 0),
};
let mut bytes = [0u8; SLOT as usize];
bytes[0..4].copy_from_slice(&(span.stage as i32).to_le_bytes());
bytes[4..8].copy_from_slice(&entity_id.to_le_bytes());
bytes[8..12].copy_from_slice(&block_id.to_le_bytes());
for (i, c) in entity_color(run[0].layer).iter().enumerate() {
bytes[16 + 4 * i..20 + 4 * i].copy_from_slice(&c.to_le_bytes());
}
self.uniforms.extend_from_slice(&bytes);
self.uniforms
.resize(self.uniforms.len() + (self.stride - SLOT) as usize, 0);
self.draws.push(Draw {
base: start,
quads: run.len() as u32 / 4,
program,
slot: self.draws.len() as u32,
});
}
if self.draws.is_empty() {
return;
}
let vertex_size = std::mem::size_of::<Vertex>() as u64;
let (need_vertices, need_slots) = (self.scratch.len() as u64, self.draws.len() as u64);
let have_vertices = self.vertices.size() / vertex_size;
let have_slots = self.slots.size() / self.stride;
if need_vertices > have_vertices {
(self.vertices, self.table_group) =
Self::vertex_buffer(device, &self.table, need_vertices.next_power_of_two());
}
if need_slots > have_slots {
(self.slots, self.group) =
Self::slot_buffer(device, layout, need_slots.next_power_of_two(), self.stride);
}
let quads = self.draws.iter().map(|d| d.quads).max().unwrap_or(0);
if quads > self.quads {
self.quads = quads.next_power_of_two();
self.indices = quad_indices(device, self.quads);
}
queue.write_buffer(&self.vertices, 0, bytemuck::cast_slice(&self.scratch));
queue.write_buffer(&self.slots, 0, &self.uniforms);
}
}
/// Two triangles for each of `quads` quads, from vertex 0.
fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer {
let indices: Vec<u32> = (0..quads)
.flat_map(|q| [0, 1, 2, 0, 2, 3].map(|i| q * 4 + i))
.collect();
wgpu::util::DeviceExt::create_buffer_init(
device,
&wgpu::util::BufferInitDescriptor {
label: Some("Shader pack entity indices"),
contents: bytemuck::cast_slice(&indices),
usage: wgpu::BufferUsages::INDEX,
},
)
}
/// Whether a run holds only geometry a gbuffers program can draw from the shared atlas: no
/// celestial body, cloud, beam, End portal or crack (overlay codes Horizon's entity shader
/// draws in its own way; entity.wgsl).
fn plain(run: &[Vertex]) -> bool {
run.iter()
.step_by(4)
.all(|v| !matches!(v.layer, 2 | 4 | 6 | 9 | 10 | 11 | 12))
}
/// The programs of entity runs, in the order they draw.
pub const ENTITY: usize = 0;
pub const BLOCK: usize = 1;
pub const TRANSLUCENT: usize = 2;
pub const PARTICLE: usize = 3;
pub const PROGRAMS: usize = 4;
/// Which program draws `span`'s run, given which of them (or their fallbacks) the pack has;
/// `None`: Horizon draws it.
pub fn drawn_by_pack(span: &EntitySpan, drawn: [bool; PROGRAMS]) -> Option<usize> {
let program = if span.stage == render_stage("ENTITIES") {
if span.translucent {
TRANSLUCENT
} else {
ENTITY
}
} else if span.stage == render_stage("BLOCK_ENTITIES") {
BLOCK
} else if span.stage == render_stage("PARTICLES") {
PARTICLE
} else {
return None;
};
drawn[program].then_some(program)
}
/// Each span with its vertex range: from its start to the next span's (or the end).
pub fn runs(
len: usize,
spans: &[EntitySpan],
) -> impl Iterator<Item = (EntitySpan, Range<usize>)> + '_ {
spans.iter().enumerate().map(move |(i, s)| {
let end = spans.get(i + 1).map_or(len, |n| n.start as usize);
let start = (s.start as usize).min(len);
(*s, start..end.clamp(start, len))
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runs_split_the_list_between_pack_and_horizon() {
let v = |layer| Vertex {
layer,
..bytemuck::Zeroable::zeroed()
};
let span = |start, stage: &str, id| EntitySpan {
start,
stage: render_stage(stage),
id,
translucent: false,
};
let spans = [
span(2, "ENTITIES", 7),
span(5, "PARTICLES", 0),
span(6, "BLOCK_ENTITIES", 9),
];
let ranges: Vec<_> = runs(10, &spans).map(|(_, r)| r).collect();
assert_eq!(ranges, [2..5, 5..6, 6..10]);
let all = [true; PROGRAMS];
assert_eq!(drawn_by_pack(&spans[0], all), Some(ENTITY));
assert_eq!(drawn_by_pack(&spans[1], all), Some(PARTICLE));
assert_eq!(drawn_by_pack(&spans[1], [true, true, true, false]), None);
assert_eq!(drawn_by_pack(&spans[2], [true, false, true, true]), None);
assert_eq!(drawn_by_pack(&spans[2], all), Some(BLOCK));
let shadow = EntitySpan {
translucent: true,
..spans[0]
};
assert_eq!(drawn_by_pack(&shadow, all), Some(TRANSLUCENT));
assert_eq!(drawn_by_pack(&span(0, "DESTROY", 0), all), None);
// A beacon beam's quads stay Horizon's.
assert!(plain(&[v(0), v(0), v(0), v(0), v(1)]));
assert!(!plain(&[v(0), v(0), v(0), v(0), v(6)]));
assert_eq!(entity_color(1)[0], 1.0);
assert!((entity_color(1)[3] - (1.0 - 178.0 / 255.0)).abs() < 1e-6);
assert_eq!(entity_color(0), [0.0; 4]);
}
}
+241 -5
View File
@@ -16,6 +16,7 @@ use std::collections::HashMap;
use horizon_shaders::{Format, Group, Kind, Post, Val};
use super::pack_draw::DrawUniforms;
use super::pack_entities::{PROGRAMS, PackEntities};
use super::pack_sky::PackSky;
use super::pack_uniforms::{self, FrameUniforms, PackInputs};
@@ -130,6 +131,15 @@ struct Sky {
textured: Option<Pass>,
}
/// Entities, block entities, translucent entity parts and particles a pack draws
/// (`pack_entities::ENTITY`... order), after terrain or, `late`, after deferred; Horizon draws
/// the others.
struct Entities {
geometry: PackEntities,
passes: [Option<Pass>; PROGRAMS],
late: [bool; PROGRAMS],
}
struct Pass {
name: String,
group: Group,
@@ -192,6 +202,17 @@ pub(super) struct World<'a> {
pub block_ids: &'a [i32],
/// The atlas of the sun and moon's sprites.
pub celestial: Option<wgpu::TextureView>,
/// Set 1 of the clouds' draw: their offset and palette.
pub clouds: Option<&'a wgpu::BindGroupLayout>,
}
/// This frame's clouds, when the pack draws them: their vertices, uniform, quad indices and
/// quad count.
pub(super) struct Clouds {
pub vertices: wgpu::Buffer,
pub group: wgpu::BindGroup,
pub indices: wgpu::Buffer,
pub quads: u32,
}
pub struct PackPost {
@@ -203,6 +224,14 @@ pub struct PackPost {
water: Option<Pass>,
/// What draws the sky (`gbuffers_skybasic` or its fallback), before terrain, and its vertices.
sky: Option<Sky>,
/// What draws entities and block entities, after terrain, and their vertices.
entities: Option<Entities>,
/// What draws the clouds, after entities, and this frame's clouds.
clouds: Option<Pass>,
cloud_draw: Option<Clouds>,
/// 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,
/// A program after translucent terrain reads `depthtex1`: it is copied before water.
depth1: bool,
/// Buffers with mipmaps (filterable ones a program asks them for).
@@ -901,6 +930,50 @@ impl PackPost {
}
});
let sky = sky.filter(|s| s.basic.is_some() || s.textured.is_some());
let programs = [
post.entities,
post.block,
post.entities_translucent,
post.particles,
];
let late = [false, false, post.translucent_late, post.particles_late];
let entity_vertices = programs
.iter()
.any(Option::is_some)
.then(|| PackEntities::new(device, &draws.layout));
let entity_buffers = super::pack_entities::buffers();
let entity_geometry = entity_vertices.as_ref().map(|e| Geometry {
buffers: &entity_buffers,
table: Some(&e.table),
depth_write: true,
atlas: world.celestial.clone(),
ids: None,
cull: false,
});
let entity_passes = programs.map(|p| {
p.zip(entity_geometry.as_ref())
.and_then(|(p, g)| build(p, Some(g)))
});
let entities = entity_vertices
.filter(|_| entity_passes.iter().any(Option::is_some))
.map(|geometry| Entities {
geometry,
passes: entity_passes,
late,
});
let cloud_geometry = world.clouds.map(|layout| Geometry {
buffers: &entity_buffers,
table: Some(layout),
depth_write: true,
atlas: world.celestial.clone(),
ids: None,
cull: false,
});
let hides_clouds = post.clouds.is_some() && cloud_geometry.is_some();
let clouds = post
.clouds
.zip(cloud_geometry.as_ref())
.and_then(|(p, g)| build(p, Some(g)));
// 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<Pass> = post
@@ -923,6 +996,20 @@ impl PackPost {
notes.push(format!("the {part} draw with {}", p.name));
}
}
let parts = [
"entities",
"block entities",
"translucent entities",
"particles",
];
if let Some(c) = &clouds {
notes.push(format!("clouds draw with {}", c.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));
}
}
let depth1 = water.is_some()
&& passes
.iter()
@@ -940,6 +1027,8 @@ impl PackPost {
.iter()
.flat_map(|s| s.basic.iter().chain(&s.textured))
.chain(&terrain)
.chain(entities.iter().flat_map(|e| e.passes.iter().flatten()))
.chain(&clouds)
.chain(&water)
.find(touched)
.map(|_| true)
@@ -955,6 +1044,8 @@ impl PackPost {
let blit_depth = terrain.is_some()
|| water.is_some()
|| sky.is_some()
|| entities.is_some()
|| clouds.is_some()
|| passes.iter().any(|p| {
p.samplers
.iter()
@@ -1050,6 +1141,10 @@ impl PackPost {
terrain,
water,
sky,
entities,
clouds,
cloud_draw: None,
hides_clouds,
depth1,
mipped,
mips_valid: 0,
@@ -1372,7 +1467,86 @@ impl PackPost {
self.sky = Some(sky);
}
/// The sky, when it shows, then terrain.
/// Entities, block entities, translucent entity parts and particles with the pack's
/// programs, those drawn before deferred or (`late`) after: each run `prepare_entities` kept
/// is one draw with its own `entityId` or `blockEntityId` and `entityColor`.
fn draw_entities(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
size: [u32; 2],
late: bool,
) {
let Some(mut entities) = self.entities.take() else {
return;
};
let geometry = &entities.geometry;
for (program, pass) in entities.passes.iter_mut().enumerate() {
let Some(pass) = pass.as_mut().filter(|_| entities.late[program] == late) else {
continue;
};
let mut draws = geometry
.draws
.iter()
.filter(|d| d.program == program)
.peekable();
if draws.peek().is_none() {
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, &[]);
rp.set_bind_group(1, &geometry.table_group, &[]);
rp.set_vertex_buffer(0, geometry.vertices());
rp.set_index_buffer(geometry.indices.slice(..), wgpu::IndexFormat::Uint32);
for d in draws {
if pass.draw {
rp.set_bind_group(2, &geometry.group, &[geometry.offset(d.slot)]);
}
rp.draw_indexed(0..d.quads * 6, d.base as i32, 0..1);
}
}
self.mips_valid &= !pass.written;
}
self.entities = Some(entities);
}
/// Splits `entities` (`Frame::entities`) between the pack and Horizon by its runs
/// (`spans`): the pack's part is uploaded for this frame's draw, Horizon's goes to `rest`.
pub fn prepare_entities(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
entities: &[super::Vertex],
spans: &[super::pack_draw::EntitySpan],
rest: &mut Vec<super::Vertex>,
) {
let Some(e) = &mut self.entities else {
rest.clear();
rest.extend_from_slice(entities);
return;
};
let drawn = e.passes.each_ref().map(Option::is_some);
e.geometry.prepare(
device,
queue,
&self.draws.layout,
entities,
spans,
drawn,
rest,
);
}
/// Whether the pack draws entities or block entities itself.
pub fn has_entities(&self) -> bool {
self.entities.is_some()
}
/// The sky, when it shows, then terrain, entities and block entities.
fn draw_opaque(
&mut self,
device: &wgpu::Device,
@@ -1386,6 +1560,59 @@ impl PackPost {
self.draw_sky(device, queue, encoder, size, frame);
}
self.draw_terrain(device, queue, encoder, size, false, terrain);
self.draw_entities(device, queue, encoder, size, false);
self.draw_clouds(device, queue, encoder, size);
}
/// The clouds `set_clouds` gave for this frame, with `gbuffers_clouds`.
fn draw_clouds(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
size: [u32; 2],
) {
let (Some(mut pass), Some(clouds)) = (self.clouds.take(), self.cloud_draw.take()) else {
return;
};
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, &[]);
rp.set_bind_group(1, &clouds.group, &[]);
if pass.draw {
self.draws.bind(&mut rp, "CLOUDS");
}
rp.set_vertex_buffer(0, clouds.vertices.slice(..));
rp.set_index_buffer(clouds.indices.slice(..), wgpu::IndexFormat::Uint32);
rp.draw_indexed(0..clouds.quads * 6, 0, 0..1);
}
self.mips_valid &= !pass.written;
self.clouds = Some(pass);
}
/// Whether the pack draws the clouds itself (or hides them).
pub fn has_clouds(&self) -> bool {
self.hides_clouds
}
/// The clouds to draw this frame (`None`: none).
pub fn set_clouds(&mut self, clouds: Option<Clouds>) {
self.cloud_draw = clouds.filter(|c| c.quads > 0);
}
/// Translucent terrain, then the entity parts drawn after deferred.
fn draw_translucent(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
size: [u32; 2],
terrain: &mut TerrainDraw<'_>,
) {
self.draw_terrain(device, queue, encoder, size, true, terrain);
self.draw_entities(device, queue, encoder, size, true);
}
/// Regenerates the mip chain of buffer `b`'s side that programs read.
@@ -1692,8 +1919,17 @@ impl PackPost {
let mut passes = std::mem::take(&mut self.passes);
let mut seen = (false, false);
let mut shown = false;
let mut terrain_drawn = self.terrain.is_none() && self.sky.is_none();
let mut water_drawn = self.water.is_none();
let mut terrain_drawn = self.terrain.is_none()
&& self.sky.is_none()
&& self.entities.is_none()
&& self.clouds.is_none();
let late_entities = self.entities.as_ref().is_some_and(|e| {
e.passes
.iter()
.zip(e.late)
.any(|(p, late)| p.is_some() && late)
});
let mut water_drawn = self.water.is_none() && !late_entities;
for pass in &mut passes {
if !terrain_drawn && pass.group != Group::Prepare {
terrain_drawn = true;
@@ -1701,7 +1937,7 @@ impl PackPost {
}
if !water_drawn && matches!(pass.group, Group::Composite | Group::Final) {
water_drawn = true;
self.draw_terrain(device, queue, encoder, size, true, terrain);
self.draw_translucent(device, queue, encoder, size, terrain);
}
if pass.group == Group::Deferred && !seen.0 {
seen.0 = true;
@@ -1756,7 +1992,7 @@ impl PackPost {
self.draw_opaque(device, queue, encoder, size, frame, terrain);
}
if !water_drawn {
self.draw_terrain(device, queue, encoder, size, true, terrain);
self.draw_translucent(device, queue, encoder, size, terrain);
}
let targets = self.targets.as_ref().expect("resized");
let view = |m: u16, i: usize, alt: bool| {
@@ -96,6 +96,7 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
],
// At the far plane: the sky shows only where nothing else drew, and it writes no depth.
after: " gl_Position.z = gl_Position.w;\n".into(),
alpha_test: None,
}
}
@@ -120,6 +121,7 @@ pub fn celestial_inputs() -> horizon_shaders::GbuffersInputs {
("vaNormal".into(), "hz_Normal".into()),
],
after: " gl_Position.z = gl_Position.w;\n".into(),
alpha_test: None,
}
}
+2 -1
View File
@@ -132,7 +132,8 @@ impl PassTiming {
fn report(&mut self) {
let mut total = 0.0;
let mut parts = Vec::new();
for (name, v) in &mut self.samples {
// A pass that did not run in this window (no entities, the sky out of sight) is left out.
for (name, v) in self.samples.iter_mut().filter(|s| !s.1.is_empty()) {
v.sort_by(f32::total_cmp);
let median = v[v.len() / 2];
total += median;
+1 -1
View File
@@ -44,6 +44,6 @@ pub use post::{
pub use preprocess::{Diagnostic, Origin, Preprocessed, preprocess};
pub use properties::{Entry, Note, Properties};
pub use translate::{
DRAW_UNIFORMS, Error, GbuffersInputs, Interface, Program, Sampler, Target, Uniform,
AlphaTest, DRAW_UNIFORMS, Error, GbuffersInputs, Interface, Program, Sampler, Target, Uniform,
translate_composite, translate_gbuffers,
};
+164 -4
View File
@@ -103,6 +103,43 @@ const SKY_TEXTURED: [&str; 3] = [
"gbuffers_basic",
];
/// `gbuffers_entities` and its fallbacks (2.3).
const ENTITIES: [&str; 4] = [
"gbuffers_entities",
"gbuffers_textured_lit",
"gbuffers_textured",
"gbuffers_basic",
];
/// `gbuffers_block` and its fallbacks (2.3).
const BLOCK: [&str; 5] = [
"gbuffers_block",
"gbuffers_terrain",
"gbuffers_textured_lit",
"gbuffers_textured",
"gbuffers_basic",
];
/// `gbuffers_clouds`: no fallback, the game draws its clouds otherwise (OQ-3).
const CLOUDS: [&str; 1] = ["gbuffers_clouds"];
/// `gbuffers_entities_translucent` and its fallbacks (2.3).
const ENTITIES_TRANSLUCENT: [&str; 5] = [
"gbuffers_entities_translucent",
"gbuffers_entities",
"gbuffers_textured_lit",
"gbuffers_textured",
"gbuffers_basic",
];
/// `gbuffers_particles` and its fallbacks (2.3).
const PARTICLES: [&str; 4] = [
"gbuffers_particles",
"gbuffers_textured_lit",
"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,
@@ -149,6 +186,20 @@ pub struct Post {
pub sky: Option<PostProgram>,
/// What draws the sun and moon, between the sunset and the stars.
pub sky_textured: Option<PostProgram>,
/// What draws entities, after terrain.
pub entities: Option<PostProgram>,
/// What draws block entities, after terrain.
pub block: Option<PostProgram>,
/// What draws translucent entities (name tags, shadows), after the others.
pub entities_translucent: Option<PostProgram>,
/// What draws particles.
pub particles: Option<PostProgram>,
/// What draws the game's clouds.
pub clouds: 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).
pub particles_late: bool,
/// The custom uniforms of `shaders.properties` (3.4).
pub custom: Custom,
pub config: Config,
@@ -174,6 +225,10 @@ pub struct GameInputs {
pub terrain: Option<GbuffersInputs>,
pub sky: Option<GbuffersInputs>,
pub celestial: Option<GbuffersInputs>,
/// Entities and block entities (one vertex format).
pub entities: Option<GbuffersInputs>,
/// The clouds' mesh.
pub clouds: Option<GbuffersInputs>,
}
/// Loads the post-processing programs of `folder` and, for the geometry `inputs` describes, the
@@ -194,6 +249,13 @@ pub fn load_post(
water: None,
sky: None,
sky_textured: None,
entities: None,
block: None,
entities_translucent: None,
particles: None,
clouds: None,
translucent_late: false,
particles_late: false,
custom: Custom::parse(properties),
config: Config::default(),
notes: Vec::new(),
@@ -226,8 +288,15 @@ pub fn load_post(
}
let mut gbuffers = |names: &[&str], group, inputs: &GbuffersInputs| {
names.iter().find_map(|name| {
// `alphaTest.<program>` replaces the geometry's default test (OQ-23).
let key = properties.get(&format!("alphaTest.{name}"));
let test = key.and_then(|v| crate::AlphaTest::parse(v.trim()));
let mut inputs = inputs.clone();
if let Some(test) = test {
inputs.alpha_test = test;
}
loader.load(name.to_string(), group, |v, f| {
translate_gbuffers(v, f, Target::Buffers, inputs)
translate_gbuffers(v, f, Target::Buffers, &inputs)
})
})
};
@@ -246,6 +315,50 @@ pub fn load_post(
p.blend = blend(properties, &p.name).unwrap_or(Some(CELESTIAL_BLEND));
p
});
// Entities and block entities draw without blending, as terrain does and as vanilla's
// cutout entity types do, unless `blend.*` says otherwise (OQ-23).
let entity_blend = |p: Option<PostProgram>| {
p.map(|mut p| {
p.blend = blend(properties, &p.name).flatten();
p
})
};
let (entities, block) = match &inputs.entities {
Some(i) => (
entity_blend(gbuffers(&ENTITIES, Group::Gbuffers, i)),
entity_blend(gbuffers(&BLOCK, Group::Gbuffers, i)),
),
None => (None, None),
};
// Translucent entities and particles blend (OQ-23). Particles keep vanilla's alpha cut at
// 0.1; translucent entities lose only fully transparent texels (a shadow fades out).
let translucent =
|names: &[&str],
cut: f32,
gbuffers: &mut dyn FnMut(&[&str], &GbuffersInputs) -> Option<PostProgram>| {
let i = inputs.entities.as_ref()?;
let mut i = i.clone();
i.alpha_test = Some(crate::AlphaTest {
op: ">",
reference: cut,
});
gbuffers(names, &i).map(|mut p| {
p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_BLEND));
p
})
};
let mut gbuffers_dyn = |names: &[&str], i: &GbuffersInputs| gbuffers(names, Group::Gbuffers, i);
let entities_translucent = translucent(&ENTITIES_TRANSLUCENT, 0.0, &mut gbuffers_dyn);
let particles = translucent(&PARTICLES, 0.1, &mut gbuffers_dyn);
// Clouds blend, as vanilla's do (OQ-23).
let clouds = inputs
.clouds
.as_ref()
.and_then(|i| gbuffers_dyn(&CLOUDS, i));
let clouds = clouds.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).
@@ -261,6 +374,20 @@ pub fn load_post(
}
loader.post.sky = sky;
loader.post.sky_textured = sky_textured;
loader.post.entities = entities;
loader.post.block = block;
loader.post.entities_translucent = entities_translucent;
loader.post.particles = particles;
loader.post.clouds = clouds;
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
// `mixed` draws them after deferred too.
loader.post.particles_late = match properties.get("particles.ordering").map(str::trim) {
Some("before") => false,
Some(_) => true,
None => !flag("particles.before.deferred").unwrap_or(false),
};
post.config = std::mem::take(&mut post.config).finish();
post
}
@@ -523,8 +650,8 @@ mod tests {
assert!(post.programs.iter().any(|p| p.name == "composite3"));
}
/// Water falls back to the terrain chain and blends by default, as the sky does; `blend.*`
/// overrides.
/// Water falls back to the terrain chain and blends by default, as the sky does; entities
/// and block entities fall back along theirs; `blend.*` overrides.
#[test]
fn water_falls_back_to_terrain_and_blends() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/packs/terrain-test");
@@ -538,7 +665,9 @@ mod tests {
let inputs = GameInputs {
terrain: Some(inputs.clone()),
sky: Some(inputs.clone()),
celestial: Some(inputs),
celestial: Some(inputs.clone()),
entities: Some(inputs.clone()),
clouds: Some(inputs),
};
let post = load_post(&pack, "", &Properties::default(), &macros, &inputs);
let (terrain, water) = (post.terrain.unwrap(), post.water.unwrap());
@@ -563,6 +692,37 @@ mod tests {
(water.group, water.blend),
(Group::Translucent, Some(TRANSLUCENT_BLEND))
);
// Entities fall back to gbuffers_textured, block entities to gbuffers_terrain; both
// draw without blending.
let (entities, block) = (post.entities.unwrap(), post.block.unwrap());
assert_eq!(
(entities.name.as_str(), entities.blend),
("gbuffers_textured", None)
);
assert_eq!(
(block.name.as_str(), block.blend),
("gbuffers_terrain", None)
);
// Translucent entity parts and particles blend; particles draw after deferred unless
// the pack says otherwise, translucent entities before unless `separateEntityDraws`.
let (translucent, particles) = (
post.entities_translucent.as_ref().unwrap(),
post.particles.as_ref().unwrap(),
);
assert_eq!(
(translucent.name.as_str(), translucent.blend),
("gbuffers_textured", Some(TRANSLUCENT_BLEND))
);
assert_eq!(particles.blend, Some(TRANSLUCENT_BLEND));
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());
let ordering = Properties::parse(
"particles.ordering = before\nseparateEntityDraws = true\n",
&macros,
);
let post = load_post(&pack, "", &ordering, &macros, &inputs);
assert!(!post.particles_late && post.translucent_late);
let properties = Properties::parse(
"blend.gbuffers_terrain = ONE ONE ZERO ONE\nblend.gbuffers_water = off\n",
&macros,
+125 -1
View File
@@ -111,6 +111,41 @@ pub struct GbuffersInputs {
pub attributes: Vec<(String, String)>,
/// GLSL statements run last in `main`, with `gl_Position` in wgpu's clip space.
pub after: String,
/// The alpha test applied to output 0 (`gl_FragData[0]`, `gl_FragColor`), the loader's
/// (3.2 `alphaTest.<program>`): `None` keeps every fragment.
pub alpha_test: Option<AlphaTest>,
}
/// A fragment stays when its output 0's alpha compares to `reference` as `op` says (a GLSL
/// comparison operator, `true` for GL's `ALWAYS`, `false` for `NEVER`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AlphaTest {
pub op: &'static str,
pub reference: f32,
}
impl AlphaTest {
/// `alphaTest.<program>`'s value: `off`, or a GL comparison and a reference.
pub fn parse(value: &str) -> Option<Option<Self>> {
let mut words = value.split_whitespace();
let func = words.next()?;
if func == "off" {
return Some(None);
}
let op = match func.trim_start_matches("GL_") {
"NEVER" => "false",
"LESS" => "<",
"EQUAL" => "==",
"LEQUAL" => "<=",
"GREATER" => ">",
"NOTEQUAL" => "!=",
"GEQUAL" => ">=",
"ALWAYS" => return Some(None),
_ => return None,
};
let reference = words.next()?.parse().ok()?;
Some(Some(Self { op, reference }))
}
}
/// Translates a composite-style program (`composite`, `deferred`, `final`...).
@@ -343,7 +378,23 @@ fn translate(
for name in &f.inits {
writeln!(fragment_main, " {name} = hz_init_{name}();").unwrap();
}
fragment_main.push_str(" hz_main();\n}\n");
fragment_main.push_str(" hz_main();\n");
// With `out` variables the pack tests alpha itself.
if let Some(t) = gbuffers.and_then(|g| g.alpha_test)
&& f.outputs.contains(&0)
&& !f.frag_outs.iter().any(|(n, _)| *n == 0)
{
match t.op {
"false" => fragment_main.push_str(" discard;\n"),
op => writeln!(
fragment_main,
" if (!(hz_out0.a {op} {:?})) {{ discard; }}",
t.reference
)
.unwrap(),
}
}
fragment_main.push_str("}\n");
let v_text = format!(
"{}{}{vertex_main}",
@@ -651,6 +702,79 @@ mod tests {
}
}
/// Code after an unconditional `discard` (BSL's `gbuffers_clouds` with its own clouds on)
/// or `return;` still makes a valid module.
#[test]
fn code_after_discard_or_return_translates() {
let vsh = "#version 120\nvoid main() { gl_Position = ftransform(); }\n";
for fsh in [
"#version 120\nuniform sampler2D texture;\nvoid main() {\n discard;\n vec4 c = texture2D(texture, vec2(0.5));\n gl_FragData[0] = c;\n}\n",
"#version 120\nvoid main() {\n gl_FragData[0] = vec4(1.0);\n return;\n gl_FragData[0] = vec4(0.5);\n}\n",
] {
let files = [
("shaders/gbuffers_clouds.vsh", vsh),
("shaders/gbuffers_clouds.fsh", fsh),
];
let pack = Pack::from_zip_bytes("P.zip", zip(&files)).unwrap();
let m = Macros::standard();
let inputs = GbuffersInputs {
body: " hz_Vertex = vec4(0.0, 0.0, 0.0, 1.0);\n".into(),
..Default::default()
};
translate_gbuffers(
&preprocess(&pack, "gbuffers_clouds.vsh", &m),
&preprocess(&pack, "gbuffers_clouds.fsh", &m),
Target::Buffers,
&inputs,
)
.unwrap_or_else(|e| panic!("{fsh}: {e:?}"));
}
}
#[test]
fn the_alpha_test_discards_below_its_reference() {
assert_eq!(
AlphaTest::parse("GREATER 0.1"),
Some(Some(AlphaTest {
op: ">",
reference: 0.1
}))
);
assert_eq!(AlphaTest::parse("off"), Some(None));
assert_eq!(AlphaTest::parse("GL_ALWAYS 0"), Some(None));
assert_eq!(AlphaTest::parse("SOMETIMES 0.5"), None);
let vsh = "#version 120\nvoid main() { gl_Position = ftransform(); }\n";
let legacy = "#version 120\nvoid main() { gl_FragData[0] = vec4(0.5); }\n";
let outs =
"#version 330\nlayout(location = 0) out vec4 c;\nvoid main() { c = vec4(0.5); }\n";
for (fsh, kills) in [(legacy, true), (outs, false)] {
let files = [
("shaders/gbuffers_entities.vsh", vsh),
("shaders/gbuffers_entities.fsh", fsh),
];
let pack = Pack::from_zip_bytes("P.zip", zip(&files)).unwrap();
let m = Macros::standard();
let inputs = GbuffersInputs {
body: " hz_Vertex = vec4(0.0, 0.0, 0.0, 1.0);\n".into(),
alpha_test: AlphaTest::parse("GREATER 0.1").unwrap(),
..Default::default()
};
let p = translate_gbuffers(
&preprocess(&pack, "gbuffers_entities.vsh", &m),
&preprocess(&pack, "gbuffers_entities.fsh", &m),
Target::Buffers,
&inputs,
)
.unwrap_or_else(|e| panic!("{e:?}"));
let functions = p.fragment.functions.iter().map(|(_, f)| f);
let kill = functions
.chain([&p.fragment.entry_points[0].function])
.any(|f| format!("{:?}", f.body).contains("Kill"));
// With `out` variables the pack tests alpha itself.
assert_eq!(kill, kills, "{fsh}");
}
}
#[test]
fn gbuffers_programs_read_the_games_vertices() {
let vsh = "#version 120\nattribute vec4 mc_Entity;\nattribute vec2 mc_midTexCoord;\nvarying vec2 uv;\nvarying vec2 light;\n\
@@ -190,6 +190,13 @@ impl Stage<'_> {
}
let replaced: Option<String> = match t {
"main" if depth == 0 && called => Some("hz_main".into()),
// naga's frontend leaves the code after an unconditional `discard` or `return;`
// unreachable but half-built (a module that fails validation): behind an `if`
// it stays reachable as far as naga knows.
"discard" => Some("if (true) discard".into()),
"return" if next(i).is_some_and(|j| self.tokens[j] == ";") => {
Some("if (true) return".into())
}
// GLSL's `modf`, which naga's frontend lacks.
"modf" if called => Some("hz_modf".into()),
"texture2D" | "texture1D" | "texture3D" | "textureCube" if called => {
+6 -2
View File
@@ -172,16 +172,20 @@ fn real_packs_read() {
let inputs = horizon_shaders::GameInputs {
terrain: Some(terrain.clone()),
sky: Some(terrain.clone()),
celestial: Some(terrain),
celestial: Some(terrain.clone()),
entities: Some(terrain.clone()),
clouds: 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 {:?} {:?}, entities {:?} {:?}, {} 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.entities.as_ref().map(|t| &t.name),
post.block.as_ref().map(|t| &t.name),
post.notes.len() + post.config.notes.len(),
start.elapsed().as_secs_f64() * 1000.0
);