Merge pull request #1744 from ludovic111/feat/shader-packs-normals

🤖 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 02:52:49 +01:00
committed by GitHub
26 changed files with 2806 additions and 202 deletions
+100 -5
View File
@@ -4,7 +4,7 @@
use horizon_client::camera::CameraFluid;
use horizon_client::gfx::pack_uniforms::PackInputs;
use horizon_shaders::{Macros, Pack, Properties, dimension_folder, load_post};
use horizon_shaders::{BlockIds, Macros, Pack, Properties, dimension_folder, load_post};
use super::{Dim, Game};
@@ -42,9 +42,23 @@ impl Game<'_> {
);
}
let folder = dimension_folder(&pack, dimension);
let terrain = renderer.pack_terrain_inputs();
let post = load_post(&pack, &folder, &properties, &macros, terrain.as_ref());
if let Some((programs, notes)) = renderer.set_shader_pack(dimension, Some(post))
let inputs = renderer.pack_inputs();
let post = load_post(&pack, &folder, &properties, &macros, &inputs);
let text = pack.read_text("block.properties").unwrap_or_default();
let ids = BlockIds::parse(&Properties::parse(&text, &macros));
for note in &ids.notes {
log::warn!("shader pack {name}: block.properties: {note}");
}
let started_ids = std::time::Instant::now();
let table = block_id_table(&self.pack, &ids);
log::info!(
"shader pack {name}: mc_Entity for {} of {} block sprites in {} ms",
table.chunks(2).filter(|p| p[0] != -1).count(),
table.len() / 2,
started_ids.elapsed().as_millis()
);
if let Some((programs, notes)) =
renderer.set_shader_pack(dimension, Some(post), &table)
{
for note in notes {
log::warn!("shader pack {name}: {note}");
@@ -59,7 +73,7 @@ impl Game<'_> {
}
Err(e) => {
log::warn!("shader pack {name}: {e}");
renderer.set_shader_pack(dimension, None);
renderer.set_shader_pack(dimension, None, &[]);
}
}
}
@@ -83,3 +97,84 @@ impl Game<'_> {
}
}
}
/// `mc_Entity` (x, y) of each block sprite layer, as (id, fluid) pairs: terrain vertices carry
/// their sprite layer, not their block. A layer takes the id of the block named like its sprite
/// (`block/oak_leaves` for `oak_leaves`), else the id most blocks drawing it share (ties: the
/// lowest); -1 when no block drawing it has one. y is 1 for the fluid sprites, -1 otherwise.
fn block_id_table(pack: &super::PackResources, ids: &BlockIds) -> Vec<i32> {
use std::collections::{BTreeMap, BTreeSet};
let layers = pack
.render
.sprite_layers
.values()
.max()
.map_or(0, |l| l + 1) as usize;
let mut table = vec![-1; layers * 2];
if ids.is_empty() {
return table;
}
let registry = pack.assets.registry;
let catalog = &pack.render.model_catalog;
let sprite = |name: &str| pack.render.sprite_layers.get(name).copied();
// (layer, id) -> (a block named like the sprite, the blocks).
let mut votes: BTreeMap<(u32, i32), (bool, BTreeSet<&str>)> = BTreeMap::new();
for i in 0..registry.len() {
let state_id = horizon_world::registry::BlockStateId(i as u32);
let Some(state) = registry.state(state_id) else {
continue;
};
let Some(id) = ids.id(&state.name, |k| state.properties.get(k).map(String::as_str)) else {
continue;
};
let block = state.name.strip_prefix("minecraft:").unwrap_or(&state.name);
let mut vote = |layer: u32| {
let named = pack
.layer_names
.get(&layer)
.and_then(|n| n.strip_prefix("block/"))
== Some(block);
let v = votes.entry((layer, id)).or_default();
v.0 |= named;
v.1.insert(&state.name);
};
// Fluids draw from their own sprites.
let fluid = match block {
"water" => ["water_still", "water_flow"],
"lava" => ["lava_still", "lava_flow"],
_ => ["", ""],
};
for f in fluid.iter().filter(|f| !f.is_empty()) {
if let Some(l) = sprite(&format!("minecraft:block/{f}")) {
vote(l);
}
}
let origin = horizon_core::position::BlockPos::new(0, 0, 0);
for (_, model) in catalog.collect(state_id, origin).unwrap_or_default() {
for face in &model.faces {
vote(face.layer);
}
}
}
let mut best: BTreeMap<u32, (bool, usize, i32)> = BTreeMap::new();
for ((layer, id), (named, blocks)) in votes {
let candidate = (named, blocks.len(), -id);
let b = best.entry(layer).or_insert(candidate);
if candidate > *b {
*b = candidate;
}
}
for (layer, (_, _, id)) in best {
if let Some(slot) = table.get_mut(layer as usize * 2) {
*slot = -id;
}
}
for f in ["water_still", "water_flow", "lava_still", "lava_flow"] {
if let Some(l) = sprite(&format!("minecraft:block/{f}"))
&& let Some(slot) = table.get_mut(l as usize * 2 + 1)
{
*slot = 1;
}
}
table
}
+112 -32
View File
@@ -69,7 +69,10 @@ pub mod lightning;
mod lod;
mod occlusion;
mod pack_atlas;
mod pack_draw;
mod pack_post;
mod pack_sky;
mod pack_timing;
pub mod pack_uniforms;
mod page_runs;
pub mod panorama;
@@ -86,6 +89,19 @@ const COMPLETE_COLUMN: u32 = (1 << (crate::chunk::HEIGHT / 16)) - 1;
/// its fixed-point UVs (`terrain.wgsl`'s `terrain_uv`).
/// The world pass again after occlusion culling's test: it loads both
/// targets (phase 2 draws over phase 1, reading the test's results).
/// LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks).
fn sky_open(frame: &Frame) -> bool {
match frame.fog {
Some(f) => f.sky_end > 2.0,
None => !frame.underwater,
}
}
/// The Overworld-style sky (disc, sunset, stars, void) draws this frame.
fn sky_visible(frame: &Frame) -> bool {
!frame.title && frame.skybox && sky_open(frame)
}
fn world_pass_after_culling<'e>(
encoder: &'e mut wgpu::CommandEncoder,
view: &wgpu::TextureView,
@@ -844,12 +860,17 @@ async fn open_device(
continue;
}
// Mappable primary buffers: section pages that no longer fit in
// video memory go to system memory.
// video memory go to system memory. Shader packs' 16-bit normalized buffers (render
// targets with the adapter's own format features) and R11F_G11F_B10F: a float
// stand-in neither clamps nor drops NaN.
let features = timing::GpuTimer::features(&adapter)
| cull::Cull::features(&adapter)
| (adapter.features()
& (wgpu::Features::INDIRECT_FIRST_INSTANCE
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS));
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS
| wgpu::Features::TEXTURE_FORMAT_16BIT_NORM
| wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
| wgpu::Features::RG11B10UFLOAT_RENDERABLE));
let driver = format!("{} {}", info.driver, info.driver_info);
startup_step(format_args!(
"requesting the device (driver {}) with features [{features}] and the adapter's \
@@ -2151,13 +2172,16 @@ impl Renderer {
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let flat_wanted = flat::wanted(&adapter, &device);
// Readable as storage where flat draws run: a shader pack's terrain program reads them.
let arena = arena::Arena::new(
&device,
std::mem::size_of::<TerrainVertex>() as u64,
1 << 20,
flat_wanted,
);
// Sections as one index list per frame where multi-draw is emulated.
let flat = flat::wanted(&adapter, &device).then(|| {
let flat = flat_wanted.then(|| {
let buffers = [Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<TerrainVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
@@ -2796,12 +2820,14 @@ impl Renderer {
self.world_post.scale = scale.clamp(0.25, 2.0);
self.world_post.antialias = antialias;
}
/// Runs `post` over the world from now on (`None`: no pack), for the dimension `dimension`.
/// Runs `post` over the world from now on (`None`: no pack), for the dimension `dimension`;
/// `block_ids` gives each block sprite layer's `mc_Entity` (id, fluid) pair.
/// Returns the programs that run and the notes of loading them.
pub fn set_shader_pack(
&mut self,
dimension: i32,
pack: Option<horizon_shaders::Post>,
block_ids: &[i32],
) -> Option<(Vec<String>, Vec<String>)> {
if pack.is_none() {
self.pack_atlas = None;
@@ -2826,7 +2852,17 @@ impl Renderer {
terrain: self.pack_atlas.as_ref().map(|_| pack_post::Geometry {
buffers: if flat { &buffers[..1] } else { &buffers },
table: self.flat.as_ref().filter(|_| flat).map(|f| &f.draw_layout),
depth_write: true,
atlas: None,
ids: None,
cull: true,
}),
block_ids,
celestial: self
.hud
.atlas_texture
.as_ref()
.map(|t| t.create_view(&Default::default())),
};
pack_post::PackPost::new(
&self.device,
@@ -2843,9 +2879,17 @@ impl Renderer {
self.pack_post = Some((dimension, post));
report
}
/// What a shader pack's terrain program reads from Horizon's terrain vertices, in the
/// pack's block atlas (made here when missing); `None` when the atlas does not fit.
pub fn pack_terrain_inputs(&mut self) -> Option<horizon_shaders::GbuffersInputs> {
/// What a shader pack's gbuffers programs read from Horizon's geometry: the sky's, and
/// terrain's in the pack's block atlas (made here when missing; none when it does not fit).
pub fn pack_inputs(&mut self) -> horizon_shaders::GameInputs {
horizon_shaders::GameInputs {
terrain: self.pack_terrain_inputs(),
sky: Some(pack_sky::inputs()),
celestial: Some(pack_sky::celestial_inputs()),
}
}
fn pack_terrain_inputs(&mut self) -> Option<horizon_shaders::GbuffersInputs> {
if self.pack_atlas.is_none() {
let mut encoder = self.device.create_command_encoder(&Default::default());
let layers = self
@@ -3764,6 +3808,24 @@ impl Renderer {
let pack_post = !frame.title && self.pack_post.as_ref().is_some_and(|p| p.1.is_some());
// The pack's program reads the vertices this frame's draws bind.
let pack_draws_terrain = pack_terrain && flat_frame == self.pack_terrain_flat;
let pack_draws_sky = pack_post
&& self
.pack_post
.as_ref()
.and_then(|p| p.1.as_ref())
.is_some_and(|p| p.has_sky());
let pack_draws_celestial = pack_post
&& self
.pack_post
.as_ref()
.and_then(|p| p.1.as_ref())
.is_some_and(|p| p.has_celestial());
let pack_draws_water = pack_draws_terrain
&& self
.pack_post
.as_ref()
.and_then(|p| p.1.as_ref())
.is_some_and(|p| p.has_water());
let scaled = self.world_post.prepare(
&self.device,
[self.config.width, self.config.height],
@@ -3817,13 +3879,9 @@ impl Renderer {
..Default::default()
});
pass.set_bind_group(0, &self.group, &[]);
// LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks).
let sky_visible = match frame.fog {
Some(f) => f.sky_end > 2.0,
None => !frame.underwater,
};
let sky_visible = sky_open(frame);
if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) {
if !frame.title && frame.skybox {
if !frame.title && frame.skybox && !pack_draws_sky {
pass.set_pipeline(&self.sky);
pass.draw(0..3, 0..1);
}
@@ -3837,17 +3895,17 @@ impl Renderer {
if frame.end_sky {
self.end_sky.draw(&mut pass);
}
if celestial_vertices > 0 {
if celestial_vertices > 0 && !pack_draws_celestial {
pass.set_vertex_buffer(0, self.celestial_buffer.slice(..));
pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1);
}
pass.set_bind_group(0, &self.group, &[]);
}
if !frame.title && frame.stars.is_some() {
if !frame.title && frame.stars.is_some() && !pack_draws_sky {
self.stars.draw(&mut pass);
pass.set_bind_group(0, &self.group, &[]);
}
if !frame.title && frame.dark_disc {
if !frame.title && frame.dark_disc && !pack_draws_sky {
pass.set_pipeline(&self.dark_disc);
pass.draw(0..3, 0..1);
}
@@ -3995,6 +4053,8 @@ impl Renderer {
pass.draw(0..4, debug_depth..debug_depth + debug_top);
}
match self.flat.as_ref().filter(|_| flat_frame) {
// The pack draws translucent terrain after its deferred programs.
_ if pack_draws_water => {}
Some(flat) => {
pass.set_pipeline(&flat.translucent);
flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| {
@@ -4087,23 +4147,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<'_>| {
if !pack_draws_terrain {
return;
}
match flat {
Some(flat) => {
flat.draw(rp, &flat.calls[..flat.solid_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(..));
self.draw_sections(rp, &self.indirect, 0, 0, solid_draws);
}
}
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,
@@ -4115,6 +4194,7 @@ impl Renderer {
&frame.pack,
size,
[self.config.width, self.config.height],
&pages,
&mut terrain,
);
self.pack_post = Some((dimension, Some(post)));
+16 -4
View File
@@ -65,8 +65,15 @@ pub struct Arena {
}
impl Arena {
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self {
Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX)
/// Vertices; `storage` also lets shaders read them as a storage buffer (a shader pack's
/// terrain program reads the other corners of a vertex's quad for its normal).
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64, storage: bool) -> Self {
let usage = if storage {
wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::STORAGE
} else {
wgpu::BufferUsages::VERTEX
};
Self::with_usage(device, stride, capacity, usage)
}
/// Sorted translucent indices; `storage` when compute passes read them.
pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self {
@@ -148,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()
@@ -352,7 +364,7 @@ mod tests {
eprintln!("no GPU adapter: skipped");
return;
};
let mut arena = Arena::new(&device, 4, GRAIN);
let mut arena = Arena::new(&device, 4, GRAIN, false);
arena.page_limit = 2 * GRAIN;
assert_eq!(arena.bytes(), 0);
let (first, a) = alloc(&mut arena, &device, &queue, GRAIN).unwrap();
@@ -395,7 +407,7 @@ mod tests {
return;
};
for mut arena in [
Arena::new(&device, 28, GRAIN),
Arena::new(&device, 28, GRAIN, false),
Arena::indices(&device, GRAIN, false),
] {
alloc(&mut arena, &device, &queue, GRAIN).unwrap();
+12
View File
@@ -651,10 +651,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);
}
}
+45 -4
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,6 +151,12 @@ 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),
// 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 = 1) readonly buffer HzVertices { uint hz_vertices[]; };\n",
);
"hz_slot_origins[hz_block_slots[uint(gl_VertexIndex) >> 8u]]"
} else {
declarations.push_str("layout(location = 5) in vec4 hz_v_origin;\n");
@@ -149,17 +179,27 @@ 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 {
"vec4(-1.0, -1.0, 0.0, 0.0)"
};
let attributes = [
("mc_Entity", "vec4(-1.0, -1.0, 0.0, 0.0)"),
("mc_Entity", entity),
(
"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"),
@@ -173,6 +213,7 @@ impl PackAtlas {
.iter()
.map(|&(n, v)| (n.to_owned(), v.to_owned()))
.collect(),
after: String::new(),
}
}
}
@@ -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)]);
}
}
File diff suppressed because it is too large Load Diff
@@ -53,3 +53,11 @@ fn vs_uv(@builtin(vertex_index) i: u32) -> Full {
fn fs_copy(v: Full) -> @location(0) vec4<f32> {
return textureSample(source, linear, v.uv);
}
// One level of a buffer's mip chain from the level above (6.1.7): the average of the 2×2
// texels under each destination texel, by one bilinear sample at their shared corner.
@fragment
fn fs_down(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {
let size = max(textureDimensions(source) / 2u, vec2<u32>(1u));
return textureSampleLevel(source, linear, p.xy / vec2<f32>(size), 0.0);
}
+319
View File
@@ -0,0 +1,319 @@
//! The vanilla sky's geometry for a shader pack's `gbuffers_skybasic` (spec 2.3): the sky disc,
//! the sunset fan, the stars and the void disc, as Horizon's own sky draws them (terrain.wgsl,
//! stars.rs), built once into a vertex buffer. The frame's colours and rotations sit in a small
//! uniform (set 1) that the vertex inputs read. `gbuffers_skytextured` draws the frame's sun and
//! moon quads, textured from the shared atlas.
use std::ops::Range;
use wgpu::util::DeviceExt;
/// A sky vertex: a position and what it belongs to (`SKY`...).
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
pos: [f32; 3],
kind: u32,
}
const SKY: u32 = 0;
const SUNSET_APEX: u32 = 1;
/// Rim of the sunset fan: `pos.xy` is (sin, cos) of its angle.
const SUNSET_RIM: u32 = 2;
const STAR: u32 = 3;
const VOID: u32 = 4;
/// The frame's sky (std140).
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Uniform {
/// Camera-relative world from star space.
stars: [[f32; 4]; 4],
/// Sky colour, alpha 1.
color: [f32; 4],
/// Sunset colour and alpha.
sunrise: [f32; 4],
/// cos and sin of the sunset fan's turn, star brightness.
sun: [f32; 4],
}
/// A sun or moon vertex: position, atlas UV, RGBA8 colour.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Celestial {
pos: [f32; 3],
uv: [f32; 2],
color: u32,
}
/// Quads of the sun and moon (and room to spare).
const CELESTIAL_QUADS: usize = 4;
const CELESTIAL_ATTRIBUTES: [wgpu::VertexAttribute; 3] =
wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Unorm8x4];
pub(super) const ATTRIBUTES: [wgpu::VertexAttribute; 2] =
wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint32];
/// What `gbuffers_skybasic` reads from these vertices.
pub fn inputs() -> horizon_shaders::GbuffersInputs {
let declarations =
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in uint hz_v_kind;\n\
layout(set = 1, binding = 0) uniform HzSky { mat4 hz_sky_stars; vec4 hz_sky_color; \
vec4 hz_sky_sunrise; vec4 hz_sky_sun; };\n"
.to_owned();
let body = format!(
" vec3 hz_p = hz_v_pos;\n \
hz_Color = hz_sky_color;\n \
if (hz_v_kind == {SUNSET_APEX}u || hz_v_kind == {SUNSET_RIM}u) {{\n \
vec3 hz_l = vec3(0.0, 100.0, 0.0);\n \
hz_Color = hz_sky_sunrise;\n \
if (hz_v_kind == {SUNSET_RIM}u) {{\n \
hz_l = vec3(hz_v_pos.xy * 120.0, -hz_v_pos.y * 40.0 * hz_sky_sunrise.a);\n \
hz_Color.a = 0.0;\n \
}}\n \
vec3 hz_r = vec3(hz_l.x * hz_sky_sun.x - hz_l.y * hz_sky_sun.y, hz_l.x * hz_sky_sun.y + hz_l.y * hz_sky_sun.x, hz_l.z);\n \
hz_p = vec3(hz_r.x, -hz_r.z, hz_r.y);\n \
}} else if (hz_v_kind == {STAR}u) {{\n \
hz_p = (hz_sky_stars * vec4(hz_v_pos, 1.0)).xyz;\n \
hz_Color = vec4(hz_sky_sun.z);\n \
}} else if (hz_v_kind == {VOID}u) {{\n \
hz_Color = vec4(0.0, 0.0, 0.0, 1.0);\n \
}}\n \
hz_Vertex = vec4(hz_p, 1.0);\n \
hz_MultiTexCoord0 = vec4(0.0, 0.0, 0.0, 1.0);\n \
hz_MultiTexCoord1 = vec4(0.0, 240.0, 0.0, 1.0);\n \
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
hz_Normal = vec3(0.0, 1.0, 0.0);\n"
);
horizon_shaders::GbuffersInputs {
declarations,
body,
attributes: vec![
("vaPosition".into(), "hz_Vertex.xyz".into()),
("vaColor".into(), "hz_Color".into()),
("vaNormal".into(), "hz_Normal".into()),
],
// 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(),
}
}
/// What `gbuffers_skytextured` reads from the sun and moon's vertices.
pub fn celestial_inputs() -> horizon_shaders::GbuffersInputs {
horizon_shaders::GbuffersInputs {
declarations:
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\
layout(location = 2) in vec4 hz_v_color;\n"
.into(),
body: " hz_Vertex = vec4(hz_v_pos, 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_v_color;\n \
hz_Normal = vec3(0.0, 0.0, 1.0);\n"
.into(),
attributes: vec![
("vaPosition".into(), "hz_Vertex.xyz".into()),
("vaUV0".into(), "hz_v_uv".into()),
("vaColor".into(), "hz_Color".into()),
("vaNormal".into(), "hz_Normal".into()),
],
after: " gl_Position.z = gl_Position.w;\n".into(),
}
}
/// One draw of the sky: its render stage, whether `gbuffers_skytextured` draws it, its vertices.
pub(super) struct Part {
pub stage: &'static str,
pub textured: bool,
pub range: Range<u32>,
}
/// A disc fan at height `y`, radius 512, as triangles (SkyRenderer's sky and void discs).
fn disc(y: f32, kind: u32, out: &mut Vec<Vertex>) {
let sign = y.signum();
let rim = |i: i32| {
let a = (i as f32).to_radians();
Vertex {
pos: [sign * 512.0 * a.cos(), y, 512.0 * a.sin()],
kind,
}
};
let centre = Vertex {
pos: [0.0, y, 0.0],
kind,
};
for i in (-180..180).step_by(45) {
out.extend([centre, rim(i), rim(i + 45)]);
}
}
pub(super) struct PackSky {
vertices: wgpu::Buffer,
celestial: wgpu::Buffer,
uniform: wgpu::Buffer,
pub layout: wgpu::BindGroupLayout,
group: wgpu::BindGroup,
/// Vertex ranges of the sky disc, the sunset fan, the stars and the void.
ranges: [Range<u32>; 4],
}
impl PackSky {
pub fn new(device: &wgpu::Device) -> Self {
let mut v = Vec::new();
disc(16.0, SKY, &mut v);
let sky = 0..v.len() as u32;
let apex = Vertex {
pos: [0.0; 3],
kind: SUNSET_APEX,
};
let rim = |i: u32| {
let a = i as f32 * std::f32::consts::TAU / 16.0;
Vertex {
pos: [a.sin(), a.cos(), 0.0],
kind: SUNSET_RIM,
}
};
for i in 0..16 {
v.extend([apex, rim(i), rim(i + 1)]);
}
let sunset = sky.end..v.len() as u32;
v.extend(
super::stars::star_triangles()
.into_iter()
.map(|pos| Vertex { pos, kind: STAR }),
);
let stars = sunset.end..v.len() as u32;
disc(-4.0, VOID, &mut v);
let void = stars.end..v.len() as u32;
let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Shader pack sky"),
contents: bytemuck::cast_slice(&v),
usage: wgpu::BufferUsages::VERTEX,
});
let celestial = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack sun and moon"),
size: (std::mem::size_of::<Celestial>() * 6 * CELESTIAL_QUADS) as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack sky"),
size: std::mem::size_of::<Uniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Shader pack sky"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Shader pack sky"),
layout: &layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
}],
});
Self {
vertices,
celestial,
uniform,
layout,
group,
ranges: [sky, sunset, stars, void],
}
}
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,
})]
}
pub fn celestial_buffers() -> [Option<wgpu::VertexBufferLayout<'static>>; 1] {
[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Celestial>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &CELESTIAL_ATTRIBUTES,
})]
}
/// Writes the frame's sky and returns its draws in vanilla's order: the disc, the sunset
/// fan while the sun is near the horizon, the sun and the moon, the stars and, with the
/// camera low, the void.
pub fn prepare(&self, queue: &wgpu::Queue, frame: &super::Frame) -> Vec<Part> {
let sun_angle = frame.sky.sun_angle.to_radians();
// The fan turns to the other horizon in the afternoon (terrain.wgsl's sunrise_weight).
let flip = if sun_angle.sin() < 0.0 { 180f32 } else { 0.0 };
let theta = (flip + 90.0).to_radians();
let (rotation, brightness) = frame.stars.unwrap_or_default();
let [r, g, b] = frame.sky.sky_color;
let uniform = Uniform {
stars: rotation.to_cols_array_2d(),
color: [r, g, b, 1.0],
sunrise: frame.sky.sunrise_color,
sun: [theta.cos(), theta.sin(), brightness.clamp(0.0, 1.0), 0.0],
};
queue.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniform));
// The sun's quad, then the moon's (Game::celestial_geometry), as triangles.
let quads = frame
.celestial
.as_chunks::<4>()
.0
.iter()
.take(CELESTIAL_QUADS);
let triangles: Vec<Celestial> = quads
.clone()
.flat_map(|q| [0, 1, 2, 0, 2, 3].map(|i| q[i]))
.map(|v| Celestial {
pos: v.pos,
uv: v.uv,
color: v.color,
})
.collect();
queue.write_buffer(&self.celestial, 0, bytemuck::cast_slice(&triangles));
let [sky, sunset, stars, void] = self.ranges.clone();
let part = |stage, textured, range| Part {
stage,
textured,
range,
};
let mut parts = vec![part("SKY", false, sky)];
if frame.sky.sunrise_color[3] > 0.001 {
parts.push(part("SUNSET", false, sunset));
}
for (i, stage) in ["SUN", "MOON"].into_iter().enumerate().take(quads.len()) {
parts.push(part(stage, true, i as u32 * 6..i as u32 * 6 + 6));
}
if frame.stars.is_some() {
parts.push(part("STARS", false, stars));
}
if frame.dark_disc {
parts.push(part("VOID", false, void));
}
parts
}
/// Binds the vertices of the `textured` (sun and moon) or other parts.
pub fn bind(&self, pass: &mut wgpu::RenderPass<'_>, textured: bool) {
if textured {
pass.set_vertex_buffer(0, self.celestial.slice(..));
} else {
pass.set_bind_group(1, &self.group, &[]);
pass.set_vertex_buffer(0, self.vertices.slice(..));
}
}
}
@@ -0,0 +1,147 @@
//! Developers' aid: `HORIZON_SHADER_PACK_TIMING=1` times every pass of a shader pack on the
//! GPU, one frame in `EVERY`, and logs each pass's median every `REPORT` timed frames. The
//! frame after a timed one waits for the GPU before reading the timestamps (Metal resolves
//! them without waiting for the passes that write them), so timing slows the game.
const EVERY: u32 = 30;
const REPORT: usize = 30;
/// Passes timed per frame at most (two timestamps each).
const CAPACITY: u32 = 64;
pub(super) struct PassTiming {
queries: wgpu::QuerySet,
resolve: wgpu::Buffer,
read: wgpu::Buffer,
period_ns: f32,
frame: u32,
/// The passes timed in the frame being recorded or waiting to be read, in order.
names: Vec<String>,
timed: bool,
samples: Vec<(String, Vec<f32>)>,
reports: usize,
}
impl PassTiming {
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Self> {
if std::env::var_os("HORIZON_SHADER_PACK_TIMING").is_none()
|| !device.features().contains(wgpu::Features::TIMESTAMP_QUERY)
{
return None;
}
let size = u64::from(CAPACITY) * 2 * 8;
let buffer = |label, usage| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size,
usage,
mapped_at_creation: false,
})
};
Some(Self {
queries: device.create_query_set(&wgpu::QuerySetDescriptor {
label: Some("Shader pack pass timing"),
ty: wgpu::QueryType::Timestamp,
count: CAPACITY * 2,
}),
resolve: buffer(
"Shader pack timing resolve",
wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
),
read: buffer(
"Shader pack timing read",
wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
),
period_ns: queue.get_timestamp_period(),
frame: 0,
names: Vec::new(),
timed: false,
samples: Vec::new(),
reports: 0,
})
}
/// At the start of a frame: reads the last timed frame's passes, and decides whether this
/// one is timed.
pub fn begin(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
if self.timed && !self.names.is_empty() {
self.collect(device, queue);
}
self.names.clear();
self.frame += 1;
self.timed = self.frame.is_multiple_of(EVERY);
}
/// Timestamp writes for the pass `name`, in a timed frame.
pub fn writes(&mut self, name: &str) -> Option<wgpu::RenderPassTimestampWrites<'_>> {
let i = self.names.len() as u32;
if !self.timed || i >= CAPACITY {
return None;
}
self.names.push(name.to_owned());
Some(wgpu::RenderPassTimestampWrites {
query_set: &self.queries,
beginning_of_pass_write_index: Some(2 * i),
end_of_pass_write_index: Some(2 * i + 1),
})
}
fn collect(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
// The timed frame first, then the resolve, so every timestamp is written.
_ = device.poll(wgpu::PollType::wait_indefinitely());
let count = self.names.len() as u32 * 2;
let bytes = u64::from(count) * 8;
let mut encoder = device.create_command_encoder(&Default::default());
encoder.resolve_query_set(&self.queries, 0..count, &self.resolve, 0);
encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, bytes);
queue.submit([encoder.finish()]);
let slice = self.read.slice(..bytes);
slice.map_async(wgpu::MapMode::Read, |_| {});
_ = device.poll(wgpu::PollType::wait_indefinitely());
let Ok(data) = slice.get_mapped_range() else {
return;
};
let stamps: Vec<u64> = data
.as_chunks::<8>()
.0
.iter()
.map(|b| u64::from_le_bytes(*b))
.collect();
drop(data);
self.read.unmap();
// Passes overlap on tiled GPUs (a pass begins before the one before it ends): a pass
// costs the time from the later of its beginning and the previous pass's end.
let mut previous_end = 0;
for (name, pair) in self.names.iter().zip(stamps.as_chunks::<2>().0) {
if pair[0] == 0 || pair[1] < pair[0] {
continue;
}
let from = pair[0].max(previous_end).min(pair[1]);
previous_end = pair[1];
let ms = (pair[1] - from) as f32 * self.period_ns / 1e6;
match self.samples.iter_mut().find(|s| s.0 == *name) {
Some(s) => s.1.push(ms),
None => self.samples.push((name.clone(), vec![ms])),
}
}
self.reports += 1;
if self.reports.is_multiple_of(REPORT) {
self.report();
}
}
fn report(&mut self) {
let mut total = 0.0;
let mut parts = Vec::new();
for (name, v) in &mut self.samples {
v.sort_by(f32::total_cmp);
let median = v[v.len() / 2];
total += median;
parts.push(format!("{name} {median:.3}"));
v.clear();
}
log::info!(
"shader pack GPU time per pass (median ms of {REPORT} frames): {} = {total:.3}",
parts.join(", ")
);
}
}
@@ -141,6 +141,10 @@ pub const NAMES: &[&str] = &[
"gbufferPreviousModelView",
"gbufferPreviousProjection",
"atlasSize",
"shadowModelView",
"shadowModelViewInverse",
"shadowProjection",
"shadowProjectionInverse",
];
/// Values carried from frame to frame.
@@ -226,6 +230,14 @@ impl FrameUniforms {
),
None => (frame.sky.fog_color, frame.distance * 0.9, frame.distance),
};
// The shadow camera (OQ-6, impl-plan.md): orthographic, `shadowDistance` (160) blocks
// each side, 100 blocks from the player toward the shadow light, world +z up.
let light = view
.inverse()
.transform_vector3(if day { sun } else { moon })
.normalize();
let shadow_view = Mat4::look_at_rh(light * 100.0, Vec3::ZERO, Vec3::Z);
let shadow_projection = Mat4::orthographic_rh_gl(-160.0, 160.0, -160.0, 160.0, 0.05, 256.0);
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;
@@ -247,6 +259,10 @@ impl FrameUniforms {
"worldDay" => Value::i(&[world_day as i32]),
"moonPhase" => Value::i(&[world_day.rem_euclid(8) as i32]),
"frameCounter" => Value::i(&[self.frame as i32]),
"shadowModelView" => m4(shadow_view),
"shadowModelViewInverse" => m4(shadow_view.inverse()),
"shadowProjection" => m4(shadow_projection),
"shadowProjectionInverse" => m4(shadow_projection.inverse()),
"atlasSize" => Value::i(&[self.atlas[0] as i32, self.atlas[1] as i32]),
"frameTime" => Value::f(&[dt]),
"frameTimeCounter" => Value::f(&[seconds]),
@@ -304,6 +320,47 @@ impl FrameUniforms {
}
}
impl FrameUniforms {
/// Evaluates the pack's custom uniforms with this frame's values and puts them after
/// `NAMES`' values, in `custom.uniforms()` order.
pub fn eval_custom(&mut self, custom: &mut horizon_shaders::Custom) {
self.values.truncate(NAMES.len());
let values = &self.values;
let builtin = |name: &str| {
let v = values.get(index(name)?)?;
let n = components(name);
Some(match *v {
Value::F(f) => horizon_shaders::Val::vector(&f.map(f64::from)[..n]),
Value::I(i) => horizon_shaders::Val::vector(&i.map(f64::from)[..n.min(3)]),
})
};
let dt = match index("frameTime").and_then(|i| values.get(i)) {
Some(Value::F(f)) => f64::from(f[0]),
_ => 0.0,
};
let out = custom.eval(dt, &builtin);
self.values
.extend(out.iter().map(|v| Value::f(&v.v.map(|x| x as f32)[..v.n])));
}
}
/// How many components the uniform `name` has (16 for a matrix).
fn components(name: &str) -> usize {
match name {
"cameraPosition"
| "previousCameraPosition"
| "upPosition"
| "sunPosition"
| "moonPosition"
| "shadowLightPosition"
| "fogColor"
| "skyColor" => 3,
"eyeBrightness" | "eyeBrightnessSmooth" | "atlasSize" => 2,
n if n.starts_with("gbuffer") || n.starts_with("shadow") && n != "shadowAngle" => 16,
_ => 1,
}
}
/// The position of `name` in [`NAMES`].
pub fn index(name: &str) -> Option<usize> {
NAMES.iter().position(|n| *n == name)
+120
View File
@@ -0,0 +1,120 @@
//! `block.properties` (spec 4.1): `block.<id>=<block> <block> ...`, each block
//! `[namespace:]name` with optional state filters `:<property>=<v1>,<v2>`. Values in one filter
//! are alternatives; separate filters must all match. Names the game does not know are simply
//! never asked for. Block tags (`%tag`, tier E) are not read yet.
use crate::Properties;
#[derive(Clone, Debug, PartialEq)]
struct Rule {
id: i32,
/// `minecraft:stone`.
name: String,
filters: Vec<(String, Vec<String>)>,
}
/// The ids `block.properties` gives block states.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BlockIds {
rules: Vec<Rule>,
/// Lines skipped and why.
pub notes: Vec<String>,
}
impl BlockIds {
pub fn parse(properties: &Properties) -> Self {
let mut out = Self::default();
for e in &properties.entries {
let Some(id) = e.key.strip_prefix("block.") else {
continue;
};
let Ok(id) = id.parse::<i32>() else {
// `layer.*` (4.2) and other keys are not ids.
continue;
};
for word in e.value.split_whitespace() {
if word.starts_with('%') {
out.notes.push(format!(
"line {}: block tags are not read yet: {word}",
e.line
));
continue;
}
let (names, filters): (Vec<&str>, Vec<&str>) =
word.split(':').partition(|p| !p.contains('='));
let name = match names[..] {
[name] => format!("minecraft:{name}"),
[namespace, name] => format!("{namespace}:{name}"),
_ => {
out.notes
.push(format!("line {}: not a block name: {word}", e.line));
continue;
}
};
let filters = filters
.iter()
.filter_map(|f| f.split_once('='))
.map(|(k, v)| (k.to_owned(), v.split(',').map(str::to_owned).collect()))
.collect();
out.rules.push(Rule { id, name, filters });
}
}
out
}
/// The id of block `name` (`minecraft:stone`) in the state with `properties`. The rule with
/// the most filters that all match wins, then the first in the file (one name belongs to
/// one id; a filtered entry is the more specific one).
pub fn id<'a>(&self, name: &str, properties: impl Fn(&str) -> Option<&'a str>) -> Option<i32> {
self.rules
.iter()
.filter(|r| r.name == name)
.filter(|r| {
r.filters
.iter()
.all(|(k, vs)| properties(k).is_some_and(|v| vs.iter().any(|x| x == v)))
})
.min_by_key(|r| std::cmp::Reverse(r.filters.len()))
.map(|r| r.id)
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Macros;
#[test]
fn names_states_and_precedence() {
let text = "block.10=stone minecraft:dirt mod:thing \\\n grass_block:snowy=false\n\
block.11=grass_block\nblock.12=oak_leaves:persistent=true:distance=1,2 %leaves\n\
layer.translucent=glass\n";
let ids = BlockIds::parse(&Properties::parse(text, &Macros::standard()));
let none = |_: &str| None;
assert_eq!(ids.id("minecraft:stone", none), Some(10));
assert_eq!(ids.id("mod:thing", none), Some(10));
assert_eq!(ids.id("minecraft:glass", none), None);
let snowy = |s: &'static str| move |k: &str| (k == "snowy").then_some(s);
// The filtered entry is the more specific one.
assert_eq!(ids.id("minecraft:grass_block", snowy("false")), Some(10));
assert_eq!(ids.id("minecraft:grass_block", snowy("true")), Some(11));
let leaves = |p: &'static str, d: &'static str| {
move |k: &str| match k {
"persistent" => Some(p),
"distance" => Some(d),
_ => None,
}
};
assert_eq!(
ids.id("minecraft:oak_leaves", leaves("true", "2")),
Some(12)
);
assert_eq!(ids.id("minecraft:oak_leaves", leaves("true", "3")), None);
assert_eq!(ids.id("minecraft:oak_leaves", leaves("false", "1")), None);
assert_eq!(ids.notes.len(), 1, "{:?}", ids.notes);
}
}
+570
View File
@@ -0,0 +1,570 @@
//! Custom uniforms and variables of `shaders.properties` (spec 3.4): `uniform.<type>.<name>` and
//! `variable.<type>.<name>` expressions, parsed once and evaluated on the CPU every frame in
//! file order. Uniforms reach every program; variables only later expressions.
//!
//! Decisions (impl-plan.md):
//! - OQ-25: numbers are doubles; booleans are 1 and 0; `%` is C's remainder (`fmod` floors);
//! comparisons and logic read the first component; a value takes its declared type at the
//! end (`int` truncates toward zero, `bool` is "not zero"). Unknown names read 0 and are
//! reported once.
//! - OQ-26: `smooth` runs per frame with the frame time; its fade times are seconds (1 by
//! default) to cover half of the remaining distance, `fadeIn` while rising, `fadeOut` while
//! falling. Each call keeps its own state, so the optional id is not needed.
use std::collections::{HashMap, HashSet};
use crate::Properties;
/// A value: up to 16 components (matrices only as names, for `m.row.column`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Val {
pub v: [f64; 16],
/// Components: 1 for a scalar.
pub n: usize,
}
impl Val {
pub fn scalar(x: f64) -> Self {
let mut v = [0.0; 16];
v[0] = x;
Self { v, n: 1 }
}
pub fn vector(c: &[f64]) -> Self {
let mut v = [0.0; 16];
v[..c.len()].copy_from_slice(c);
Self { v, n: c.len() }
}
fn x(&self) -> f64 {
self.v[0]
}
fn truth(&self) -> bool {
self.v[0] != 0.0
}
/// `f` per component; a scalar operand stretches to the other's size.
fn zip(self, o: Val, f: impl Fn(f64, f64) -> f64) -> Val {
let n = self.n.max(o.n).min(4);
let at = |a: &Val, i: usize| if a.n == 1 { a.v[0] } else { a.v[i] };
let mut out = Val::scalar(0.0);
out.n = n;
for i in 0..n {
out.v[i] = f(at(&self, i), at(&o, i));
}
out
}
fn map(self, f: impl Fn(f64) -> f64) -> Val {
let mut out = self;
for i in 0..self.n.min(4) {
out.v[i] = f(self.v[i]);
}
out
}
}
#[derive(Clone, Debug)]
enum Expr {
Num(f64),
/// A name and its component (`x`, `2`, `2.1` as row 2, column 1).
Name(String, Option<(usize, Option<usize>)>),
Call(String, Vec<Expr>, usize),
Neg(Box<Expr>),
Not(Box<Expr>),
Bin(&'static str, Box<Expr>, Box<Expr>),
}
#[derive(Debug)]
struct Item {
name: String,
ty: String,
uniform: bool,
expr: Expr,
}
/// The pack's custom uniforms and variables, with the state `smooth` and `random` keep.
#[derive(Debug, Default)]
pub struct Custom {
items: Vec<Item>,
/// `smooth` state per call site.
smooth: HashMap<usize, f64>,
seed: u64,
unknown: HashSet<String>,
/// Expressions that did not parse, and unknown names, as `key: message`.
pub notes: Vec<String>,
calls: usize,
}
impl Custom {
/// Reads every `uniform.*` and `variable.*` key of `properties`, in file order.
pub fn parse(properties: &Properties) -> Self {
let mut out = Custom {
seed: 0x9e37_79b9_7f4a_7c15,
..Default::default()
};
for e in &properties.entries {
let (uniform, rest) = match e.key.split_once('.') {
Some(("uniform", r)) => (true, r),
Some(("variable", r)) => (false, r),
_ => continue,
};
let Some((ty, name)) = rest.split_once('.') else {
continue;
};
if !matches!(ty, "float" | "int" | "bool" | "vec2" | "vec3" | "vec4") {
out.notes
.push(format!("{}: type `{ty}` is not supported", e.key));
continue;
}
match Parser::new(&e.value, &mut out.calls).expr_all() {
Ok(expr) => out.items.push(Item {
name: name.to_owned(),
ty: ty.to_owned(),
uniform,
expr,
}),
Err(m) => out.notes.push(format!("{}: {m}", e.key)),
}
}
out
}
/// The uniforms' names and declared types, in file order.
pub fn uniforms(&self) -> impl Iterator<Item = (&str, &str)> {
self.items
.iter()
.filter(|i| i.uniform)
.map(|i| (i.name.as_str(), i.ty.as_str()))
}
/// Evaluates everything for a frame `dt` seconds after the last; `builtin` gives the
/// values of the game's uniforms and constants (`BIOME_*`...). Returns the uniforms'
/// values, in the order of `uniforms`.
pub fn eval(&mut self, dt: f64, builtin: &dyn Fn(&str) -> Option<Val>) -> Vec<Val> {
let mut vars: HashMap<String, Val> = HashMap::new();
let mut out = Vec::new();
let items = std::mem::take(&mut self.items);
for item in &items {
let v = self.value(&item.expr, dt, &vars, builtin);
let v = match item.ty.as_str() {
"int" => Val::scalar(v.x().trunc()),
"bool" => Val::scalar(f64::from(u8::from(v.truth()))),
"float" => Val::scalar(v.x()),
t => {
let n = (t.as_bytes()[3] - b'0') as usize;
let mut v = v;
if v.n == 1 {
let x = v.v[0];
v.v[1..n].fill(x);
}
v.n = n;
v
}
};
vars.insert(item.name.clone(), v);
if item.uniform {
out.push(v);
}
}
self.items = items;
out
}
fn random(&mut self) -> f64 {
self.seed ^= self.seed << 13;
self.seed ^= self.seed >> 7;
self.seed ^= self.seed << 17;
(self.seed >> 11) as f64 / (1u64 << 53) as f64
}
fn value(
&mut self,
e: &Expr,
dt: f64,
vars: &HashMap<String, Val>,
builtin: &dyn Fn(&str) -> Option<Val>,
) -> Val {
let ev = |e: &Expr, s: &mut Self| s.value(e, dt, vars, builtin);
match e {
Expr::Num(x) => Val::scalar(*x),
Expr::Name(name, component) => {
let v = match name.as_str() {
"pi" => Some(Val::scalar(std::f64::consts::PI)),
"true" => Some(Val::scalar(1.0)),
"false" => Some(Val::scalar(0.0)),
n => vars.get(n).copied().or_else(|| builtin(n)),
};
let Some(v) = v else {
if self.unknown.insert(name.clone()) {
self.notes.push(format!("`{name}` is unknown; it reads 0"));
}
return Val::scalar(0.0);
};
match component {
None => v,
// GLSL's m[column][row] is stored column after column.
Some((row, Some(column))) => Val::scalar(v.v[column * 4 + row]),
Some((i, None)) => Val::scalar(v.v[*i]),
}
}
Expr::Neg(a) => ev(a, self).map(|x| -x),
Expr::Not(a) => Val::scalar(f64::from(u8::from(!ev(a, self).truth()))),
Expr::Bin(op, a, b) => {
let (a, b) = (ev(a, self), ev(b, self));
let bool_ = |c: bool| Val::scalar(f64::from(u8::from(c)));
match *op {
"+" => a.zip(b, |x, y| x + y),
"-" => a.zip(b, |x, y| x - y),
"*" => a.zip(b, |x, y| x * y),
"/" => a.zip(b, |x, y| x / y),
"%" => a.zip(b, |x, y| x % y),
"<" => bool_(a.x() < b.x()),
"<=" => bool_(a.x() <= b.x()),
">" => bool_(a.x() > b.x()),
">=" => bool_(a.x() >= b.x()),
"==" => bool_(a.x() == b.x()),
"!=" => bool_(a.x() != b.x()),
"&&" => bool_(a.truth() && b.truth()),
_ => bool_(a.truth() || b.truth()),
}
}
Expr::Call(f, args, site) => {
let a: Vec<Val> = args.iter().map(|e| ev(e, self)).collect();
let arg = |i: usize| a.get(i).copied().unwrap_or(Val::scalar(0.0));
let x = arg(0).x();
let one = |g: fn(f64) -> f64| arg(0).map(g);
match f.as_str() {
"sin" => one(f64::sin),
"cos" => one(f64::cos),
"tan" => one(f64::tan),
"asin" => one(f64::asin),
"acos" => one(f64::acos),
"atan" if a.len() == 2 => Val::scalar(x.atan2(arg(1).x())),
"atan" => one(f64::atan),
"atan2" => Val::scalar(x.atan2(arg(1).x())),
"torad" | "radians" => one(f64::to_radians),
"todeg" | "degrees" => one(f64::to_degrees),
"min" => a
.iter()
.copied()
.reduce(|p, q| p.zip(q, f64::min))
.unwrap_or(arg(0)),
"max" => a
.iter()
.copied()
.reduce(|p, q| p.zip(q, f64::max))
.unwrap_or(arg(0)),
"clamp" => arg(0).zip(arg(1), f64::max).zip(arg(2), f64::min),
"abs" => one(f64::abs),
"floor" => one(f64::floor),
"ceil" => one(f64::ceil),
"exp" => one(f64::exp),
"exp2" => one(f64::exp2),
"exp10" => one(|v| 10f64.powf(v)),
"frac" => one(|v| v - v.floor()),
"log" if a.len() == 2 => Val::scalar(arg(1).x().log(x)),
"log" => one(f64::ln),
"log2" => one(f64::log2),
"log10" => one(f64::log10),
"sqrt" => one(f64::sqrt),
"round" => one(f64::round),
"signum" | "sign" => one(|v| if v == 0.0 { 0.0 } else { v.signum() }),
"pow" => arg(0).zip(arg(1), f64::powf),
"fmod" => arg(0).zip(arg(1), |p, q| p - q * (p / q).floor()),
"lerp" => arg(1).zip(arg(2), |p, q| p + (q - p) * x),
"mix" => arg(0).zip(arg(1), |p, q| p + (q - p) * arg(2).x()),
"edge" => Val::scalar(if arg(1).x() < x { 0.0 } else { 1.0 }),
"random" if a.len() == 2 => Val::scalar(x + (arg(1).x() - x) * self.random()),
"random" => Val::scalar(self.random()),
"randomInt" if a.len() == 2 => {
Val::scalar((x + (arg(1).x() - x) * self.random()).floor())
}
"randomInt" => Val::scalar((self.random() * f64::from(i32::MAX)).floor()),
"if" | "ifb" => {
let mut i = 0;
while i + 1 < a.len() {
if a[i].truth() {
return a[i + 1];
}
i += 2;
}
a.last().copied().unwrap_or(Val::scalar(0.0))
}
"smooth" => {
let (val, fade_in, fade_out) = match a.len() {
4 => (arg(1).x(), arg(2).x(), arg(3).x()),
3 => (x, arg(1).x(), arg(2).x()),
2 => (x, arg(1).x(), arg(1).x()),
_ => (x, 1.0, 1.0),
};
let state = self.smooth.entry(*site).or_insert(val);
let fade = if val > *state { fade_in } else { fade_out };
if fade > 0.0 {
*state = val + (*state - val) * 0.5f64.powf(dt / fade);
} else {
*state = val;
}
Val::scalar(*state)
}
"print" => arg(2),
"between" => {
Val::scalar(f64::from(u8::from(x >= arg(1).x() && x <= arg(2).x())))
}
"equals" => {
Val::scalar(f64::from(u8::from((x - arg(1).x()).abs() <= arg(2).x())))
}
"in" => Val::scalar(f64::from(u8::from(a[1..].iter().any(|v| v.x() == x)))),
"vec2" | "vec3" | "vec4" => {
let n = (f.as_bytes()[3] - b'0') as usize;
let mut c: Vec<f64> = a.iter().flat_map(|v| v.v[..v.n].to_vec()).collect();
if c.len() == 1 {
c = vec![c[0]; n];
}
c.resize(n, 0.0);
Val::vector(&c)
}
_ => {
if self.unknown.insert(f.clone()) {
self.notes.push(format!("`{f}()` is unknown; it gives 0"));
}
Val::scalar(0.0)
}
}
}
}
}
}
struct Parser<'a> {
tokens: Vec<String>,
at: usize,
calls: &'a mut usize,
}
const OPERATORS: [&str; 18] = [
"||", "&&", "==", "!=", "<=", ">=", "<", ">", "+", "-", "*", "/", "%", "!", "(", ")", ",", ".",
];
impl<'a> Parser<'a> {
fn new(text: &str, calls: &'a mut usize) -> Self {
let mut tokens = Vec::new();
let b = text.as_bytes();
let mut i = 0;
while i < b.len() {
let c = b[i] as char;
if c.is_whitespace() {
i += 1;
} else if c.is_ascii_digit()
|| (c == '.'
&& b.get(i + 1).is_some_and(u8::is_ascii_digit)
&& !tokens
.last()
.is_some_and(|t: &String| t == "." || is_name(t)))
{
let start = i;
while i < b.len()
&& (b[i].is_ascii_alphanumeric()
|| b[i] == b'.'
|| ((b[i] == b'-' || b[i] == b'+') && matches!(b[i - 1], b'e' | b'E')))
{
i += 1;
}
tokens.push(text[start..i].to_owned());
} else if c.is_ascii_alphabetic() || c == '_' {
let start = i;
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
i += 1;
}
tokens.push(text[start..i].to_owned());
} else {
let op = OPERATORS
.iter()
.find(|o| text[i..].starts_with(**o))
.map_or(&text[i..i + c.len_utf8()], |o| o);
i += op.len();
tokens.push(op.to_owned());
}
}
Parser {
tokens,
at: 0,
calls,
}
}
fn peek(&self) -> Option<&str> {
self.tokens.get(self.at).map(String::as_str)
}
fn eat(&mut self, t: &str) -> bool {
let hit = self.peek() == Some(t);
self.at += usize::from(hit);
hit
}
fn expr_all(&mut self) -> Result<Expr, String> {
let e = self.binary(0)?;
match self.peek() {
None => Ok(e),
Some(t) => Err(format!("unexpected `{t}`")),
}
}
/// Precedence levels from the loosest: `||`, `&&`, equality, relations, sums, products.
fn binary(&mut self, level: usize) -> Result<Expr, String> {
const LEVELS: [&[&str]; 6] = [
&["||"],
&["&&"],
&["==", "!="],
&["<", "<=", ">", ">="],
&["+", "-"],
&["*", "/", "%"],
];
if level == LEVELS.len() {
return self.unary();
}
let mut left = self.binary(level + 1)?;
while let Some(op) = self
.peek()
.and_then(|t| LEVELS[level].iter().find(|o| **o == t))
{
self.at += 1;
let right = self.binary(level + 1)?;
left = Expr::Bin(op, Box::new(left), Box::new(right));
}
Ok(left)
}
fn unary(&mut self) -> Result<Expr, String> {
if self.eat("-") {
return Ok(Expr::Neg(Box::new(self.unary()?)));
}
if self.eat("!") {
return Ok(Expr::Not(Box::new(self.unary()?)));
}
self.eat("+");
self.primary()
}
fn primary(&mut self) -> Result<Expr, String> {
let Some(t) = self.peek().map(str::to_owned) else {
return Err("the expression ends early".into());
};
self.at += 1;
if t == "(" {
let e = self.binary(0)?;
return if self.eat(")") {
Ok(e)
} else {
Err("missing `)`".into())
};
}
if t.starts_with(|c: char| c.is_ascii_digit() || c == '.') {
return t
.trim_end_matches(['f', 'F'])
.parse()
.map(Expr::Num)
.map_err(|_| format!("bad number `{t}`"));
}
if !is_name(&t) {
return Err(format!("unexpected `{t}`"));
}
if self.eat("(") {
let mut args = Vec::new();
if !self.eat(")") {
loop {
args.push(self.binary(0)?);
if self.eat(")") {
break;
}
if !self.eat(",") {
return Err(format!("missing `)` after the arguments of `{t}`"));
}
}
}
*self.calls += 1;
return Ok(Expr::Call(t, args, *self.calls));
}
let component = if self.eat(".") {
let c = self.peek().map(str::to_owned).ok_or("nothing after `.`")?;
self.at += 1;
let index = |s: &str| match s {
"x" | "r" | "s" | "0" => Some(0),
"y" | "g" | "t" | "1" => Some(1),
"z" | "b" | "p" | "2" => Some(2),
"w" | "a" | "q" | "3" => Some(3),
_ => None,
};
Some(match c.split_once('.') {
Some((r, col)) => (
index(r).ok_or(format!("bad component `{c}`"))?,
Some(index(col).ok_or(format!("bad component `{c}`"))?),
),
None => (index(&c).ok_or(format!("bad component `{c}`"))?, None),
})
} else {
None
};
Ok(Expr::Name(t, component))
}
}
fn is_name(t: &str) -> bool {
t.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Macros;
fn custom(text: &str) -> Custom {
Custom::parse(&Properties::parse(text, &Macros::standard()))
}
#[test]
fn expressions_follow_c_precedence_and_file_order() {
let mut c = custom(
"variable.float.a = 1 + 2 * 3 - 4 % 3\n\
uniform.float.b = a / 2\n\
uniform.bool.c = a > 5 && !(b < 1) || false\n\
uniform.int.d = -7 / 2\n\
uniform.vec3.e = vec3(a, cameraPosition.y, 2) * 2\n\
uniform.float.f = if(a < 0, 1, a < 7, 2, 3) + clamp(fmod(-1, 4), 0, 2.5) + min(4, 2, 3)\n\
uniform.float.g = gbufferModelView.1.0 + frac(sunAngle - 0.25) + pi * 0\n\
uniform.float.h = unknownThing + in(biome, 3, BIOME_DESERT)\n",
);
assert!(c.notes.is_empty(), "{:?}", c.notes);
let names: Vec<_> = c.uniforms().map(|u| u.0).collect();
assert_eq!(names, ["b", "c", "d", "e", "f", "g", "h"]);
let builtin = |n: &str| match n {
"cameraPosition" => Some(Val::vector(&[1.0, 64.0, 2.0])),
"sunAngle" => Some(Val::scalar(0.125)),
"biome" => Some(Val::scalar(5.0)),
"BIOME_DESERT" => Some(Val::scalar(5.0)),
"gbufferModelView" => {
let mut m = Val::scalar(0.0);
m.v[1] = 9.0; // column 0, row 1
m.n = 16;
Some(m)
}
_ => None,
};
let v = c.eval(0.016, &builtin);
let x: Vec<f64> = v.iter().map(|v| v.v[0]).collect();
assert_eq!(x, [3.0, 1.0, -3.0, 12.0, 2.0 + 2.5 + 2.0, 9.0 + 0.875, 1.0]);
assert_eq!(&v[3].v[..3], &[12.0, 128.0, 4.0]);
assert_eq!(c.notes, ["`unknownThing` is unknown; it reads 0"]);
}
#[test]
fn smooth_halves_the_distance_per_fade_time() {
let mut c = custom("uniform.float.s = smooth(1, target, 2, 0.5)\n");
let mut target = 0.0;
let mut run = |t: f64, dt: f64| {
target = t;
c.eval(dt, &|n: &str| (n == "target").then(|| Val::scalar(target)))[0].v[0]
};
assert_eq!(run(0.0, 0.0), 0.0);
assert!((run(1.0, 2.0) - 0.5).abs() < 1e-9, "rising: fadeIn");
assert!((run(0.0, 0.5) - 0.25).abs() < 1e-9, "falling: fadeOut");
}
#[test]
fn bad_expressions_are_reported() {
let c = custom("uniform.float.a = (1 + \nuniform.mat4.m = 1\nuniform.float.ok = 2\n");
assert_eq!(c.uniforms().count(), 1);
assert_eq!(c.notes.len(), 2, "{:?}", c.notes);
}
}
+11 -4
View File
@@ -12,8 +12,10 @@
//! - [`load_post`]: a dimension's `prepare`, `deferred`, `composite` and `final` programs, in order (2.1).
//! - [`Macros`] and [`eval_condition`]: the macros packs test, and the `#if` arithmetic (1.5).
mod block_ids;
mod condition;
mod config;
mod custom;
mod discover;
mod lang;
mod macros;
@@ -24,17 +26,22 @@ mod preprocess;
mod properties;
mod translate;
pub use block_ids::BlockIds;
pub use condition::eval_condition;
pub use config::{BUFFERS, Buffer, Config, Format, Kind, buffer_index, draw_buffers};
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::{Group, Post, PostProgram, dimension_folder, load_post};
pub use post::{
Blend, CELESTIAL_BLEND, Factor, GameInputs, Group, Post, PostProgram, TRANSLUCENT_BLEND,
dimension_folder, load_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
+237 -12
View File
@@ -13,6 +13,7 @@
use std::collections::BTreeSet;
use crate::config::{self, Config};
use crate::custom::Custom;
use crate::{GbuffersInputs, Macros, Pack, Preprocessed, Program, Properties, Target};
use crate::{eval_condition, preprocess, translate_composite, translate_gbuffers};
@@ -23,10 +24,67 @@ pub enum Group {
Deferred,
Composite,
Final,
/// A gbuffers program: the game draws its geometry with it.
/// A gbuffers program: the game draws its geometry with it, before deferred.
Gbuffers,
/// A gbuffers program drawing translucent geometry, after deferred (2.1).
Translucent,
}
/// A blend factor of `blend.<program>` (3.2), as GL names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Factor {
Zero,
One,
SrcColor,
OneMinusSrcColor,
DstColor,
OneMinusDstColor,
SrcAlpha,
OneMinusSrcAlpha,
DstAlpha,
OneMinusDstAlpha,
SrcAlphaSaturate,
}
impl Factor {
fn parse(word: &str) -> Option<Self> {
Some(match word {
"ZERO" => Self::Zero,
"ONE" => Self::One,
"SRC_COLOR" => Self::SrcColor,
"ONE_MINUS_SRC_COLOR" => Self::OneMinusSrcColor,
"DST_COLOR" => Self::DstColor,
"ONE_MINUS_DST_COLOR" => Self::OneMinusDstColor,
"SRC_ALPHA" => Self::SrcAlpha,
"ONE_MINUS_SRC_ALPHA" => Self::OneMinusSrcAlpha,
"DST_ALPHA" => Self::DstAlpha,
"ONE_MINUS_DST_ALPHA" => Self::OneMinusDstAlpha,
"SRC_ALPHA_SATURATE" => Self::SrcAlphaSaturate,
_ => return None,
})
}
}
/// Source and destination factors for colour, then for alpha.
pub type Blend = [Factor; 4];
/// The default blend of translucent geometry (3.2).
pub const TRANSLUCENT_BLEND: Blend = [
Factor::SrcAlpha,
Factor::OneMinusSrcAlpha,
Factor::One,
Factor::OneMinusSrcAlpha,
];
/// `gbuffers_water` and its fallbacks (2.3).
const WATER: [&str; 5] = [
"gbuffers_water",
"gbuffers_terrain",
"gbuffers_textured_lit",
"gbuffers_textured",
"gbuffers_basic",
];
/// `gbuffers_terrain` and its fallbacks (2.3).
const TERRAIN: [&str; 4] = [
"gbuffers_terrain",
@@ -35,6 +93,24 @@ const TERRAIN: [&str; 4] = [
"gbuffers_basic",
];
/// `gbuffers_skybasic` and its fallback (2.3).
const SKY: [&str; 2] = ["gbuffers_skybasic", "gbuffers_basic"];
/// `gbuffers_skytextured` and its fallbacks (2.3).
const SKY_TEXTURED: [&str; 3] = [
"gbuffers_skytextured",
"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,
Factor::One,
Factor::One,
Factor::OneMinusSrcAlpha,
];
const GROUPS: [(Group, &str); 4] = [
(Group::Prepare, "prepare"),
(Group::Deferred, "deferred"),
@@ -51,6 +127,11 @@ pub struct PostProgram {
pub buffers: Vec<u32>,
/// `flip.<name>.<buffer>`: buffers forced to flip (true) or kept (false) after this program.
pub flips: Vec<(u32, bool)>,
/// How a gbuffers program's output blends into its buffers; `None` writes them.
pub blend: Option<Blend>,
/// Bit n: `colortex<n>MipmapEnabled` in its fragment stage, so buffer n's mip chain is
/// regenerated right before it (6.1.7; not for gbuffers programs).
pub mipmaps: u16,
}
pub struct Post {
@@ -62,6 +143,14 @@ pub struct Post {
pub composite_pre: Vec<(u32, bool)>,
/// What draws solid and cutout terrain, when the game asked for it and one loads.
pub terrain: Option<PostProgram>,
/// What draws translucent terrain (water, stained glass) after deferred.
pub water: Option<PostProgram>,
/// What draws the sky (disc, sunset, stars, void) before terrain.
pub sky: Option<PostProgram>,
/// What draws the sun and moon, between the sunset and the stars.
pub sky_textured: Option<PostProgram>,
/// The custom uniforms of `shaders.properties` (3.4).
pub custom: Custom,
pub config: Config,
/// Programs skipped and why, as `program: message` or `file:line: message`.
pub notes: Vec<String>,
@@ -78,14 +167,23 @@ pub fn dimension_folder(pack: &Pack, id: i32) -> String {
}
}
/// Loads the post-processing programs of `folder` and, given the game's terrain vertices, the
/// program terrain draws with.
/// The game's geometry a pack may draw with its gbuffers programs: each kind's vertex inputs,
/// when the game can draw it with a pack.
#[derive(Clone, Debug, Default)]
pub struct GameInputs {
pub terrain: Option<GbuffersInputs>,
pub sky: Option<GbuffersInputs>,
pub celestial: Option<GbuffersInputs>,
}
/// Loads the post-processing programs of `folder` and, for the geometry `inputs` describes, the
/// gbuffers programs it draws with.
pub fn load_post(
pack: &Pack,
folder: &str,
properties: &Properties,
macros: &Macros,
terrain: Option<&GbuffersInputs>,
inputs: &GameInputs,
) -> Post {
let mut post = Post {
folder: folder.to_owned(),
@@ -93,6 +191,10 @@ pub fn load_post(
deferred_pre: flips(properties, "deferred_pre"),
composite_pre: flips(properties, "composite_pre"),
terrain: None,
water: None,
sky: None,
sky_textured: None,
custom: Custom::parse(properties),
config: Config::default(),
notes: Vec::new(),
};
@@ -122,13 +224,43 @@ pub fn load_post(
}
}
}
if let Some(inputs) = terrain {
loader.post.terrain = TERRAIN.iter().find_map(|name| {
loader.load(name.to_string(), Group::Gbuffers, |v, f| {
let mut gbuffers = |names: &[&str], group, inputs: &GbuffersInputs| {
names.iter().find_map(|name| {
loader.load(name.to_string(), group, |v, f| {
translate_gbuffers(v, f, Target::Buffers, inputs)
})
})
};
// The sky blends as vanilla draws its sunset fan and stars unless `blend.*` says otherwise.
let sky = inputs
.sky
.as_ref()
.and_then(|i| gbuffers(&SKY, Group::Gbuffers, i));
let sky = sky.map(|mut p| {
p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_BLEND));
p
});
let celestial = inputs.celestial.as_ref();
let sky_textured = celestial.and_then(|i| gbuffers(&SKY_TEXTURED, Group::Gbuffers, i));
let sky_textured = sky_textured.map(|mut p| {
p.blend = blend(properties, &p.name).unwrap_or(Some(CELESTIAL_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).
let water = gbuffers(&WATER, Group::Translucent, inputs);
loader.post.terrain = terrain;
loader.post.water = water.map(|mut p| {
p.blend = blend(properties, &p.name).unwrap_or(Some(TRANSLUCENT_BLEND));
p
});
if let Some(p) = &mut loader.post.terrain {
p.blend = blend(properties, &p.name).flatten();
}
}
loader.post.sky = sky;
loader.post.sky_textured = sky_textured;
post.config = std::mem::take(&mut post.config).finish();
post
}
@@ -201,12 +333,24 @@ impl Loader<'_> {
self.post.config.read(&vertex);
self.post.config.read(&fragment);
let buffers = config::draw_buffers(&fragment).unwrap_or_else(|| (0..8).collect());
let mipmaps = match group {
Group::Gbuffers | Group::Translucent => 0,
_ => {
let mut own = Config::default();
own.read(&fragment);
(own.buffers.iter().enumerate())
.filter(|b| b.1.mipmap)
.fold(0, |m, (i, _)| m | 1 << i)
}
};
Some(PostProgram {
flips: flips(self.properties, &name),
name,
group,
program,
buffers,
blend: None,
mipmaps,
})
}
}
@@ -256,6 +400,20 @@ fn enabled(
eval_condition(&condition, macros).ok() != Some(0)
}
/// `blend.<program>`: `Some(None)` for `off`, `Some(factors)`, or `None` when absent or not
/// four known factors.
fn blend(properties: &Properties, program: &str) -> Option<Option<Blend>> {
let value = properties.get(&format!("blend.{program}"))?.trim();
if value == "off" {
return Some(None);
}
let factors: Vec<Factor> = value
.split_whitespace()
.map(Factor::parse)
.collect::<Option<_>>()?;
Some(Some(factors.try_into().ok()?))
}
/// `flip.<program>.<buffer>=<bool>` keys of one program.
fn flips(properties: &Properties, program: &str) -> Vec<(u32, bool)> {
let prefix = format!("flip.{program}.");
@@ -297,7 +455,8 @@ mod tests {
("shaders/deferred.vsh", VSH),
(
"shaders/deferred.fsh",
"#version 120\nvoid main() { gl_FragColor = vec4(1.0); }\n",
"#version 120\nconst bool colortex5MipmapEnabled = true;\n\
void main() { gl_FragColor = vec4(1.0); }\n",
),
("shaders/composite1.fsh", FSH),
("shaders/composite3.vsh", VSH),
@@ -324,11 +483,18 @@ mod tests {
);
assert_eq!(dimension_folder(&pack, 0), "");
assert_eq!(dimension_folder(&pack, -1), "world-1");
let post = load_post(&pack, "", &properties, &Macros::standard(), None);
let post = load_post(
&pack,
"",
&properties,
&Macros::standard(),
&GameInputs::default(),
);
let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["deferred", "composite", "composite2", "final"]);
let p = &post.programs;
assert_eq!(p[0].buffers, (0..8).collect::<Vec<_>>());
assert_eq!((p[0].mipmaps, p[1].mipmaps), (1 << 5, 0));
assert_eq!(p[1].buffers, [3]);
assert_eq!(p[1].flips, [(3, false)]);
assert_eq!(p[2].flips, [(4, true)]);
@@ -344,13 +510,72 @@ mod tests {
let mut macros = Macros::standard();
macros.define("HQ", "");
let post = load_post(&pack, "world-1", &properties, &macros, None);
let post = load_post(
&pack,
"world-1",
&properties,
&macros,
&GameInputs::default(),
);
let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["final"]);
let post = load_post(&pack, "", &properties, &macros, None);
let post = load_post(&pack, "", &properties, &macros, &GameInputs::default());
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.
#[test]
fn water_falls_back_to_terrain_and_blends() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/packs/terrain-test");
let pack = Pack::open(&dir).unwrap();
let macros = Macros::standard();
let inputs = crate::GbuffersInputs {
declarations: "layout(location = 0) in vec3 hz_v_pos;".into(),
body: " hz_Vertex = vec4(hz_v_pos, 1.0);\n hz_Color = vec4(1.0);\n".into(),
..Default::default()
};
let inputs = GameInputs {
terrain: Some(inputs.clone()),
sky: Some(inputs.clone()),
celestial: Some(inputs),
};
let post = load_post(&pack, "", &Properties::default(), &macros, &inputs);
let (terrain, water) = (post.terrain.unwrap(), post.water.unwrap());
assert_eq!((terrain.group, terrain.blend), (Group::Gbuffers, None));
assert_eq!(water.name, "gbuffers_terrain");
let sky = post.sky.unwrap();
assert_eq!(
(sky.name.as_str(), sky.group, sky.blend),
(
"gbuffers_skybasic",
Group::Gbuffers,
Some(TRANSLUCENT_BLEND)
)
);
// gbuffers_skytextured falls back to gbuffers_textured, then gbuffers_basic.
let sun = post.sky_textured.unwrap();
assert_eq!(
(sun.name.as_str(), sun.blend),
("gbuffers_textured", Some(CELESTIAL_BLEND))
);
assert_eq!(
(water.group, water.blend),
(Group::Translucent, Some(TRANSLUCENT_BLEND))
);
let properties = Properties::parse(
"blend.gbuffers_terrain = ONE ONE ZERO ONE\nblend.gbuffers_water = off\n",
&macros,
);
let terrain_blend = blend(&properties, "gbuffers_terrain");
assert_eq!(
terrain_blend,
Some(Some([Factor::One, Factor::One, Factor::Zero, Factor::One]))
);
assert_eq!(blend(&properties, "gbuffers_water"), Some(None));
assert_eq!(blend(&properties, "gbuffers_basic"), None);
}
#[test]
fn horizons_test_pack_loads() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/packs/post-test");
@@ -362,7 +587,7 @@ mod tests {
&dimension_folder(&pack, 0),
&properties,
&macros,
None,
&GameInputs::default(),
);
assert!(post.notes.is_empty(), "{:?}", post.notes);
let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect();
+49 -4
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,
@@ -98,6 +109,8 @@ pub struct GbuffersInputs {
/// The value of each attribute a pack may declare (`mc_Entity`, `vaPosition`...), as a GLSL
/// expression of the declared type's size; an attribute not listed reads zero.
pub attributes: Vec<(String, String)>,
/// GLSL statements run last in `main`, with `gl_Position` in wgpu's clip space.
pub after: String,
}
/// Translates a composite-style program (`composite`, `deferred`, `final`...).
@@ -170,6 +183,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 +227,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!(
@@ -264,7 +294,8 @@ fn translate(
}
write!(
vertex_main,
" hz_main();\n gl_Position = vec4(gl_Position.x, {flip}gl_Position.y, (gl_Position.z + gl_Position.w) * 0.5, gl_Position.w);\n}}\n"
" hz_main();\n gl_Position = vec4(gl_Position.x, {flip}gl_Position.y, (gl_Position.z + gl_Position.w) * 0.5, gl_Position.w);\n{}}}\n",
gbuffers.map_or("", |g| &g.after)
)
.unwrap();
let mut fragment_main = String::from("\nvoid main() {\n");
@@ -327,6 +358,7 @@ fn translate(
uniforms,
samplers,
outputs,
draw,
},
})
}
@@ -394,7 +426,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 +582,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)]
@@ -564,6 +600,7 @@ mod tests {
hz_MultiTexCoord1 = vec4(240.0, 240.0, 0.0, 1.0);\n hz_Color = vec4(1.0);\n hz_Normal = vec3(0.0, 1.0, 0.0);\n"
.into(),
attributes: vec![("mc_midTexCoord".into(), "vec2(game_uv) / 32768.0".into())],
..Default::default()
};
let p = translate_gbuffers(
&preprocess(&pack, "gbuffers_terrain.vsh", &m),
@@ -586,6 +623,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,9 @@
Horizon's own shader pack for testing gbuffers terrain (written for Horizon, no other pack's code).
`gbuffers_terrain` draws blocks from the atlas with their vertex colour and lightmap, tinted by
the lightmap coordinate's sky light (cooler where the sky is hidden); `mc_midTexCoord` marks each
face's centre with a dot. `composite` puts the depth buffer's view-space distance into the blue
face's centre with a dot; leaves (id 1 in `block.properties`) are yellow, and any stage but solid terrain (translucent terrain falls back to it)
is red. `gbuffers_skybasic` draws the sky in its vertex colour, a little greener, with magenta
stars and a dark red void; `gbuffers_textured` (the fallback of `gbuffers_skytextured`) the sun,
and the moon tinted green. `composite` puts the depth buffer's view-space distance into the blue
channel of the far half. Copy the folder into `shaderpacks/` and run the game with
`HORIZON_SHADER_PACK=terrain-test`.
@@ -0,0 +1,3 @@
# Leaves draw yellow in gbuffers_terrain.
block.1=oak_leaves spruce_leaves birch_leaves jungle_leaves acacia_leaves dark_oak_leaves \
mangrove_leaves cherry_leaves azalea_leaves flowering_azalea_leaves pale_oak_leaves
@@ -0,0 +1,15 @@
#version 120
uniform int renderStage;
varying vec4 glcolor;
void main() {
vec4 color = glcolor;
// Stars magenta, the void dark red, the sky disc a little greener: each stage is told apart.
if (renderStage == MC_RENDER_STAGE_STARS) color.rgb = vec3(1.0, 0.0, 1.0);
if (renderStage == MC_RENDER_STAGE_VOID) color.rgb = vec3(0.3, 0.0, 0.0);
if (renderStage == MC_RENDER_STAGE_SKY) color.g = min(color.g + 0.2, 1.0);
/* DRAWBUFFERS:0 */
gl_FragData[0] = color;
}
@@ -0,0 +1,8 @@
#version 120
varying vec4 glcolor;
void main() {
gl_Position = ftransform();
glcolor = gl_Color;
}
@@ -3,11 +3,13 @@
uniform sampler2D texture;
uniform sampler2D lightmap;
uniform ivec2 atlasSize;
uniform int renderStage;
varying vec2 texcoord;
varying vec2 lmcoord;
varying vec2 mid;
varying vec4 glcolor;
varying float blockId;
void main() {
vec4 color = texture2D(texture, texcoord) * glcolor;
@@ -15,8 +17,12 @@ void main() {
color.rgb *= texture2D(lightmap, lmcoord).rgb;
// Less sky light: bluer.
color.rgb = mix(color.rgb * vec3(0.6, 0.7, 1.2), color.rgb, lmcoord.y);
// Leaves (block.properties' id 1) yellow.
if (abs(blockId - 1.0) < 0.5) color.rgb = vec3(color.g, color.g, 0.0);
// 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;
}
@@ -1,11 +1,13 @@
#version 120
attribute vec4 mc_midTexCoord;
attribute vec4 mc_Entity;
varying vec2 texcoord;
varying vec2 lmcoord;
varying vec2 mid;
varying vec4 glcolor;
varying float blockId;
void main() {
gl_Position = ftransform();
@@ -13,4 +15,5 @@ void main() {
lmcoord = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy;
mid = mc_midTexCoord.xy;
glcolor = gl_Color;
blockId = mc_Entity.x;
}
@@ -0,0 +1,15 @@
#version 120
uniform sampler2D texture;
uniform int renderStage;
varying vec2 texcoord;
varying vec4 glcolor;
void main() {
vec4 color = texture2D(texture, texcoord) * glcolor;
// The moon tinted green: the sun and the moon are told apart.
if (renderStage == MC_RENDER_STAGE_MOON) color.rb *= 0.3;
/* DRAWBUFFERS:0 */
gl_FragData[0] = color;
}
@@ -0,0 +1,10 @@
#version 120
varying vec2 texcoord;
varying vec4 glcolor;
void main() {
gl_Position = ftransform();
texcoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy;
glcolor = gl_Color;
}
+18 -8
View File
@@ -167,21 +167,31 @@ fn real_packs_read() {
declarations: "layout(location = 0) in vec3 hz_v_pos;".into(),
body: " hz_Vertex = vec4(hz_v_pos, 1.0);\n hz_Color = vec4(1.0);\n".into(),
attributes: vec![("mc_Entity".into(), "vec4(-1.0)".into())],
..Default::default()
};
let post = load_post(
&pack,
&folder,
&shaders,
&Macros::standard(),
Some(&terrain),
);
let inputs = horizon_shaders::GameInputs {
terrain: Some(terrain.clone()),
sky: Some(terrain.clone()),
celestial: Some(terrain),
};
let post = load_post(&pack, &folder, &shaders, &Macros::standard(), &inputs);
println!(
" dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, {} notes, {:.0} ms",
" dimension {id} (folder `{folder}`): {} post programs, terrain {:?}, water {:?}, sky {:?} {:?}, {} 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.notes.len() + post.config.notes.len(),
start.elapsed().as_secs_f64() * 1000.0
);
let mut custom = post.custom;
custom.eval(0.016, &|_| None);
println!(
" {} custom uniforms; notes: {:?}",
custom.uniforms().count(),
custom.notes.iter().take(4).collect::<Vec<_>>()
);
for n in post.notes.iter().chain(&post.config.notes).take(12) {
println!(" {n}");
}