feat(shaders): complete wgpu Iris/Horizon API-2 shader pipeline, shadow & G-buffer passes, GLSL translator fixes, and settings/import UI

This commit is contained in:
kerneldroid
2026-10-23 10:37:14 +05:00
parent 5bb492ca54
commit 4dff61b697
27 changed files with 3614 additions and 287 deletions
+3
View File
@@ -10700,6 +10700,9 @@ impl ApplicationHandler for Game<'_> {
WindowEvent::CloseRequested => {
self.pending_save.as_mut().unwrap().quit = true;
}
WindowEvent::DroppedFile(path) => {
self.import_shader_pack_path(&path);
}
WindowEvent::Focused(focused) => {
self.focused = focused;
if !focused {
@@ -243,6 +243,12 @@ impl Game<'_> {
super::packs::open_folder(&dir);
}
Event::Credits => self.open_win_screen(false, super::win::Finish::Options),
Event::ImportShaderPack => {
self.import_shader_pack_dialog();
}
Event::ReloadShaderPack => {
self.load_shader_pack();
}
}
}
Ok(())
+54
View File
@@ -34,6 +34,60 @@ pub fn open_folder(dir: &Path) {
log::warn!("Horizon: could not open {}: {e}", dir.display());
}
}
/// Open a native file dialog to pick a shader pack `.zip` or folder, falling
/// back to opening `dir` in the system file manager when no dialog helper is present.
pub fn pick_shader_pack(dir: &Path) -> Option<PathBuf> {
let _ = std::fs::create_dir_all(dir);
let output = if cfg!(target_os = "windows") {
std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"Add-Type -AssemblyName System.Windows.Forms; $f = New-Object System.Windows.Forms.OpenFileDialog; $f.Filter = 'Shader Packs (*.zip;pack.toml)|*.zip;pack.toml|All Files (*.*)|*.*'; if ($f.ShowDialog() -eq 'OK') { Write-Output $f.FileName }",
])
.output()
.ok()
} else if cfg!(target_os = "macos") {
std::process::Command::new("osascript")
.args([
"-e",
"POSIX path of (choose file with prompt \"Select Shader Pack (.zip)\")",
])
.output()
.ok()
} else {
std::process::Command::new("zenity")
.args([
"--file-selection",
"--title=Import Shader Pack (.zip)",
"--file-filter=Shader Packs (*.zip) | *.zip",
])
.output()
.ok()
.filter(|o| o.status.success())
.or_else(|| {
std::process::Command::new("kdialog")
.args(["--getopenfilename", ".", "*.zip|Shader Packs (*.zip)"])
.output()
.ok()
})
};
if let Some(out) = output
&& out.status.success()
{
let raw = String::from_utf8_lossy(&out.stdout).trim().to_owned();
if !raw.is_empty() {
let p = PathBuf::from(raw);
if p.file_name().is_some_and(|n| n == "pack.toml") {
return p.parent().map(Path::to_path_buf);
}
return Some(p);
}
return None;
}
open_folder(dir);
None
}
/// The resource root to load from, given the vanilla root and the selection.
pub fn startup_root(vanilla: &Path, selected: &[String]) -> std::io::Result<PathBuf> {
let all = packs::discover(vanilla, &packs_dir());
@@ -101,6 +101,32 @@ impl Game<'_> {
self.load_shader_pack();
}
}
/// Import a shader pack from `source` into `shaderpacks/`, activate it, and reload.
pub(super) fn import_shader_pack_path(&mut self, source: &std::path::Path) {
let dest = dir();
match shader_pack::import_pack(source, &dest) {
Ok(id) => {
self.ui.options.shader_packs = Default::default();
self.ui.options.shader_packs.poll(dest);
self.settings.horizon.shader_pack = id;
self.ui.options.shader_pack_config = None;
self.ui.options.sync_shader_pack_config(&self.settings);
self.settings.save(&Self::options_path());
self.load_shader_pack();
}
Err(e) => {
log::warn!("Horizon: shader pack import failed: {e}");
self.system_message(Text::literal(format!("Shader pack import: {e}")));
}
}
}
/// Open the system file picker (or `shaderpacks/` folder) to import a shader pack.
pub(super) fn import_shader_pack_dialog(&mut self) {
let dest = dir();
if let Some(chosen) = super::packs::pick_shader_pack(&dest) {
self.import_shader_pack_path(&chosen);
}
}
fn shader_pack_error(&mut self, id: &str, error: &str) {
log::warn!("Horizon: shader pack {id}: {error}");
// The Shader Packs page says why on the pack's row: the first line,
@@ -387,6 +387,22 @@ impl Loading {
self.menu.win = Some((screen, Instant::now()));
}
}
Event::ImportShaderPack => {
let dir = horizon_client::shader_pack::folder();
if let Some(chosen) = packs::pick_shader_pack(&dir)
&& let Ok(id) = horizon_client::shader_pack::import_pack(&chosen, &dir)
{
self.menu.options.shader_packs = Default::default();
self.menu.options.shader_packs.poll(dir);
self.settings.horizon.shader_pack = id;
self.menu.options.shader_pack_config = None;
self.menu.options.sync_shader_pack_config(&self.settings);
self.save_menu_settings();
}
}
Event::ReloadShaderPack => {
self.save_menu_settings();
}
// The startup menu runs before the game opens a control socket.
Event::ButtonClick | Event::CopyAgentDetails => {}
}
@@ -452,6 +468,17 @@ impl Loading {
}
self.apply_menu_settings();
}
WindowEvent::DroppedFile(path) => {
let dir = horizon_client::shader_pack::folder();
if let Ok(id) = horizon_client::shader_pack::import_pack(&path, &dir) {
self.menu.options.shader_packs = Default::default();
self.menu.options.shader_packs.poll(dir);
self.settings.horizon.shader_pack = id;
self.menu.options.shader_pack_config = None;
self.menu.options.sync_shader_pack_config(&self.settings);
self.save_menu_settings();
}
}
WindowEvent::RedrawRequested => self.draw(),
WindowEvent::ModifiersChanged(modifiers) => self.menu.modifiers = modifiers.state(),
WindowEvent::Focused(false) => {
+213 -1
View File
@@ -332,6 +332,11 @@ pub struct Renderer {
/// (`crosshair_globals`).
crosshair_group: wgpu::BindGroup,
crosshair_globals: wgpu::Buffer,
shadow_pipeline: wgpu::RenderPipeline,
shadow_entity_pipeline: wgpu::RenderPipeline,
shadow_globals: wgpu::Buffer,
shadow_group: wgpu::BindGroup,
shadow_entity_group: wgpu::BindGroup,
entity_pipeline: wgpu::RenderPipeline,
weather: weather::Weather,
crumbling_pipeline: wgpu::RenderPipeline,
@@ -1271,6 +1276,38 @@ impl Renderer {
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let shadow_globals = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack shadow globals"),
size: std::mem::size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Terrain shadow"),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_terrain"),
compilation_options: Default::default(),
buffers: &terrain_buffers,
},
primitive: wgpu::PrimitiveState {
topology: tri,
cull_mode: Some(wgpu::Face::Back),
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: None,
multiview_mask: None,
cache: None,
});
let prepared = prepared.unwrap_or_else(|| {
PreparedTextures::new(sprite_pixels, sprite_size, layers, sprite_mips, forcefield)
});
@@ -1384,6 +1421,16 @@ impl Renderer {
&lightmap_view,
&lightmap_sampler,
);
let shadow_group = terrain_group(
&device,
"Shader pack shadow terrain resources",
&bindings,
&shadow_globals,
&sprite_views,
&sprite_sampler,
&lightmap_view,
&lightmap_sampler,
);
let index_quads = 1 << 16;
let indices = Self::quad_indices(&device, index_quads);
let instance_capacity = 4096;
@@ -1539,6 +1586,32 @@ impl Renderer {
},
],
});
let shadow_entity_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Shader pack shadow entity resources"),
layout: &entity_bindings,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: shadow_globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&atlas_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&lightmap_sampler),
},
],
});
let entity_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Entity layout"),
bind_group_layouts: &[Some(&entity_bindings)],
@@ -1649,6 +1722,32 @@ impl Renderer {
wgpu::ColorWrites::ALL,
)
};
let shadow_entity_pipeline =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Entity shadow"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
module: &entity_shader,
entry_point: Some("vs_entity"),
compilation_options: Default::default(),
buffers: &entity_vertex,
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: None,
multiview_mask: None,
cache: None,
});
// RenderPipelines.WATER_MASK: the boat's water patch writes depth only.
let water_mask_pipeline = entity_pipeline_with(
"Water mask",
@@ -2157,6 +2256,11 @@ impl Renderer {
debug_line_capacity: 4096,
crosshair_group,
crosshair_globals,
shadow_pipeline,
shadow_entity_pipeline,
shadow_globals,
shadow_group,
shadow_entity_group,
entity_pipeline,
weather,
crumbling_pipeline,
@@ -2661,7 +2765,12 @@ impl Renderer {
&pack.id,
java,
)?),
None => Pack::Horizon(pack_stages::PackStages::new(&self.device, format, pack)?),
None => Pack::Horizon(pack_stages::PackStages::new(
&self.device,
&self.queue,
format,
pack,
)?),
}),
None => None,
};
@@ -2703,6 +2812,16 @@ impl Renderer {
&self.lightmap_view,
&self.lightmap_sampler,
);
self.shadow_group = terrain_group(
&self.device,
"Shader pack shadow terrain resources",
&self.terrain_layout,
&self.shadow_globals,
&views,
&self.sprite_sampler,
&self.lightmap_view,
&self.lightmap_sampler,
);
}
pub fn view_projection(&self, frame: &Frame) -> Mat4 {
self.projection(
@@ -3544,6 +3663,32 @@ impl Renderer {
}
// The world's targets: the screen, or the scaled target of `post`.
let pack = self.pack.is_some() && !frame.title;
let shadow_cfg = if pack {
self.pack.as_ref().and_then(|p| match p {
Pack::Horizon(s) if s.needs_shadow => Some((s.shadow_res, s.shadow_dist)),
Pack::Java(s) if s.needs_shadow() => Some(s.shadow_config(frame.shader.dimension)),
_ => None,
})
} else {
None
};
if let Some((shadow_res, shadow_dist)) = shadow_cfg {
self.world_post
.prepare_shadow(&self.device, shadow_res, shadow_dist, sun, -sun);
let shadow_globals = Globals {
view_proj: (self.world_post.shadow_proj * self.world_post.shadow_view)
.to_cols_array_2d(),
..globals
};
self.uploads.buffer(
&mut encoder,
&self.shadow_globals,
0,
bytemuck::bytes_of(&shadow_globals),
);
} else {
self.world_post.shadow_active = false;
}
let scaled =
self.world_post
.prepare(&self.device, [self.config.width, self.config.height], pack);
@@ -3552,6 +3697,36 @@ impl Renderer {
None => (&view_target, &self.depth),
};
let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0);
if shadow_cfg.is_some() {
let shadow_view = self.world_post.shadow_depth().clone();
let mut shadow_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon shadow"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &shadow_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
..Default::default()
});
if solid_draws > 0 && !flat_frame {
shadow_pass.set_bind_group(0, &self.shadow_group, &[]);
shadow_pass.set_pipeline(&self.shadow_pipeline);
shadow_pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
shadow_pass.set_vertex_buffer(1, self.instances.slice(..));
self.draw_sections(&mut shadow_pass, &self.indirect, 0, 0, solid_draws);
}
if entity_quads > 0 {
shadow_pass.set_pipeline(&self.shadow_entity_pipeline);
shadow_pass.set_bind_group(0, &self.shadow_entity_group, &[]);
shadow_pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
shadow_pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
shadow_pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
}
}
{
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: world_view,
@@ -3753,6 +3928,33 @@ impl Renderer {
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
pass.draw(0..4, debug_depth..debug_depth + debug_top);
}
if pack {
drop(pass);
self.world_post.capture_opaque_depth(&mut encoder);
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: world_view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon world, translucent"),
color_attachments: &attachments,
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: world_depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
..Default::default()
});
pass.set_bind_group(0, &self.group, &[]);
}
match self.flat.as_ref().filter(|_| flat_frame) {
Some(flat) => {
pass.set_pipeline(&flat.translucent);
@@ -3824,6 +4026,15 @@ impl Renderer {
);
}
}
if pack && scaled.is_some() {
self.world_post.build_gbuffer(
&self.queue,
&mut encoder,
&pack_uniform,
frame.shader.eye_light,
frame.shader.rain,
);
}
if let (true, Some((color, depth)), Some(size), Some(stages)) =
(pack, &scaled, self.world_post.size(), self.pack.as_mut())
{
@@ -3837,6 +4048,7 @@ impl Renderer {
size,
&self.world_post,
pack_uniform,
frame.shader.eye_light,
),
Pack::Java(stages) => stages.run(
&self.device,
+258 -50
View File
@@ -1,17 +1,20 @@
//! A Java (OptiFine/Iris) shader pack on the GPU (docs/shader-packs.md):
//! Iris's colour targets (`colortex0..`, each with a main and an alternate
//! side) and the pack's `begin`, `prepare`, `deferred`, `composite` and
//! `final` programs as full-screen passes over them, as Iris's
//! `CompositeRenderer` runs them. Horizon's world enters `colortex0` and
//! `depthtex0..2` after `prepare`, where Iris's gbuffers programs would have
//! drawn, and the last picture goes to `world_post`. The targets keep GL's
//! layout (row 0 at the bottom, which the translated vertex programs
//! produce), so the world is flipped going in and the picture coming out.
//! side), pre-translucent depth (`depthtex1`/`depthtex2`), directional
//! shadow map (`shadowtex0`/`shadowtex1`) and the pack's `begin`, `prepare`,
//! `deferred`, `composite` and `final` programs as full-screen passes over
//! them, as Iris's `CompositeRenderer` runs them. Horizon's world enters
//! `colortex0` and `depthtex0..2` after `prepare`, where Iris's gbuffers
//! programs would have drawn, and the last picture goes to `world_post`. The
//! targets keep GL's layout (row 0 at the bottom, which the translated vertex
//! programs produce), so the world is flipped going in and the picture coming
//! out.
use super::pack_stages::FrameUniform;
use crate::java_pack::{JavaFolder, JavaPasses};
use glam::{Mat3, Mat4, Vec3, Vec4};
use horizon_shaderpack::pipeline::TargetSettings;
use horizon_shaderpack::pipeline::{Directives, Program, target_index};
use horizon_shaderpack::properties::Blend;
use horizon_shaderpack::uniforms::{CustomUniforms, SmoothFloat, UniformState};
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -35,6 +38,7 @@ const MAX_ATTRIBUTES: usize = 8;
const BLIT: &str = r#"
@group(0) @binding(0) var color: texture_2d<f32>;
@group(0) @binding(1) var depth: texture_depth_2d;
@group(0) @binding(2) var opaque_depth: texture_depth_2d;
@vertex
fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
@@ -45,15 +49,20 @@ fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
struct World {
@location(0) color: vec4f,
@location(1) depth: vec4f,
@location(2) opaque_depth: vec4f,
}
// The world's colour and depth, upside down into GL's layout; Horizon's
// reversed depth (near 1) as GL's (near 0).
// The world's colour, depth and pre-translucent depth, upside down into GL's
// layout; Horizon's reversed depth (near 1) as GL's (near 0).
@fragment
fn world_in(@builtin(position) p: vec4f) -> World {
let size = textureDimensions(depth);
let xy = vec2u(u32(p.x), size.y - 1u - u32(p.y));
return World(textureLoad(color, xy, 0), vec4f(1.0 - textureLoad(depth, xy, 0)));
return World(
textureLoad(color, xy, 0),
vec4f(1.0 - textureLoad(depth, xy, 0)),
vec4f(1.0 - textureLoad(opaque_depth, xy, 0)),
);
}
// A target, upside down back into wgpu's layout.
@@ -64,6 +73,42 @@ fn present(@builtin(position) p: vec4f) -> @location(0) vec4f {
}
"#;
/// Convert a GL `Blend` override from `shaders.properties` into a wgpu `BlendState`.
fn blend_state(blend: &Blend) -> Option<wgpu::BlendState> {
let Blend::Factors(factors) = blend else {
return None;
};
let map_factor = |name: &str| -> wgpu::BlendFactor {
use wgpu::BlendFactor as B;
match name {
"ZERO" => B::Zero,
"ONE" => B::One,
"SRC_COLOR" => B::Src,
"ONE_MINUS_SRC_COLOR" => B::OneMinusSrc,
"DST_COLOR" => B::Dst,
"ONE_MINUS_DST_COLOR" => B::OneMinusDst,
"SRC_ALPHA" => B::SrcAlpha,
"ONE_MINUS_SRC_ALPHA" => B::OneMinusSrcAlpha,
"DST_ALPHA" => B::DstAlpha,
"ONE_MINUS_DST_ALPHA" => B::OneMinusDstAlpha,
"SRC_ALPHA_SATURATE" => B::SrcAlphaSaturated,
_ => B::One,
}
};
Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: map_factor(&factors[0]),
dst_factor: map_factor(&factors[1]),
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: map_factor(&factors[2]),
dst_factor: map_factor(&factors[3]),
operation: wgpu::BlendOperation::Add,
},
})
}
/// A wgpu format for each of Iris's (`InternalTextureFormat`), renderable
/// everywhere: 8-bit unsigned normalized formats stay, signed normalized,
/// 16-bit and packed float ones become half floats, integer ones 32-bit.
@@ -123,11 +168,12 @@ struct Target {
#[derive(Clone, Copy, Debug, PartialEq)]
enum Source {
Target(u32),
/// `depthtex0..2`: the world's depth.
/// `depthtex0` / `gdepthtex`: the world's depth (including translucent water).
Depth,
/// `depthtex1` / `depthtex2`: the opaque world's depth (before translucent water).
OpaqueDepth,
Noise,
/// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow);
/// also Distant Horizons' and Voxy's depth, as without those mods.
/// `shadowtex*`: directional sun/moon shadow map depth (or far depth for DH/Voxy).
Shadow,
/// Anything else (`shadowcolor*`, custom textures): white or black.
Blank(bool),
@@ -135,7 +181,8 @@ enum Source {
fn source(name: &str) -> Source {
match name {
"depthtex0" | "depthtex1" | "depthtex2" | "gdepthtex" => Source::Depth,
"depthtex0" | "gdepthtex" => Source::Depth,
"depthtex1" | "depthtex2" => Source::OpaqueDepth,
"noisetex" => Source::Noise,
"shadowtex0" | "shadowtex1" | "shadow" | "watershadow" => Source::Shadow,
n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Shadow,
@@ -146,6 +193,7 @@ fn source(name: &str) -> Source {
/// A sampler of a pass: its texture and sampler bindings.
struct SamplerBinding {
name: String,
source: Source,
dimension: wgpu::TextureViewDimension,
/// `isampler` (true) or `usampler` (false).
@@ -183,6 +231,7 @@ struct Common {
repeat: wgpu::Sampler,
compare: wgpu::Sampler,
noise: wgpu::TextureView,
custom_textures: BTreeMap<String, wgpu::TextureView>,
/// Full-screen triangle data per attribute kind (see `PassGpu::attributes`).
vertices: [wgpu::Buffer; 4],
world_layout: wgpu::BindGroupLayout,
@@ -196,6 +245,7 @@ struct Bound {
size: [u32; 2],
targets: BTreeMap<u32, Target>,
depth: wgpu::TextureView,
opaque_depth: wgpu::TextureView,
/// Per pass, then `final`.
groups: Vec<wgpu::BindGroup>,
world_in: (wgpu::RenderPipeline, wgpu::BindGroup),
@@ -217,6 +267,7 @@ struct Folder {
passes: Vec<PassGpu>,
final_pass: Option<PassGpu>,
directives: Directives,
shadow_enabled: bool,
}
pub struct JavaStages {
@@ -234,9 +285,25 @@ pub struct JavaStages {
uniform_state: UniformState,
/// `eyeBrightnessSmooth`, block then sky.
eye_smooth: [SmoothFloat; 2],
/// `wetness`, smoothed with `wetnessHalflife` / `drynessHalflife`.
wetness_smooth: SmoothFloat,
/// `centerDepthSmooth`, smoothed with `centerDepthHalflife`.
center_depth_smooth: SmoothFloat,
}
impl JavaStages {
/// Whether any dimension folder in this pack reads directional shadow maps.
pub fn needs_shadow(&self) -> bool {
self.folders.iter().any(|f| f.shadow_enabled)
}
/// Shadow map resolution and distance for `dimension`.
pub fn shadow_config(&self, dimension: i8) -> (u32, f32) {
let idx = self.folder_for[(dimension.clamp(-1, 1) + 1) as usize].unwrap_or(0);
let d = &self.folders[idx].directives;
(d.shadow_map_resolution, d.shadow_distance)
}
/// The pipelines of a loaded Java pack, or wgpu's error.
pub fn new(
device: &wgpu::Device,
@@ -245,7 +312,7 @@ impl JavaStages {
id: &str,
pack: &JavaPasses,
) -> Result<Self, String> {
let common = Common::new(device, queue);
let common = Common::new(device, queue, &pack.custom_textures);
let folder_for = [-1, 0, 1].map(|d| pack.folder_for(d));
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let folders = pack
@@ -275,6 +342,7 @@ impl JavaStages {
passes,
final_pass,
directives: plan.directives,
shadow_enabled: plan.shadow_enabled,
})
})
.collect::<Result<Vec<_>, _>>()?;
@@ -295,6 +363,8 @@ impl JavaStages {
uniforms: pack.uniforms.clone(),
uniform_state: UniformState::default(),
eye_smooth: [SmoothFloat::default(); 2],
wetness_smooth: SmoothFloat::default(),
center_depth_smooth: SmoothFloat::default(),
})
}
@@ -335,10 +405,26 @@ impl JavaStages {
self.previous,
);
inputs.set_world(&world, directives.sun_path_rotation);
inputs.shadow_view = post.shadow_view;
inputs.shadow_projection = post.gl_shadow_projection();
inputs.ambient_occlusion_level = directives.ambient_occlusion_level;
inputs.shadow_map_resolution = directives.shadow_map_resolution as f32;
let half_life = directives.eye_brightness_half_life;
for (i, smooth) in self.eye_smooth.iter_mut().enumerate() {
inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time);
}
inputs.wetness = self.wetness_smooth.update(
frame.weather[0],
directives.wetness_half_life,
directives.dryness_half_life,
frame_time,
);
inputs.center_depth_smooth = self.center_depth_smooth.update(
0.5,
directives.center_depth_half_life,
directives.center_depth_half_life,
frame_time,
);
self.uniforms
.update(&mut self.uniform_state, frame_time, &|name| {
inputs.builtin(name)
@@ -496,10 +582,28 @@ impl JavaStages {
size,
)
.create_view(&Default::default());
let opaque_depth = texture(
"Java shader pack opaque depth",
wgpu::TextureFormat::R32Float,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
size,
)
.create_view(&Default::default());
let mut blank = Vec::new();
let groups = all
.clone()
.map(|pass| pass.bind(device, queue, &targets, &depth, &self.common, &mut blank))
.map(|pass| {
pass.bind(
device,
queue,
&targets,
&depth,
&opaque_depth,
post,
&self.common,
&mut blank,
)
})
.collect();
// The world goes into colortex0's side the gbuffers would write.
@@ -509,7 +613,11 @@ impl JavaStages {
&self.common,
&self.common.world_layout,
"world_in",
&[colortex0.format, wgpu::TextureFormat::R32Float],
&[
colortex0.format,
wgpu::TextureFormat::R32Float,
wgpu::TextureFormat::R32Float,
],
);
let world_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Java shader pack world"),
@@ -523,6 +631,10 @@ impl JavaStages {
binding: 1,
resource: wgpu::BindingResource::TextureView(world_depth),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(post.opaque_depth()),
},
],
});
@@ -571,6 +683,7 @@ impl JavaStages {
size,
targets,
depth,
opaque_depth,
groups,
world_in: (world_pipeline, world_group),
world_alt: plan.flipped_after_prepare.contains(&0),
@@ -593,6 +706,7 @@ fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) {
let attachments = [
Some(color_attachment(side, None)),
Some(color_attachment(&bound.depth, None)),
Some(color_attachment(&bound.opaque_depth, None)),
];
let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Java shader pack world"),
@@ -666,7 +780,11 @@ fn blit_pipeline(
}
impl Common {
fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
custom_map: &BTreeMap<String, (u32, u32, Vec<u8>)>,
) -> Self {
let sampler = |filter, address, compare| {
device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Java shader pack"),
@@ -714,6 +832,34 @@ impl Common {
},
noise.size(),
);
let mut custom_textures = BTreeMap::new();
for (name, (w, h, bytes)) in custom_map {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some(name),
size: wgpu::Extent3d {
width: *w,
height: *h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
tex.as_image_copy(),
bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(*w * 4),
rows_per_image: None,
},
tex.size(),
);
custom_textures.insert(name.clone(), tex.create_view(&Default::default()));
}
// The full-screen triangle (0, 0), (2, 0), (0, 2): the pack's
// projection maps 0..1 to the screen. Texture coordinates are the
// position; colours white; normals up.
@@ -754,12 +900,14 @@ impl Common {
repeat: sampler(Linear, Repeat, None),
compare: sampler(Linear, ClampToEdge, Some(wgpu::CompareFunction::LessEqual)),
noise: noise.create_view(&Default::default()),
custom_textures,
vertices,
world_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Java shader pack world"),
entries: &[
texture_entry(0, unfilterable),
texture_entry(1, wgpu::TextureSampleType::Depth),
texture_entry(2, wgpu::TextureSampleType::Depth),
],
}),
present_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -841,6 +989,7 @@ impl PassGpu {
.cloned()
.unwrap_or_else(|| format!("{sampler}_s"));
samplers.push(SamplerBinding {
name: sampler.clone(),
source: source(sampler),
dimension,
signed,
@@ -885,7 +1034,7 @@ impl PassGpu {
)),
)
}
(false, Source::Depth | Source::Shadow) => (
(false, Source::Depth | Source::OpaqueDepth | Source::Shadow) => (
wgpu::TextureSampleType::Float { filterable: false },
Some(false),
),
@@ -979,10 +1128,11 @@ impl PassGpu {
// Output location `l` writes target `draw_buffers[l]` (or the screen).
let outputs = &program.fragment.interface.outputs;
let pass_blend = program.pass.blend.as_ref().and_then(blend_state);
let target_states: Vec<Option<wgpu::ColorTargetState>> = match screen {
Some(format) => vec![Some(wgpu::ColorTargetState {
format,
blend: None,
blend: pass_blend,
write_mask: if outputs.contains_key(&0) {
wgpu::ColorWrites::ALL
} else {
@@ -994,12 +1144,25 @@ impl PassGpu {
.iter()
.enumerate()
.map(|(l, &i)| {
let format = formats
.get(i as usize)
.copied()
.unwrap_or(wgpu::TextureFormat::Rgba8Unorm);
// Only filterable float/unorm formats support blending.
let can_blend = matches!(
sample_type(format),
wgpu::TextureSampleType::Float { filterable: true }
);
let buf_blend = program
.pass
.buffer_blends
.iter()
.find(|(idx, _)| *idx == i)
.map(|(_, b)| blend_state(b))
.unwrap_or(pass_blend);
Some(wgpu::ColorTargetState {
format: formats
.get(i as usize)
.copied()
.unwrap_or(wgpu::TextureFormat::Rgba8Unorm),
blend: None,
format,
blend: if can_blend { buf_blend } else { None },
write_mask: if outputs.contains_key(&(l as u32)) {
wgpu::ColorWrites::ALL
} else {
@@ -1068,37 +1231,54 @@ impl PassGpu {
}
/// The pass's bind group over `targets`.
#[allow(clippy::too_many_arguments)]
fn bind(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
targets: &BTreeMap<u32, Target>,
depth: &wgpu::TextureView,
opaque_depth: &wgpu::TextureView,
post: &super::world_post::Post,
common: &Common,
blank: &mut Vec<wgpu::Texture>,
) -> wgpu::BindGroup {
let mut views = Vec::new();
for s in &self.samplers {
let view = match (s.compare, s.source) {
(true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth),
(false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => {
match targets.get(&i) {
Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(),
Some(t) => t.main_view.clone(),
None => blank_view(device, queue, blank, s, BlankKind::Color(false)),
let view = if let Some(custom) = common
.custom_textures
.get(&s.name)
.filter(|_| !s.compare && s.dimension == wgpu::TextureViewDimension::D2)
{
custom.clone()
} else {
match (s.compare, s.source) {
(true, Source::Shadow) if post.shadow_active => post.shadow_depth().clone(),
(true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth),
(false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => {
match targets.get(&i) {
Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(),
Some(t) => t.main_view.clone(),
None => blank_view(device, queue, blank, s, BlankKind::Color(false)),
}
}
(false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => {
depth.clone()
}
(false, Source::OpaqueDepth)
if s.dimension == wgpu::TextureViewDimension::D2 =>
{
opaque_depth.clone()
}
(false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far),
(false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => {
common.noise.clone()
}
(false, Source::Blank(white)) => {
blank_view(device, queue, blank, s, BlankKind::Color(white))
}
_ => blank_view(device, queue, blank, s, BlankKind::Color(false)),
}
(false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => {
depth.clone()
}
(false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far),
(false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => {
common.noise.clone()
}
(false, Source::Blank(white)) => {
blank_view(device, queue, blank, s, BlankKind::Color(white))
}
_ => blank_view(device, queue, blank, s, BlankKind::Color(false)),
};
let sampler = match (s.compare, s.source) {
_ if s.shared.is_some() => match s.shared.as_deref() {
@@ -1110,7 +1290,7 @@ impl PassGpu {
(true, _) => &common.compare,
_ if s.signed.is_some() => &common.nearest,
(false, Source::Noise) => &common.repeat,
(false, Source::Depth | Source::Shadow) => &common.nearest,
(false, Source::Depth | Source::OpaqueDepth | Source::Shadow) => &common.nearest,
(false, Source::Target(i)) => {
match targets.get(&i).map(|t| sample_type(t.format)) {
Some(wgpu::TextureSampleType::Float { filterable: true }) | None => {
@@ -1432,6 +1612,8 @@ struct Inputs {
view: Mat4,
/// GL's: near at -1, far at 1.
projection: Mat4,
shadow_view: Mat4,
shadow_projection: Mat4,
camera: Vec3,
previous: (Mat4, Mat4, Vec3),
size: [f32; 2],
@@ -1442,6 +1624,10 @@ struct Inputs {
/// `eyeBrightness` and `eyeBrightnessSmooth`: block, sky light × 16.
eye: [f32; 2],
eye_smooth: [f32; 2],
wetness: f32,
center_depth_smooth: f32,
ambient_occlusion_level: f32,
shadow_map_resolution: f32,
/// `CelestialUniforms`, in view space.
sun_position: Vec3,
moon_position: Vec3,
@@ -1490,6 +1676,8 @@ impl Inputs {
let mut out = Self {
view,
projection,
shadow_view: Mat4::IDENTITY,
shadow_projection: Mat4::IDENTITY,
camera,
previous: previous.unwrap_or((view, projection, camera)),
size: size.map(|v| v as f32),
@@ -1499,6 +1687,10 @@ impl Inputs {
frame: *frame,
eye: [0.0; 2],
eye_smooth: [0.0; 2],
wetness: frame.weather[0],
center_depth_smooth: 0.5,
ambient_occlusion_level: 1.0,
shadow_map_resolution: 2048.0,
sun_position: Vec3::ZERO,
moon_position: Vec3::ZERO,
up_position: Vec3::ZERO,
@@ -1591,27 +1783,42 @@ impl Inputs {
}),
"upPosition" => vec3(self.up_position),
"moonPhase" => vec![f.moon[3]],
"rainStrength" | "wetness" => vec![f.weather[0]],
"rainStrength" => vec![f.weather[0]],
"wetness" => vec![self.wetness],
"thunderStrength" => vec![f.weather[1]],
"fogColor" => f.fog_color[..3].to_vec(),
"skyColor" => f.sky_color[..3].to_vec(),
"isEyeInWater" => vec![f.camera_state[0]],
"nightVision" => vec![f.camera_state[1]],
"darknessFactor" => vec![f.camera_state[2]],
"darknessFactor" | "darknessLightFactor" => vec![f.camera_state[2]],
"blindness" => vec![f.camera_state[3]],
"screenBrightness" => vec![1.0],
"centerDepthSmooth" => vec![self.center_depth_smooth],
"ambientOcclusionLevel" => vec![self.ambient_occlusion_level],
"shadowMapResolution" => vec![self.shadow_map_resolution],
"eyeBrightness" => self.eye.to_vec(),
// An ivec2: the smoothed value truncated.
"eyeBrightnessSmooth" => self.eye_smooth.map(f32::trunc).to_vec(),
"hasSkylight" => vec![f.dimension[1]],
"heldItemId" | "heldItemId2" | "heldBlockLightValue" | "heldBlockLightValue2" => {
vec![0.0]
}
"biome" | "biome_category" => vec![0.0],
"biome_precipitation" => vec![if f.weather[0] > 0.01 { 1.0 } else { 0.0 }],
"temp" => vec![0.8],
"rainfall" => vec![0.4],
"alphaTestRef" => vec![0.1],
"renderStage" => vec![0.0],
"playerMood" | "currentColorSpace" => vec![0.0],
"iris_ModelViewMatrix" | "iris_ModelViewMatrixInverse" => mat(Mat4::IDENTITY),
"iris_ProjectionMatrix" | "iris_ModelViewProjectionMatrix" => mat(screen),
"iris_ProjectionMatrixInverse" => mat(screen.inverse()),
"iris_TextureMatrix" => (0..8).flat_map(|_| mat(Mat4::IDENTITY)).collect(),
"iris_NormalMatrix" => Mat3::IDENTITY.to_cols_array().to_vec(),
"shadowModelView"
| "shadowModelViewInverse"
| "shadowProjection"
| "shadowProjectionInverse" => mat(Mat4::IDENTITY),
"shadowModelView" => mat(self.shadow_view),
"shadowModelViewInverse" => mat(self.shadow_view.inverse()),
"shadowProjection" => mat(self.shadow_projection),
"shadowProjectionInverse" => mat(self.shadow_projection.inverse()),
_ => return None,
})
}
@@ -1651,6 +1858,7 @@ mod tests {
assert_eq!(source("colortex4"), Source::Target(4));
assert_eq!(source("gaux1"), Source::Target(4));
assert_eq!(source("gdepthtex"), Source::Depth);
assert_eq!(source("depthtex1"), Source::OpaqueDepth);
assert_eq!(source("shadowtex1"), Source::Shadow);
assert_eq!(source("dhDepthTex0"), Source::Shadow);
assert_eq!(source("shadowcolor0"), Source::Blank(true));
+229 -25
View File
@@ -1,9 +1,12 @@
//! A Horizon shader pack on the GPU (docs/shader-packs.md): each `composite`
//! stage is one full-screen pass that reads the world's colour and depth and
//! the previous stage's output and writes its own target; the last target
//! goes to the screen through `world_post` (copy or FXAA) under the hand and
//! HUD. Only exists while a pack is selected.
use crate::shader_pack::{ShaderPack, VERTEX_ENTRY};
//! A Horizon shader pack on the GPU (docs/shader-packs.md): each stage
//! (`shadow`, `gbuffer`, `deferred`, `composite`, `final`) is a full-screen
//! pass that reads the world's colour, depth, opaque depth, G-buffer normals
//! and materials, shadow map, noise texture and the previous stage's output,
//! and writes its own target; the last target goes to the screen through
//! `world_post` (copy or FXAA) under the hand and HUD. Only exists while a
//! pack is selected.
use crate::shader_pack::{ShaderPack, StageKind, VERTEX_ENTRY};
use horizon_shaderpack::uniforms::SmoothFloat;
/// The `Frame` uniform of the prelude (`shader_pack_prelude.wgsl`).
#[repr(C)]
@@ -27,10 +30,29 @@ pub struct FrameUniform {
pub dimension: [f32; 4],
}
/// The API 2 `FrameExt` uniform of the prelude (`shader_pack_prelude.wgsl`).
#[repr(C)]
#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub struct FrameExtUniform {
pub previous_view: [[f32; 4]; 4],
pub previous_projection: [[f32; 4]; 4],
pub shadow_view: [[f32; 4]; 4],
pub shadow_projection: [[f32; 4]; 4],
pub shadow_inverse_view: [[f32; 4]; 4],
pub shadow_inverse_projection: [[f32; 4]; 4],
pub previous_camera: [f32; 4],
pub shadow_params: [f32; 4],
pub environment: [f32; 4],
}
const NOISE_SIZE: u32 = 256;
struct Pass {
pipeline: wgpu::RenderPipeline,
scale: f32,
target_format: wgpu::TextureFormat,
uniform: wgpu::Buffer,
uniform_ext: wgpu::Buffer,
}
/// A stage's output and the bindings that read the world into it.
struct Target {
@@ -41,24 +63,43 @@ struct Target {
pub struct PackStages {
pub id: String,
pub needs_shadow: bool,
pub shadow_res: u32,
pub shadow_dist: f32,
layout: wgpu::BindGroupLayout,
linear: wgpu::Sampler,
nearest: wgpu::Sampler,
repeat: wgpu::Sampler,
shadow_sampler: wgpu::Sampler,
noise_view: wgpu::TextureView,
passes: Vec<Pass>,
format: wgpu::TextureFormat,
/// Built for this world target size.
targets: Vec<Target>,
/// `world_post`'s bindings of the last stage's output.
output: Option<wgpu::BindGroup>,
world_size: [u32; 2],
shadow_size: u32,
started: std::time::Instant,
last: Option<std::time::Instant>,
frames: u32,
previous: Option<([[f32; 4]; 4], [[f32; 4]; 4], [f32; 3])>,
wetness: SmoothFloat,
}
fn stage_format(name: Option<&str>, default: wgpu::TextureFormat) -> wgpu::TextureFormat {
match name.map(str::to_lowercase).as_deref() {
Some("rgba16float" | "rgba16f") => wgpu::TextureFormat::Rgba16Float,
Some("rgba8unorm" | "rgba8" | "rgba") => wgpu::TextureFormat::Rgba8Unorm,
Some("rgb10a2unorm" | "rgb10_a2") => wgpu::TextureFormat::Rgb10a2Unorm,
_ => default,
}
}
impl PackStages {
/// The pipelines of a loaded (already validated) pack, or wgpu's error.
pub fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
pack: &ShaderPack,
) -> Result<Self, String> {
@@ -79,6 +120,16 @@ impl PackStages {
ty: wgpu::BindingType::Sampler(ty),
count: None,
};
let uniform_entry = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Shader pack stage"),
entries: &[
@@ -87,16 +138,15 @@ impl PackStages {
texture(2, float),
sampler(3, wgpu::SamplerBindingType::Filtering),
sampler(4, wgpu::SamplerBindingType::NonFiltering),
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
uniform_entry(5),
uniform_entry(6),
texture(7, float),
texture(8, float),
texture(9, wgpu::TextureSampleType::Depth),
texture(10, wgpu::TextureSampleType::Depth),
sampler(11, wgpu::SamplerBindingType::Comparison),
texture(12, float),
sampler(13, wgpu::SamplerBindingType::Filtering),
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
@@ -106,10 +156,18 @@ impl PackStages {
});
let constants = pack.constants();
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let stage_count = pack.stages.len();
let passes = pack
.stages
.iter()
.map(|stage| {
.enumerate()
.map(|(idx, stage)| {
let is_last = idx + 1 == stage_count || stage.kind == StageKind::Final;
let target_format = if is_last {
format
} else {
stage_format(stage.format.as_deref(), format)
};
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(&stage.file),
source: wgpu::ShaderSource::Wgsl(stage.source.as_str().into()),
@@ -140,7 +198,7 @@ impl PackStages {
..Default::default()
},
targets: &[Some(wgpu::ColorTargetState {
format,
format: target_format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
@@ -151,38 +209,110 @@ impl PackStages {
Pass {
pipeline,
scale: stage.scale,
target_format,
uniform: device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack frame"),
size: std::mem::size_of::<FrameUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}),
uniform_ext: device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack frame ext"),
size: std::mem::size_of::<FrameExtUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}),
}
})
.collect();
if let Some(error) = pollster::block_on(scope.pop()) {
return Err(error.to_string());
}
let sampler = |filter| {
let make_sampler = |filter, address, compare| {
device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Shader pack"),
address_mode_u: address,
address_mode_v: address,
address_mode_w: address,
mag_filter: filter,
min_filter: filter,
compare,
..Default::default()
})
};
let (nw, nh, noise_bytes) = match &pack.custom_noise {
Some((w, h, bytes)) => (*w, *h, bytes.clone()),
None => {
let mut seed = 0x2545_f491_u32;
let bytes: Vec<u8> = (0..NOISE_SIZE * NOISE_SIZE * 4)
.map(|i| {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
if i % 4 == 3 { 255 } else { (seed >> 24) as u8 }
})
.collect();
(NOISE_SIZE, NOISE_SIZE, bytes)
}
};
let noise_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Shader pack noise"),
size: wgpu::Extent3d {
width: nw,
height: nh,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
noise_tex.as_image_copy(),
&noise_bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(nw * 4),
rows_per_image: None,
},
noise_tex.size(),
);
let (shadow_res, shadow_dist, _) = pack.shadow_config(0);
Ok(Self {
id: pack.id.clone(),
needs_shadow: pack.needs_shadow(),
shadow_res,
shadow_dist,
layout,
linear: sampler(wgpu::FilterMode::Linear),
nearest: sampler(wgpu::FilterMode::Nearest),
linear: make_sampler(
wgpu::FilterMode::Linear,
wgpu::AddressMode::ClampToEdge,
None,
),
nearest: make_sampler(
wgpu::FilterMode::Nearest,
wgpu::AddressMode::ClampToEdge,
None,
),
repeat: make_sampler(wgpu::FilterMode::Linear, wgpu::AddressMode::Repeat, None),
shadow_sampler: make_sampler(
wgpu::FilterMode::Linear,
wgpu::AddressMode::ClampToEdge,
Some(wgpu::CompareFunction::GreaterEqual),
),
noise_view: noise_tex.create_view(&Default::default()),
passes,
format,
targets: Vec::new(),
output: None,
world_size: [0, 0],
shadow_size: 0,
started: std::time::Instant::now(),
last: None,
frames: 0,
previous: None,
wetness: SmoothFloat::default(),
})
}
@@ -199,9 +329,14 @@ impl PackStages {
size: [u32; 2],
post: &super::world_post::Post,
mut uniform: FrameUniform,
eye_light: [u8; 2],
) -> &wgpu::BindGroup {
if self.world_size != size || self.targets.len() != self.passes.len() {
if self.world_size != size
|| self.shadow_size != post.shadow_resolution
|| self.targets.len() != self.passes.len()
{
self.world_size = size;
self.shadow_size = post.shadow_resolution;
self.targets.clear();
for pass in &self.passes {
let target_size = size.map(|v| ((v as f32 * pass.scale).round() as u32).max(1));
@@ -216,7 +351,7 @@ impl PackStages {
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.format,
format: pass.target_format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
@@ -251,6 +386,38 @@ impl PackStages {
binding: 5,
resource: pass.uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 6,
resource: pass.uniform_ext.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::TextureView(post.normal()),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(post.material()),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::TextureView(post.opaque_depth()),
},
wgpu::BindGroupEntry {
binding: 10,
resource: wgpu::BindingResource::TextureView(post.shadow_depth()),
},
wgpu::BindGroupEntry {
binding: 11,
resource: wgpu::BindingResource::Sampler(&self.shadow_sampler),
},
wgpu::BindGroupEntry {
binding: 12,
resource: wgpu::BindingResource::TextureView(&self.noise_view),
},
wgpu::BindGroupEntry {
binding: 13,
resource: wgpu::BindingResource::Sampler(&self.repeat),
},
],
});
self.targets.push(Target {
@@ -262,6 +429,42 @@ impl PackStages {
let last = &self.targets.last().expect("a pack has a stage").view;
self.output = Some(post.bind(device, last));
}
let now = std::time::Instant::now();
let dt = self.last.map_or(0.0, |t| (now - t).as_secs_f32());
self.last = Some(now);
let wet = self.wetness.update(uniform.weather[0], 60.0, 120.0, dt);
let cam = [
uniform.camera_position[0],
uniform.camera_position[1],
uniform.camera_position[2],
];
let (prev_view, prev_proj, prev_cam) =
self.previous
.unwrap_or((uniform.view, uniform.projection, cam));
self.previous = Some((uniform.view, uniform.projection, cam));
let shadow_view = post.shadow_view;
let shadow_proj = post.shadow_proj;
let ext = FrameExtUniform {
previous_view: prev_view,
previous_projection: prev_proj,
shadow_view: shadow_view.to_cols_array_2d(),
shadow_projection: shadow_proj.to_cols_array_2d(),
shadow_inverse_view: shadow_view.inverse().to_cols_array_2d(),
shadow_inverse_projection: shadow_proj.inverse().to_cols_array_2d(),
previous_camera: [prev_cam[0], prev_cam[1], prev_cam[2], dt],
shadow_params: [
post.shadow_resolution as f32,
post.shadow_distance,
0.0,
if post.shadow_active { 1.0 } else { 0.0 },
],
environment: [
f32::from(eye_light[0]) * 16.0,
f32::from(eye_light[1]) * 16.0,
wet,
uniform.view_params[2] * 0.5,
],
};
uniform.time[0] = self.started.elapsed().as_secs_f32();
uniform.time[1] = self.frames as f32;
self.frames = self.frames.wrapping_add(1);
@@ -269,6 +472,7 @@ impl PackStages {
let [w, h] = target.size.map(|v| v as f32);
uniform.resolution = [w, h, 1.0 / w, 1.0 / h];
queue.write_buffer(&pass.uniform, 0, bytemuck::bytes_of(&uniform));
queue.write_buffer(&pass.uniform_ext, 0, bytemuck::bytes_of(&ext));
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &target.view,
resolve_target: None,
+536 -21
View File
@@ -1,26 +1,148 @@
//! Resolution scale and FXAA (Horizon settings): the world renders into its
//! own target at the scaled size, then one full-screen pass copies or
//! anti-aliases it onto the screen, under the hand and HUD. A shader pack
//! also needs the target (its stages read the world's colour and depth).
//! Resolution scale, FXAA, and shader-pack G-buffer/shadow targets (Horizon
//! settings): the world renders into its own target at the scaled size, then
//! one full-screen pass copies or anti-aliases it onto the screen, under the
//! hand and HUD. When a shader pack is active, `Post` also maintains:
//! - `opaque_depth` (`depthtex1`/`depthtex2`): depth captured before
//! translucent terrain (water, stained glass, ice) renders;
//! - `normal` (`colortex1`/`scene_normal`) and `material`
//! (`colortex2`/`scene_material`): G-buffer surface normals and material
//! properties reconstructed from depth and scene colour;
//! - `shadow_depth` (`shadowtex0`/`shadowtex1`): the directional sun/moon
//! shadow map and its light-space `shadow_view` and `shadow_proj` matrices.
//!
//! With none of them on, the world renders straight to the screen as before.
use super::pack_stages::FrameUniform;
use glam::{Mat4, Vec3, Vec4};
const GBUFFER_WGSL: &str = r#"
struct GbufferParams {
inverse_view: mat4x4<f32>,
inverse_projection: mat4x4<f32>,
resolution: vec4<f32>,
// x: eye block light (0..1), y: eye sky light (0..1), z: wetness (0..1), w: sun elevation
env: vec4<f32>,
}
@group(0) @binding(0) var world_color: texture_2d<f32>;
@group(0) @binding(1) var world_depth: texture_depth_2d;
@group(0) @binding(2) var opaque_depth: texture_depth_2d;
@group(0) @binding(3) var nearest_sampler: sampler;
@group(0) @binding(4) var<uniform> params: GbufferParams;
struct VsOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
}
@vertex
fn vs_gbuffer(@builtin(vertex_index) i: u32) -> VsOut {
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
var out: VsOut;
out.clip = vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0);
out.uv = vec2<f32>(p.x, 1.0 - p.y);
return out;
}
struct GbufferOut {
@location(0) normal: vec4<f32>,
@location(1) material: vec4<f32>,
}
fn world_pos(uv: vec2<f32>, d: f32) -> vec3<f32> {
let v = params.inverse_projection * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0);
let view = v.xyz / max(v.w, 1e-6);
return (params.inverse_view * vec4<f32>(view, 1.0)).xyz;
}
@fragment
fn fs_gbuffer(in: VsOut) -> GbufferOut {
let d_all = textureSampleLevel(world_depth, nearest_sampler, in.uv, 0);
let d_opq = textureSampleLevel(opaque_depth, nearest_sampler, in.uv, 0);
let color = textureSampleLevel(world_color, nearest_sampler, in.uv, 0.0);
var out: GbufferOut;
if d_all <= 0.0 && d_opq <= 0.0 {
out.normal = vec4<f32>(0.5, 1.0, 0.5, 0.0);
out.material = vec4<f32>(0.0, params.env.y, 0.0, 1.0);
return out;
}
let d = select(d_all, d_opq, d_opq > 0.0);
let step_uv = params.resolution.zw;
let p0 = world_pos(in.uv, d);
let uv_r = clamp(in.uv + vec2<f32>(step_uv.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0));
let uv_l = clamp(in.uv - vec2<f32>(step_uv.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0));
let uv_d = clamp(in.uv + vec2<f32>(0.0, step_uv.y), vec2<f32>(0.0), vec2<f32>(1.0));
let uv_u = clamp(in.uv - vec2<f32>(0.0, step_uv.y), vec2<f32>(0.0), vec2<f32>(1.0));
let dr = textureSampleLevel(opaque_depth, nearest_sampler, uv_r, 0);
let dl = textureSampleLevel(opaque_depth, nearest_sampler, uv_l, 0);
let dd = textureSampleLevel(opaque_depth, nearest_sampler, uv_d, 0);
let du = textureSampleLevel(opaque_depth, nearest_sampler, uv_u, 0);
let dx = select(world_pos(uv_r, dr) - p0, p0 - world_pos(uv_l, dl), abs(dl - d) < abs(dr - d));
let dy = select(world_pos(uv_d, dd) - p0, p0 - world_pos(uv_u, du), abs(du - d) < abs(dd - d));
let raw_n = cross(dy, dx);
let n_len = length(raw_n);
let n = select(vec3<f32>(0.0, 1.0, 0.0), raw_n / max(n_len, 1e-6), n_len > 1e-6);
// Reversed depth: closer translucent geometry has larger depth than opaque geometry.
let is_translucent = select(0.0, 1.0, d_all > d_opq + 1e-5);
let luma = dot(color.rgb, vec3<f32>(0.2126, 0.7152, 0.0722));
let block_light = clamp(max(params.env.x, smoothstep(0.65, 0.98, luma)), 0.0, 1.0);
let roughness = select(clamp(0.85 - params.env.z * 0.45, 0.1, 1.0), 0.05, is_translucent > 0.5);
out.normal = vec4<f32>(n * 0.5 + 0.5, 1.0);
out.material = vec4<f32>(block_light, params.env.y, is_translucent, roughness);
return out;
}
"#;
#[repr(C)]
#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)]
struct GbufferUniform {
inverse_view: [[f32; 4]; 4],
inverse_projection: [[f32; 4]; 4],
resolution: [f32; 4],
env: [f32; 4],
}
struct WorldTarget {
size: [u32; 2],
color: wgpu::TextureView,
depth_tex: wgpu::Texture,
depth: wgpu::TextureView,
opaque_depth_tex: wgpu::Texture,
opaque_depth: wgpu::TextureView,
normal: wgpu::TextureView,
material: wgpu::TextureView,
gbuffer_group: wgpu::BindGroup,
group: wgpu::BindGroup,
opaque_captured: bool,
}
struct ShadowTarget {
resolution: u32,
depth: wgpu::TextureView,
}
pub struct Post {
layout: wgpu::BindGroupLayout,
sampler: wgpu::Sampler,
nearest: wgpu::Sampler,
copy: wgpu::RenderPipeline,
fxaa: wgpu::RenderPipeline,
gbuffer_layout: wgpu::BindGroupLayout,
gbuffer_pipeline: wgpu::RenderPipeline,
gbuffer_uniform: wgpu::Buffer,
format: wgpu::TextureFormat,
/// World resolution relative to the window (0.5..=2.0).
pub scale: f32,
pub antialias: bool,
target: Option<WorldTarget>,
shadow: Option<ShadowTarget>,
fallback_shadow: wgpu::TextureView,
fallback_color: wgpu::TextureView,
pub shadow_view: Mat4,
pub shadow_proj: Mat4,
pub shadow_distance: f32,
pub shadow_resolution: u32,
pub shadow_active: bool,
}
impl Post {
@@ -88,17 +210,169 @@ impl Post {
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let nearest = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Horizon post nearest"),
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
let gbuffer_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon gbuffer"),
source: wgpu::ShaderSource::Wgsl(GBUFFER_WGSL.into()),
});
let gbuffer_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Horizon gbuffer layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let gbuffer_pipe_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Horizon gbuffer"),
bind_group_layouts: &[Some(&gbuffer_layout)],
..Default::default()
});
let gbuffer_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Horizon gbuffer"),
layout: Some(&gbuffer_pipe_layout),
vertex: wgpu::VertexState {
module: &gbuffer_shader,
entry_point: Some("vs_gbuffer"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &gbuffer_shader,
entry_point: Some("fs_gbuffer"),
compilation_options: Default::default(),
targets: &[
Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba8Unorm,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
}),
Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba8Unorm,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
}),
],
}),
multiview_mask: None,
cache: None,
});
let gbuffer_uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon gbuffer uniform"),
size: std::mem::size_of::<GbufferUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let fallback_shadow = device
.create_texture(&wgpu::TextureDescriptor {
label: Some("Horizon fallback shadow"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default());
let fallback_color = device
.create_texture(&wgpu::TextureDescriptor {
label: Some("Horizon fallback gbuffer"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default());
Self {
copy: pipeline("fs_copy"),
fxaa: pipeline("fs_fxaa"),
layout,
sampler,
nearest,
gbuffer_layout,
gbuffer_pipeline,
gbuffer_uniform,
format,
scale: 1.0,
antialias: false,
target: None,
shadow: None,
fallback_shadow,
fallback_color,
shadow_view: Mat4::IDENTITY,
shadow_proj: Mat4::IDENTITY,
shadow_distance: 128.0,
shadow_resolution: 2048,
shadow_active: false,
}
}
/// The world's colour and depth targets this frame, or `None` to draw
/// it straight to the screen. `pack`: a shader pack runs this frame.
pub fn prepare(
@@ -109,6 +383,7 @@ impl Post {
) -> Option<(wgpu::TextureView, wgpu::TextureView)> {
if self.scale == 1.0 && !self.antialias && !pack {
self.target = None;
self.shadow_active = false;
return None;
}
let size = window.map(|v| ((v as f32 * self.scale).round() as u32).clamp(1, 8192));
@@ -118,46 +393,284 @@ impl Post {
height: size[1],
depth_or_array_layers: 1,
};
let texture = |label, format, usage| {
device
.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: extent,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
.create_view(&Default::default())
let make_tex = |label, format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: extent,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
let color = texture(
let color = make_tex(
"Scaled world",
self.format,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
);
let depth = texture(
)
.create_view(&Default::default());
let depth_tex = make_tex(
"Scaled world depth",
wgpu::TextureFormat::Depth32Float,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC,
);
let depth = depth_tex.create_view(&Default::default());
let opaque_depth_tex = make_tex(
"Opaque world depth",
wgpu::TextureFormat::Depth32Float,
wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_DST,
);
let opaque_depth = opaque_depth_tex.create_view(&Default::default());
let normal = make_tex(
"World G-buffer normal",
wgpu::TextureFormat::Rgba8Unorm,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
)
.create_view(&Default::default());
let material = make_tex(
"World G-buffer material",
wgpu::TextureFormat::Rgba8Unorm,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
)
.create_view(&Default::default());
let gbuffer_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon gbuffer"),
layout: &self.gbuffer_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&color),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&depth),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&opaque_depth),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(&self.nearest),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.gbuffer_uniform.as_entire_binding(),
},
],
});
let group = self.bind(device, &color);
self.target = Some(WorldTarget {
size,
color,
depth_tex,
depth,
opaque_depth_tex,
opaque_depth,
normal,
material,
gbuffer_group,
group,
opaque_captured: false,
});
}
if let Some(t) = &mut self.target {
t.opaque_captured = false;
}
self.target
.as_ref()
.map(|t| (t.color.clone(), t.depth.clone()))
}
/// Prepare the directional sun/moon shadow map target and compute its
/// camera-relative orthographic `shadow_view` and `shadow_proj` matrices.
pub fn prepare_shadow(
&mut self,
device: &wgpu::Device,
resolution: u32,
distance: f32,
sun_dir: Vec3,
moon_dir: Vec3,
) -> &wgpu::TextureView {
let resolution = resolution.clamp(256, 4096);
let distance = distance.clamp(16.0, 512.0);
if self
.shadow
.as_ref()
.is_none_or(|s| s.resolution != resolution)
{
let depth = device
.create_texture(&wgpu::TextureDescriptor {
label: Some("Horizon shadow map"),
size: wgpu::Extent3d {
width: resolution,
height: resolution,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default());
self.shadow = Some(ShadowTarget { resolution, depth });
}
let light_dir = if sun_dir.y >= -0.05 {
sun_dir.normalize_or_zero()
} else {
moon_dir.normalize_or_zero()
};
let dir = if light_dir.length_squared() > 1e-4 {
light_dir
} else {
Vec3::Y
};
let up = if dir.y.abs() > 0.99 { Vec3::Z } else { Vec3::Y };
self.shadow_view = Mat4::look_at_rh(dir * distance, Vec3::ZERO, up);
// Reversed-depth orthographic projection for the world's GreaterEqual
// pipelines (near maps to 1.0, far maps to 0.0), and standard 0..1
// projection for shader sampling.
self.shadow_proj = Mat4::orthographic_rh(
-distance,
distance,
-distance,
distance,
distance * 2.5,
0.05,
);
self.shadow_distance = distance;
self.shadow_resolution = resolution;
self.shadow_active = true;
&self.shadow.as_ref().expect("created above").depth
}
/// Snapshot `world_depth` into `opaque_depth` (`depthtex1`/`depthtex2`)
/// right before translucent water and weather draw.
pub fn capture_opaque_depth(&mut self, encoder: &mut wgpu::CommandEncoder) {
let Some(t) = &mut self.target else { return };
encoder.copy_texture_to_texture(
t.depth_tex.as_image_copy(),
t.opaque_depth_tex.as_image_copy(),
t.depth_tex.size(),
);
t.opaque_captured = true;
}
/// Reconstruct the G-buffer `normal` and `material` textures after the
/// world pass finishes.
pub fn build_gbuffer(
&mut self,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
frame: &FrameUniform,
eye_light: [u8; 2],
wetness: f32,
) {
let Some(t) = &mut self.target else { return };
if !t.opaque_captured {
encoder.copy_texture_to_texture(
t.depth_tex.as_image_copy(),
t.opaque_depth_tex.as_image_copy(),
t.depth_tex.size(),
);
t.opaque_captured = true;
}
let [w, h] = t.size.map(|v| v.max(1) as f32);
let uniform = GbufferUniform {
inverse_view: frame.inverse_view,
inverse_projection: frame.inverse_projection,
resolution: [w, h, 1.0 / w, 1.0 / h],
env: [
f32::from(eye_light[0]) / 15.0,
f32::from(eye_light[1]) / 15.0,
wetness,
frame.sun[1],
],
};
queue.write_buffer(&self.gbuffer_uniform, 0, bytemuck::bytes_of(&uniform));
let attachments = [
Some(wgpu::RenderPassColorAttachment {
view: &t.normal,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
}),
Some(wgpu::RenderPassColorAttachment {
view: &t.material,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
}),
];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon gbuffer"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.gbuffer_pipeline);
pass.set_bind_group(0, &t.gbuffer_group, &[]);
pass.draw(0..3, 0..1);
}
/// The world target's size, once `prepare` made one.
pub fn size(&self) -> Option<[u32; 2]> {
self.target.as_ref().map(|t| t.size)
}
/// Pre-translucent depth view (`depthtex1`/`depthtex2` / `opaque_depth`).
pub fn opaque_depth(&self) -> &wgpu::TextureView {
self.target
.as_ref()
.map_or(&self.fallback_shadow, |t| &t.opaque_depth)
}
/// Reconstructed world-space normal G-buffer view (`colortex1` / `scene_normal`).
pub fn normal(&self) -> &wgpu::TextureView {
self.target
.as_ref()
.map_or(&self.fallback_color, |t| &t.normal)
}
/// Reconstructed material/lightmap G-buffer view (`colortex2` / `scene_material`).
pub fn material(&self) -> &wgpu::TextureView {
self.target
.as_ref()
.map_or(&self.fallback_color, |t| &t.material)
}
/// Directional sun/moon shadow map view (`shadowtex0`/`shadowtex1` / `shadow_depth`).
pub fn shadow_depth(&self) -> &wgpu::TextureView {
self.shadow
.as_ref()
.map_or(&self.fallback_shadow, |s| &s.depth)
}
/// OpenGL-convention (-1..1 Z) shadow projection for Java/Iris shader packs.
pub fn gl_shadow_projection(&self) -> Mat4 {
let to_gl = Mat4::from_cols(
Vec4::X,
Vec4::Y,
Vec4::new(0.0, 0.0, -2.0, 0.0),
Vec4::new(0.0, 0.0, 1.0, 1.0),
);
to_gl * self.shadow_proj
}
/// Bindings that copy (or anti-alias) `view` onto the screen in `finish_with`.
pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
@@ -175,11 +688,13 @@ impl Post {
],
})
}
/// Draw the scaled world onto `screen`.
pub fn finish(&self, encoder: &mut wgpu::CommandEncoder, screen: &wgpu::TextureView) {
let Some(target) = &self.target else { return };
self.finish_with(encoder, screen, &target.group);
}
/// Draw what `group` binds (`bind`) onto `screen`.
pub fn finish_with(
&self,
+7 -6
View File
@@ -112,13 +112,18 @@ pub fn rows(level: Level) -> Vec<Row> {
"Waits for the display's refresh: no tearing, a little latency.",
);
let gui = v(Opt::GuiScale, None, "Size of menus and the HUD.");
let shader_pack = h(
H::ShaderPack,
High,
"Redraws the world with a pack from the shaderpacks folder. Off is vanilla.",
);
let preset = h(
H::Preset,
None,
"Sets the options below together. Changing one makes it Custom.",
);
let mut rows = match level {
Level::Simple => vec![preset, render, lod, far, fov, fps, vsync, gui],
Level::Simple => vec![preset, render, lod, far, fov, fps, vsync, gui, shader_pack],
Level::Advanced => vec![
Row::Header("Rendering"),
render,
@@ -246,11 +251,7 @@ pub fn rows(level: Level) -> Vec<Row> {
None,
"Lowers the frame rate when minimised, or idle too.",
),
h(
H::ShaderPack,
High,
"Redraws the world with a pack from the shaderpacks folder. Off is vanilla.",
),
shader_pack,
Row::Header("Preferences"),
v(Opt::ViewBobbing, None, "Sways the view while walking."),
v(Opt::ChunkFade, None, "Fades newly loaded chunks in."),
+23 -4
View File
@@ -1,9 +1,9 @@
//! Java (OptiFine/Iris) shader packs in `shaderpacks/` (docs/shader-packs.md):
//! a folder holding `shaders/`, or a `.zip`. `horizon-shaderpack` translates
//! their full-screen programs (`begin`, `prepare`, `deferred`, `composite`,
//! `final`) to WGSL, and `gfx/java_stages.rs` runs them over Horizon's world
//! as Iris runs them over its own. Geometry programs (`gbuffers_*`,
//! `shadow`) don't run yet: the world is drawn by Horizon.
//! `final`) to WGSL, and `gfx/java_stages.rs` runs them over Horizon's world,
//! G-buffers, pre-translucent depth (`depthtex1`) and directional shadow map
//! (`shadowtex0`/`shadowtex1`) as Iris runs them over its own.
use horizon_shaderpack::{
JavaPack,
pipeline::{Directives, Program, TargetSettings},
@@ -30,8 +30,10 @@ pub struct JavaFolder {
pub final_pass: Option<Program>,
/// The targets whose alternate side holds the frame's last write.
pub flipped_at_end: BTreeSet<u32>,
/// `sunPathRotation` and `eyeBrightnessHalflife`.
/// `sunPathRotation`, `eyeBrightnessHalflife`, shadow and wetness directives.
pub directives: Directives,
/// Whether this dimension's passes read directional shadow maps.
pub shadow_enabled: bool,
}
/// A loaded Java pack.
@@ -41,6 +43,8 @@ pub struct JavaPasses {
pub uniforms: CustomUniforms,
/// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`).
pub sky: SkyDirectives,
/// Decoded RGBA8 custom textures (`sampler_name` → `(width, height, rgba)`).
pub custom_textures: BTreeMap<String, (u32, u32, Vec<u8>)>,
}
impl JavaPasses {
@@ -131,11 +135,25 @@ pub fn load(
final_pass,
flipped_at_end: plan.flipped_at_end,
directives: plan.directives,
shadow_enabled: plan.shadow_enabled,
});
}
if folders.is_empty() {
return Err("no deferred, composite or final programs".into());
}
let mut custom_textures = BTreeMap::new();
for tex in properties.custom_textures() {
if let Some(bytes) = pack.files.read_bytes(&tex.path) {
match crate::shader_pack::decode_png_rgba(&bytes) {
Ok(decoded) => {
custom_textures.insert(tex.sampler, decoded);
}
Err(e) => {
log::warn!("Horizon: shader pack texture {}: {e}", tex.path);
}
}
}
}
let uniforms = properties.custom_uniforms();
for problem in &uniforms.problems {
log::warn!("Horizon: shader pack custom uniform {problem}");
@@ -144,6 +162,7 @@ pub fn load(
folders,
uniforms,
sky: properties.sky(),
custom_textures,
})
}
+309 -2
View File
@@ -864,6 +864,8 @@ pub enum Page {
Mods,
/// The shader packs in `shaderpacks/`: pick one, open the folder.
ShaderPacks,
/// Interactive options and profiles for the active shader pack.
ShaderPackOptions,
/// Horizon's graphics settings (`graphics_ui`).
Graphics,
GraphicsAdvanced,
@@ -901,6 +903,13 @@ enum Act {
/// Credits & Attribution's Credits button (WinScreen without the poem).
Credits,
CopyAgentDetails,
/// Pick and import a shader pack `.zip` or folder into `shaderpacks/`.
ImportShaderPack,
ShaderPackProfile,
ShaderPackSubscreen(String),
ShaderPackBackScreen,
ShaderPackOption(usize),
ResetShaderPackOptions,
}
enum WKind {
Button {
@@ -913,6 +922,11 @@ enum WKind {
value: f32,
opt: Opt,
},
ShaderOptionSlider {
label: Text,
value: f32,
index: usize,
},
Text {
text: Text,
color: u32,
@@ -954,6 +968,10 @@ pub enum Event {
Credits,
/// Copy how an agent connects (the AI Agent page).
CopyAgentDetails,
/// Pick and import a shader pack `.zip` or folder into `shaderpacks/`.
ImportShaderPack,
/// Reload the active shader pack after its options file changed.
ReloadShaderPack,
}
/// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after
/// the last change (`OptionInstanceSliderButton.delayedApplyAt`).
@@ -1011,6 +1029,12 @@ pub struct OptionsUi {
pub shader_pack_error: Option<(String, String)>,
/// The AI Agent page's status lines (set by the game while it shows).
pub agent_status: Vec<String>,
/// Loaded interactive configuration for the currently selected shader pack.
pub shader_pack_config: Option<crate::shader_pack::PackConfig>,
/// Classic shader option slider currently being dragged.
pub(crate) dragging_shader_option: Option<usize>,
/// Horizon shader option slider currently being dragged.
pub(crate) hdragging_shader_option: Option<usize>,
}
impl Default for OptionsUi {
fn default() -> Self {
@@ -1042,6 +1066,9 @@ impl Default for OptionsUi {
shader_packs: Default::default(),
shader_pack_error: None,
agent_status: Vec::new(),
shader_pack_config: None,
dragging_shader_option: None,
hdragging_shader_option: None,
}
}
}
@@ -1172,7 +1199,7 @@ impl OptionsUi {
}
/// Pick shader pack `i` of the folder, or turn it off when it is the
/// one running.
pub(crate) fn toggle_shader_pack(&self, s: &mut Settings, i: usize) {
pub(crate) fn toggle_shader_pack(&mut self, s: &mut Settings, i: usize) {
let Some((id, Ok(_))) = self.shader_packs.packs.get(i) else {
return;
};
@@ -1182,6 +1209,39 @@ impl OptionsUi {
} else {
id.clone()
};
self.sync_shader_pack_config(s);
}
/// Ensure `shader_pack_config` matches `s.horizon.shader_pack`.
pub fn sync_shader_pack_config(&mut self, s: &Settings) {
let id = s.horizon.shader_pack.as_str();
if id.is_empty() {
self.shader_pack_config = None;
return;
}
if self
.shader_pack_config
.as_ref()
.is_some_and(|cfg| cfg.id == id)
{
return;
}
let dir = if self.shader_packs.dir.as_os_str().is_empty() {
crate::shader_pack::folder()
} else {
self.shader_packs.dir.clone()
};
self.shader_pack_config = crate::shader_pack::PackConfig::load(&dir, id).ok();
}
/// Save the active shader pack options to `shaderpacks/<id>.txt`.
pub(crate) fn save_shader_pack_config(&self) {
if let Some(cfg) = &self.shader_pack_config {
let dir = if self.shader_packs.dir.as_os_str().is_empty() {
crate::shader_pack::folder()
} else {
self.shader_packs.dir.clone()
};
let _ = cfg.save(&dir);
}
}
pub(crate) fn shader_pack_failed(&self, id: &str) -> bool {
self.shader_pack_error
@@ -1215,6 +1275,7 @@ impl OptionsUi {
Page::Packs => "resourcePack.title",
Page::Mods => "Mods",
Page::ShaderPacks => "Shader Packs",
Page::ShaderPackOptions => "Shader Pack Settings",
Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle",
Page::Controller => "Controller Settings",
Page::PadBinds => "Controller Binds",
@@ -1587,6 +1648,121 @@ impl OptionsUi {
None,
));
}
let has_settings = !s.horizon.shader_pack.is_empty()
&& self.shader_pack_config.as_ref().is_some_and(|c| {
c.id == s.horizon.shader_pack
&& (!c.options.is_empty() || !c.profiles.is_empty())
});
if has_settings {
rows.push(Row::Buttons(
button(
0.0,
0.0,
150.0,
Text::literal("Shader Pack Settings..."),
Act::Push(Page::ShaderPackOptions),
),
Some(button(
0.0,
0.0,
150.0,
Text::literal("Import Shader Pack..."),
Act::ImportShaderPack,
)),
));
} else {
rows.push(Row::Buttons(
button(
0.0,
0.0,
310.0,
Text::literal("Import Shader Pack..."),
Act::ImportShaderPack,
),
None,
));
}
rows
}
Page::ShaderPackOptions => {
let Some(cfg) = &self.shader_pack_config else {
return vec![Row::Header("No configurable options for this shader pack")];
};
let screen = cfg.current_screen();
let mut rows = vec![Row::Note(format!("{} — {}", cfg.id, screen.label))];
if cfg.active_screen.is_some() {
rows.push(Row::Buttons(
button(
0.0,
0.0,
310.0,
Text::literal("Back to Main Screen"),
Act::ShaderPackBackScreen,
),
None,
));
}
let mut widgets = Vec::new();
for item in &screen.items {
match item {
crate::shader_pack::ScreenItem::Empty => {}
crate::shader_pack::ScreenItem::Profile => {
let label =
Text::literal(format!("Profile: {}", cfg.active_profile_label()));
widgets.push(button(0.0, 0.0, 150.0, label, Act::ShaderPackProfile));
}
crate::shader_pack::ScreenItem::Subscreen(sub, title) => {
let label = Text::literal(format!("{title}..."));
widgets.push(button(
0.0,
0.0,
150.0,
label,
Act::ShaderPackSubscreen(sub.clone()),
));
}
crate::shader_pack::ScreenItem::Option(idx) => {
if let Some(opt) = cfg.options.get(*idx) {
let label = Text::literal(format!(
"{}: {}",
opt.label,
opt.display_value()
));
if let Some(value) = opt.slider_pos() {
widgets.push(Widget {
x: 0.0,
y: 0.0,
w: 150.0,
h: 20.0,
kind: WKind::ShaderOptionSlider {
label,
value,
index: *idx,
},
list: false,
});
} else {
widgets.push(button(
0.0,
0.0,
150.0,
label,
Act::ShaderPackOption(*idx),
));
}
}
}
}
}
let mut iter = widgets.into_iter();
while let Some(mut first) = iter.next() {
if let Some(second) = iter.next() {
rows.push(Row::Buttons(first, Some(second)));
} else {
first.w = 310.0;
rows.push(Row::Buttons(first, None));
}
}
rows
}
_ => {
@@ -1599,6 +1775,9 @@ impl OptionsUi {
fn layout(&mut self, s: &Settings, w: f32, h: f32) -> (Vec<Widget>, f32, f32, f32) {
let mut out = Vec::new();
let page = self.page();
if matches!(page, Page::ShaderPacks | Page::ShaderPackOptions) {
self.sync_shader_pack_config(s);
}
let cx = (w / 2.0).floor();
if matches!(page, Page::Video | Page::Controls | Page::KeyBinds) {
self.settings_search.x = cx - 100.0;
@@ -2079,6 +2258,9 @@ impl OptionsUi {
Page::ShaderPacks => {
Some(("Open Shader Pack Folder", Act::OpenShaderPackFolder))
}
Page::ShaderPackOptions => {
Some(("Reset to Defaults", Act::ResetShaderPackOptions))
}
_ => None,
};
if let Some((label, act)) = folder {
@@ -2248,6 +2430,16 @@ impl OptionsUi {
170.0,
));
}
if let WKind::Button {
act: Act::ShaderPackOption(i),
..
} = &wd.kind
&& let Some(cfg) = &self.shader_pack_config
&& let Some(opt) = cfg.options.get(*i)
&& !opt.description.is_empty()
{
tooltip = Some(atlas.font.split(&Text::literal(&opt.description), 170.0));
}
}
match &wd.kind {
WKind::Button { label, active, act } => {
@@ -2288,6 +2480,31 @@ impl OptionsUi {
true,
);
}
WKind::ShaderOptionSlider {
label,
value,
index,
} => {
let dragging = self.dragging_shader_option == Some(*index);
if hover
&& let Some(cfg) = &self.shader_pack_config
&& let Some(opt) = cfg.options.get(*index)
&& !opt.description.is_empty()
{
tooltip = Some(atlas.font.split(&Text::literal(&opt.description), 170.0));
}
ui::slider(
batch,
atlas,
wd.x,
wd.y,
wd.w,
label,
*value,
hover || dragging,
true,
);
}
WKind::Text {
text,
color,
@@ -2502,6 +2719,21 @@ impl OptionsUi {
set_slider(opt, s, v);
events.push(Event::Changed);
}
if let Some(idx) = self.dragging_shader_option
&& let Some(wd) = widgets.iter().find(|wd| {
matches!(&wd.kind, WKind::ShaderOptionSlider { index, .. } if *index == idx)
})
{
let v = ui::slider_value(wd.x, wd.w, x);
if let Some(cfg) = &mut self.shader_pack_config
&& let Some(opt) = cfg.options.get_mut(idx)
{
opt.set_slider_pos(v);
}
self.save_shader_pack_config();
events.push(Event::Changed);
events.push(Event::ReloadShaderPack);
}
return events;
}
// Controller Binds: a click cancels the wait.
@@ -2589,6 +2821,45 @@ impl OptionsUi {
Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder),
Act::Credits => events.push(Event::Credits),
Act::CopyAgentDetails => events.push(Event::CopyAgentDetails),
Act::ImportShaderPack => events.push(Event::ImportShaderPack),
Act::ShaderPackProfile => {
if let Some(cfg) = &mut self.shader_pack_config {
cfg.cycle_profile(right);
}
self.save_shader_pack_config();
events.push(Event::Changed);
events.push(Event::ReloadShaderPack);
}
Act::ShaderPackSubscreen(sub) => {
if let Some(cfg) = &mut self.shader_pack_config {
cfg.active_screen = Some(sub);
}
self.scroll = 0.0;
}
Act::ShaderPackBackScreen => {
if let Some(cfg) = &mut self.shader_pack_config {
cfg.active_screen = None;
}
self.scroll = 0.0;
}
Act::ShaderPackOption(i) => {
if let Some(cfg) = &mut self.shader_pack_config
&& let Some(opt) = cfg.options.get_mut(i)
{
opt.cycle(right);
}
self.save_shader_pack_config();
events.push(Event::Changed);
events.push(Event::ReloadShaderPack);
}
Act::ResetShaderPackOptions => {
if let Some(cfg) = &mut self.shader_pack_config {
cfg.reset_all();
}
self.save_shader_pack_config();
events.push(Event::Changed);
events.push(Event::ReloadShaderPack);
}
Act::None => {}
}
}
@@ -2599,6 +2870,18 @@ impl OptionsUi {
set_slider(opt, s, v);
events.push(Event::Changed);
}
WKind::ShaderOptionSlider { index, .. } => {
self.dragging_shader_option = Some(index);
let v = ui::slider_value(wd.x, wd.w, x);
if let Some(cfg) = &mut self.shader_pack_config
&& let Some(opt) = cfg.options.get_mut(index)
{
opt.set_slider_pos(v);
}
self.save_shader_pack_config();
events.push(Event::Changed);
events.push(Event::ReloadShaderPack);
}
WKind::LanguageRow { code, .. } => {
if self.language_choice.as_deref() == Some(code.as_str()) {
events.extend(self.back(s));
@@ -2627,7 +2910,9 @@ impl OptionsUi {
}
// AbstractSliderButton suppresses the press sound and plays once on
// release, even if the pointer has left the widget or its value stayed.
let slider = self.dragging.take().is_some();
let slider = self.dragging.take().is_some()
|| self.dragging_shader_option.take().is_some()
|| self.hdragging_shader_option.take().is_some();
let graphics_slider = self.graphics.release();
if slider || graphics_slider {
vec![Event::ButtonClick]
@@ -2683,6 +2968,14 @@ impl OptionsUi {
/// Escape or Done: leave the current page, applying page results.
pub fn back(&mut self, s: &mut Settings) -> Vec<Event> {
let mut events = Vec::new();
if self.page() == Page::ShaderPackOptions
&& let Some(cfg) = &mut self.shader_pack_config
&& cfg.active_screen.is_some()
{
cfg.active_screen = None;
self.scroll = 0.0;
return events;
}
let page = self.stack.pop().unwrap_or(Page::Main);
self.scroll = 0.0;
self.scrollbar_drag_y = None;
@@ -3123,6 +3416,20 @@ mod tests {
false,
);
assert_eq!(s.horizon.shader_pack, "", "a second click turns it off");
let import_btn = find(&mut ui, &s, &|a| *a == Act::ImportShaderPack).unwrap();
assert_eq!(
ui.click(
&mut s,
&atlas,
import_btn.x + 1.0,
import_btn.y + 1.0,
size,
[480, 240],
false,
false,
),
vec![Event::ButtonClick, Event::ImportShaderPack]
);
let _ = std::fs::remove_dir_all(&dir);
}
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,7 @@
// Horizon shader pack prelude, api 1 (docs/shader-packs.md): placed before
// every stage's source. Bindings, the Frame uniform, the full-screen vertex
// shader and helpers that hide the renderer's reversed depth.
// Horizon shader pack prelude, api 2 (docs/shader-packs.md): placed before
// every stage's source. Bindings, the Frame and FrameExt uniforms, the
// full-screen vertex shader, G-buffer/shadow accessors and PBR/post helpers
// that hide the renderer's reversed depth.
struct Frame {
view: mat4x4<f32>,
projection: mat4x4<f32>,
@@ -19,12 +20,36 @@ struct Frame {
view_params: vec4<f32>,
dimension: vec4<f32>,
}
struct FrameExt {
previous_view: mat4x4<f32>,
previous_projection: mat4x4<f32>,
shadow_view: mat4x4<f32>,
shadow_projection: mat4x4<f32>,
shadow_inverse_view: mat4x4<f32>,
shadow_inverse_projection: mat4x4<f32>,
// xyz: previous camera world position, w: frame delta time (seconds)
previous_camera: vec4<f32>,
// x: shadow map resolution, y: shadow distance (blocks), z: sun_path_rotation (rad), w: shadow strength
shadow_params: vec4<f32>,
// x: eye block light (0..240), y: eye sky light (0..240), z: smoothed wetness (0..1), w: center linear depth
environment: vec4<f32>,
}
@group(0) @binding(0) var scene_color: texture_2d<f32>;
@group(0) @binding(1) var scene_depth: texture_depth_2d;
@group(0) @binding(2) var previous: texture_2d<f32>;
@group(0) @binding(3) var linear_sampler: sampler;
@group(0) @binding(4) var nearest_sampler: sampler;
@group(0) @binding(5) var<uniform> frame: Frame;
@group(0) @binding(6) var<uniform> frame_ext: FrameExt;
@group(0) @binding(7) var scene_normal: texture_2d<f32>;
@group(0) @binding(8) var scene_material: texture_2d<f32>;
@group(0) @binding(9) var opaque_depth: texture_depth_2d;
@group(0) @binding(10) var shadow_depth: texture_depth_2d;
@group(0) @binding(11) var shadow_sampler: sampler_comparison;
@group(0) @binding(12) var noise_texture: texture_2d<f32>;
@group(0) @binding(13) var repeat_sampler: sampler;
struct StageIn {
@builtin(position) position: vec4<f32>,
@@ -42,6 +67,10 @@ struct StageIn {
fn depth_at(uv: vec2<f32>) -> f32 {
return textureSampleLevel(scene_depth, nearest_sampler, uv, 0);
}
// The opaque world's depth at `uv` (before translucent water and stained glass).
fn opaque_depth_at(uv: vec2<f32>) -> f32 {
return textureSampleLevel(opaque_depth, nearest_sampler, uv, 0);
}
fn is_sky(depth: f32) -> bool {
return depth <= 0.0;
}
@@ -60,6 +89,70 @@ fn view_position(uv: vec2<f32>, depth: f32) -> vec3<f32> {
fn world_offset(uv: vec2<f32>, depth: f32) -> vec3<f32> {
return (frame.inverse_view * vec4(view_position(uv, depth), 1.0)).xyz;
}
// World-space surface normal at `uv` from the G-buffer (or reconstructed from depth).
fn world_normal_at(uv: vec2<f32>) -> vec3<f32> {
let encoded = textureSampleLevel(scene_normal, nearest_sampler, uv, 0.0);
if encoded.w > 0.001 {
return normalize(encoded.xyz * 2.0 - 1.0);
}
let step_uv = frame.resolution.zw;
let d0 = depth_at(uv);
let p0 = world_offset(uv, d0);
let px = world_offset(uv + vec2(step_uv.x, 0.0), depth_at(uv + vec2(step_uv.x, 0.0))) - p0;
let py = world_offset(uv + vec2(0.0, step_uv.y), depth_at(uv + vec2(0.0, step_uv.y))) - p0;
let n = cross(py, px);
let len = length(n);
if len > 1e-6 {
return n / len;
}
return vec3(0.0, 1.0, 0.0);
}
// G-buffer material data at `uv`: r = block light (0..1), g = sky light (0..1),
// b = water/translucent mask (0..1), a = roughness (0..1).
fn material_at(uv: vec2<f32>) -> vec4<f32> {
return textureSampleLevel(scene_material, nearest_sampler, uv, 0.0);
}
// Reproject a camera-relative world position into previous-frame UV and clip depth.
fn reproject_uv(world_rel: vec3<f32>) -> vec3<f32> {
let camera_delta = frame.camera_position.xyz - frame_ext.previous_camera.xyz;
let prev_rel = world_rel + camera_delta;
let clip = frame_ext.previous_projection * (frame_ext.previous_view * vec4(prev_rel, 1.0));
if clip.w <= 1e-5 {
return vec3(-1.0);
}
let ndc = clip.xyz / clip.w;
return vec3(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5, ndc.z);
}
// Sample the directional sun/moon shadow map with 5-tap PCF and normal offset bias.
// Returns 1.0 in full light and 0.0 in full shadow.
fn sample_shadow(world_rel: vec3<f32>, world_normal: vec3<f32>) -> f32 {
if frame_ext.shadow_params.w <= 0.001 {
return 1.0;
}
let dist = length(world_rel);
let max_dist = max(frame_ext.shadow_params.y, 16.0);
if dist >= max_dist {
return 1.0;
}
let light_dir = normalize(select(frame.moon.xyz, frame.sun.xyz, frame.sun.y >= -0.05));
let ndotl = max(dot(world_normal, light_dir), 0.0);
let bias_pos = world_rel + world_normal * (0.06 + 0.12 * (1.0 - ndotl));
let light_clip = frame_ext.shadow_projection * (frame_ext.shadow_view * vec4(bias_pos, 1.0));
let ndc = light_clip.xyz / max(light_clip.w, 1e-5);
let shadow_uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
if any(shadow_uv < vec2(0.002)) || any(shadow_uv > vec2(0.998)) || ndc.z <= 0.0 || ndc.z >= 1.0 {
return 1.0;
}
let texel = 1.0 / max(frame_ext.shadow_params.x, 512.0);
let ref_z = clamp(ndc.z + 0.0008, 0.0, 1.0);
var sum = textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv, ref_z);
sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv + vec2(texel, 0.0), ref_z);
sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv - vec2(texel, 0.0), ref_z);
sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv + vec2(0.0, texel), ref_z);
sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv - vec2(0.0, texel), ref_z);
let fade = smoothstep(max_dist, max_dist * 0.82, dist);
return mix(1.0, sum * 0.2, fade * frame_ext.shadow_params.w);
}
fn luminance(c: vec3<f32>) -> f32 {
return dot(c, vec3(0.2126, 0.7152, 0.0722));
}
@@ -69,3 +162,12 @@ fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
fn linear_to_srgb(c: vec3<f32>) -> vec3<f32> {
return select(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3(0.0031308));
}
// ACES fitted filmic tonemapping curve (linear HDR -> linear 0..1).
fn aces_tonemap(x: vec3<f32>) -> vec3<f32> {
let a = 2.51;
let b = 0.03;
let c = 2.43;
let d = 0.59;
let e = 0.14;
return clamp((x * (a * x + b)) / (x * (c * x + d) + e), vec3(0.0), vec3(1.0));
}
+27 -1
View File
@@ -17,7 +17,7 @@ pub mod uniforms;
use include::{IncludeGraph, Inlined};
use options::{Annotated, OptionSet, OptionValues};
use preprocess::{Environment, Preprocessed};
use properties::ShaderProperties;
use properties::{Properties, ShaderProperties};
use source::PackFiles;
use std::{
collections::{BTreeMap, BTreeSet},
@@ -154,6 +154,32 @@ impl JavaPack {
None => Ok(ShaderProperties::default()),
}
}
/// The pack's language translations (`shaders/lang/<code_lower>.lang` or
/// `en_US.lang`), mapping keys such as `option.SHADOW_QUALITY`,
/// `value.SHADOW_QUALITY.2`, `screen.LIGHTING`, and `profile.HIGH` to their
/// display labels.
pub fn translations(&self, lang_code: &str) -> BTreeMap<String, String> {
let mut out = BTreeMap::new();
let lower = lang_code.to_lowercase();
let upper = match lower.split_once('_') {
Some((l, r)) => format!("{l}_{}", r.to_uppercase()),
None => lower.clone(),
};
let mut candidates = vec!["lang/en_US.lang".to_owned(), "lang/en_us.lang".to_owned()];
if lower != "en_us" {
candidates.push(format!("lang/{lower}.lang"));
candidates.push(format!("lang/{upper}.lang"));
}
for path in candidates {
if let Some(text) = self.files.read(&path) {
for (k, v) in Properties::parse(&text).iter() {
out.insert(k.to_owned(), v.to_owned());
}
}
}
out
}
}
/// A program's name in `shaders.properties` (`world-1/composite1.fsh` is
+134 -10
View File
@@ -11,7 +11,7 @@ use crate::{
JavaPack,
options::OptionValues,
preprocess::Environment,
properties::{LEGACY_TARGETS, ShaderProperties},
properties::{Blend, LEGACY_TARGETS, ShaderProperties},
translate::{Link, Translated},
};
use std::collections::{BTreeMap, BTreeSet};
@@ -297,6 +297,10 @@ pub struct Pass {
pub mipmapped: BTreeSet<u32>,
/// `scale.<name>`: the fraction of the screen it draws.
pub scale: f32,
/// `blend.<program>` override for all outputs of this pass.
pub blend: Option<Blend>,
/// `blend.<program>.<buffer>` overrides per colour target index.
pub buffer_blends: Vec<(u32, Blend)>,
}
/// The full-screen passes of one program folder, in order, and the
@@ -319,6 +323,8 @@ pub struct Passes {
/// next frame starts unflipped.
pub flipped_at_end: BTreeSet<u32>,
pub directives: Directives,
/// Whether the folder uses shadow mapping (`shadow` program or `shadowtex*`).
pub shadow_enabled: bool,
}
/// The `const` directives of a program folder that aren't about targets
@@ -331,6 +337,28 @@ pub struct Directives {
pub sun_path_rotation: f32,
/// `eyeBrightnessHalflife`, tenths of a second: `eyeBrightnessSmooth`.
pub eye_brightness_half_life: f32,
/// `wetnessHalflife`, tenths of a second: `wetness` smoothing when raining.
pub wetness_half_life: f32,
/// `drynessHalflife`, tenths of a second: `wetness` smoothing when dry.
pub dryness_half_life: f32,
/// `centerDepthHalflife`, tenths of a second: `centerDepthSmooth`.
pub center_depth_half_life: f32,
/// `shadowMapResolution` (or `SHADOW_RES`), in pixels per side.
pub shadow_map_resolution: u32,
/// `shadowDistance`, in blocks.
pub shadow_distance: f32,
/// `shadowDistanceRenderMul` (-1 when unset).
pub shadow_distance_render_mul: f32,
/// `ambientOcclusionLevel` (0.0..=1.0).
pub ambient_occlusion_level: f32,
/// `noiseTextureResolution`, in pixels per side.
pub noise_texture_resolution: u32,
/// `shadowHardwareFiltering` / `shadowHardwareFiltering0..1`.
pub shadow_hardware_filtering: [bool; 2],
/// `shadowtex0Nearest` / `shadowtex1Nearest`.
pub shadow_nearest: [bool; 2],
/// `generateShadowMipmap` / `shadowtex0Mipmap` / `shadowtex1Mipmap`.
pub shadow_mipmap: [bool; 2],
}
impl Default for Directives {
@@ -338,6 +366,17 @@ impl Default for Directives {
Self {
sun_path_rotation: 0.0,
eye_brightness_half_life: 10.0,
wetness_half_life: 600.0,
dryness_half_life: 200.0,
center_depth_half_life: 1.0,
shadow_map_resolution: 2048,
shadow_distance: 128.0,
shadow_distance_render_mul: -1.0,
ambient_occlusion_level: 1.0,
noise_texture_resolution: 256,
shadow_hardware_filtering: [false; 2],
shadow_nearest: [false; 2],
shadow_mipmap: [false; 2],
}
}
}
@@ -348,11 +387,66 @@ impl Directives {
let mut out = Self::default();
for fragment in fragments {
for c in const_directives(fragment) {
// Java's `Float.parseFloat` takes a trailing `f`.
let value = c.value.trim_end_matches(['f', 'F']).parse::<f32>();
match (c.ty, c.key.as_str(), value) {
("float", "sunPathRotation", Ok(v)) => out.sun_path_rotation = v,
("float", "eyeBrightnessHalflife", Ok(v)) => out.eye_brightness_half_life = v,
let raw = c.value.trim_end_matches(['f', 'F']);
let fval = raw.parse::<f32>();
let ival = raw.parse::<u32>();
let bval = raw.parse::<bool>();
match (c.ty, c.key.as_str()) {
("float", "sunPathRotation") if fval.is_ok() => {
out.sun_path_rotation = fval.unwrap();
}
("float", "eyeBrightnessHalflife") if fval.is_ok() => {
out.eye_brightness_half_life = fval.unwrap();
}
("float", "wetnessHalflife") if fval.is_ok() => {
out.wetness_half_life = fval.unwrap();
}
("float", "drynessHalflife") if fval.is_ok() => {
out.dryness_half_life = fval.unwrap();
}
("float", "centerDepthHalflife") if fval.is_ok() => {
out.center_depth_half_life = fval.unwrap();
}
("float", "shadowDistance") if fval.is_ok() => {
out.shadow_distance = fval.unwrap().clamp(8.0, 1024.0);
}
("float", "shadowDistanceRenderMul") if fval.is_ok() => {
out.shadow_distance_render_mul = fval.unwrap();
}
("float", "ambientOcclusionLevel") if fval.is_ok() => {
out.ambient_occlusion_level = fval.unwrap().clamp(0.0, 1.0);
}
("int", "shadowMapResolution") if ival.is_ok() => {
out.shadow_map_resolution = ival.unwrap().clamp(64, 8192);
}
("int", "noiseTextureResolution") if ival.is_ok() => {
out.noise_texture_resolution = ival.unwrap().clamp(16, 2048);
}
("bool", "shadowHardwareFiltering") if bval.is_ok() => {
out.shadow_hardware_filtering = [bval.unwrap(); 2];
}
("bool", "shadowHardwareFiltering0") if bval.is_ok() => {
out.shadow_hardware_filtering[0] = bval.unwrap();
}
("bool", "shadowHardwareFiltering1") if bval.is_ok() => {
out.shadow_hardware_filtering[1] = bval.unwrap();
}
("bool", "shadowtexNearest" | "shadowtex0Nearest" | "shadow0MinMagNearest")
if bval.is_ok() =>
{
out.shadow_nearest[0] = bval.unwrap();
}
("bool", "shadowtex1Nearest" | "shadow1MinMagNearest") if bval.is_ok() => {
out.shadow_nearest[1] = bval.unwrap();
}
("bool", "generateShadowMipmap" | "shadowtexMipmap" | "shadowtex0Mipmap")
if bval.is_ok() =>
{
out.shadow_mipmap[0] = bval.unwrap();
}
("bool", "shadowtex1Mipmap") if bval.is_ok() => {
out.shadow_mipmap[1] = bval.unwrap();
}
_ => {}
}
}
@@ -474,21 +568,43 @@ impl JavaPack {
for name in &groups[0..2].concat() {
fragments.insert(name.clone(), fragment(name)?);
}
let shadow_enabled = ["shadow", "shadow_solid", "shadow_cutout"]
.iter()
.any(|s| exists(s))
|| sources.iter().any(|s| {
s.contains("shadowtex0")
|| s.contains("shadowtex1")
|| s.contains("watershadow")
|| s.contains("shadow2D")
});
let mut out = Passes {
targets: target_settings(sources.iter().map(String::as_str), properties),
directives: Directives::read(sources.iter().map(String::as_str)),
shadow_enabled,
..Passes::default()
};
let resolve_blends = |prog: &str| {
let blend = properties.blend(prog).and_then(Result::ok);
let buffer_blends: Vec<(u32, Blend)> = properties
.buffer_blends(prog)
.into_iter()
.filter_map(|(i, b)| Some((i, b.ok()?)))
.collect();
(blend, buffer_blends)
};
let flips = explicit_flips(properties);
let run = |group: &[String], pre: &str, flipped: &mut BTreeSet<u32>| {
*flipped = flips_pre(&flips, pre, flipped);
let mut passes = Vec::new();
for name in group {
let text = &fragments[name];
let prog = path(name);
let (blend, buffer_blends) = resolve_blends(&prog);
let pass = Pass {
program: path(name),
draw_buffers: draw_buffers(text).map_err(|e| format!("{}: {e}", path(name)))?,
program: prog.clone(),
draw_buffers: draw_buffers(text).map_err(|e| format!("{prog}: {e}"))?,
reads_alt: flipped.clone(),
mipmapped: mipmapped(text),
scale: properties
@@ -496,6 +612,8 @@ impl JavaPack {
.get(&format!("scale.{name}"))
.and_then(|v| v.split_whitespace().next()?.parse().ok())
.unwrap_or(1.0),
blend,
buffer_blends,
};
*flipped = flip_set(&pass, &flips);
passes.push(pass);
@@ -511,12 +629,16 @@ impl JavaPack {
out.composite = run(&groups[3], "composite_pre", &mut flipped)?;
out.flipped_at_end = flipped;
if exists("final") {
let prog = path("final");
let (blend, buffer_blends) = resolve_blends(&prog);
out.final_pass = Some(Pass {
program: path("final"),
program: prog,
draw_buffers: None,
reads_alt: out.flipped_at_end.clone(),
mipmapped: mipmapped(&fragment("final")?),
scale: 1.0,
blend,
buffer_blends,
});
}
Ok(out)
@@ -736,12 +858,14 @@ mod tests {
assert_eq!(Directives::read([]), Directives::default());
assert_eq!(Directives::default().eye_brightness_half_life, 10.0);
let d = Directives::read([
"const float sunPathRotation = 30.0;\nconst float eyeBrightnessHalflife = 4.0f;",
"const float sunPathRotation = 30.0;\nconst float eyeBrightnessHalflife = 4.0f;\nconst int shadowMapResolution = 4096;\nconst float shadowDistance = 192.0;",
"const float sunPathRotation = -40.0; // Complementary Unbound",
"const int sunPathRotation = 5;",
]);
assert_eq!(d.sun_path_rotation, -40.0);
assert_eq!(d.eye_brightness_half_life, 4.0);
assert_eq!(d.shadow_map_resolution, 4096);
assert_eq!(d.shadow_distance, 192.0);
}
#[test]
+74 -13
View File
@@ -358,8 +358,21 @@ impl Default for SkyDirectives {
}
}
/// A custom texture bound by `texture.<stage>.<sampler> = <path>` in
/// `shaders.properties`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CustomTexture {
/// Stage family (`composite`, `deferred`, `gbuffers`, `prepare`, `begin`),
/// or `None` when bound across all stages.
pub stage: Option<String>,
/// Sampler uniform name (`noisetex`, `colortex4`, `customTex`, ...).
pub sampler: String,
/// Path relative to `shaders/` (`textures/noise.png`).
pub path: String,
}
/// A pack's `shaders.properties`.
#[derive(Debug, Default)]
#[derive(Debug, Default, Clone)]
pub struct ShaderProperties {
/// As written: screens, sliders, profiles, feature flags.
pub original: Properties,
@@ -535,6 +548,31 @@ impl ShaderProperties {
.collect()
}
/// `texture.<stage>.<sampler> = <path>` and `texture.<sampler> = <path>`:
/// custom textures defined in `shaders.properties`.
pub fn custom_textures(&self) -> Vec<CustomTexture> {
let mut out = Vec::new();
for (k, v) in self.preprocessed.iter() {
let Some(rest) = k.strip_prefix("texture.") else {
continue;
};
let path = v.split_whitespace().next().unwrap_or("").trim();
if path.is_empty() {
continue;
}
let (stage, sampler) = match rest.split_once('.') {
Some((stage, sampler)) => (Some(stage.to_owned()), sampler.to_owned()),
None => (None, rest.to_owned()),
};
out.push(CustomTexture {
stage,
sampler,
path: path.to_owned(),
});
}
out
}
/// `uniform.*` and `variable.*`: the pack's custom uniforms.
pub fn custom_uniforms(&self) -> crate::uniforms::CustomUniforms {
crate::uniforms::CustomUniforms::parse(self.preprocessed.iter())
@@ -564,23 +602,37 @@ impl ShaderProperties {
pub fn blend(&self, program: &str) -> Option<Result<Blend, String>> {
self.preprocessed
.get(&format!("blend.{program}"))
.or_else(|| {
let short = program.rsplit('/').next()?;
self.preprocessed.get(&format!("blend.{short}"))
})
.map(parse_blend)
}
/// `blend.<program>.<buffer>`: per colour target overrides, by target index.
pub fn buffer_blends(&self, program: &str) -> Vec<(u32, Result<Blend, String>)> {
let prefix = format!("blend.{program}.");
self.preprocessed
.iter()
.filter_map(|(k, v)| {
let buffer = k.strip_prefix(&prefix)?;
let index = match LEGACY_TARGETS.iter().position(|t| *t == buffer) {
Some(i) => i as u32,
None => buffer.strip_prefix("colortex")?.parse().ok()?,
};
Some((index, parse_blend(v)))
})
.collect()
let short = program.rsplit('/').next().unwrap_or(program);
let prefixes = [format!("blend.{program}."), format!("blend.{short}.")];
let mut out = Vec::new();
for (k, v) in self.preprocessed.iter() {
let Some(buffer) = prefixes.iter().find_map(|p| k.strip_prefix(p.as_str())) else {
continue;
};
let Some(index) = LEGACY_TARGETS
.iter()
.position(|t| *t == buffer)
.map(|i| i as u32)
.or_else(|| buffer.strip_prefix("colortex")?.parse().ok())
else {
continue;
};
if let Some(existing) = out.iter_mut().find(|(i, _)| *i == index) {
existing.1 = parse_blend(v);
} else {
out.push((index, parse_blend(v)));
}
}
out
}
}
@@ -796,6 +848,7 @@ blend.gbuffers_water.gaux2 = off
blend.gbuffers_water.colortex9 = ONE ONE ONE ONE
size.buffer.colortex4 = 0.50 QUALITY
image.lightimg0 = lighttex0 rgba RGBA16F half_float false false 128 64 128
texture.composite.colortex4 = textures/noise.png
# a comment, not a directive
iris.features.optional = CUSTOM_IMAGES SSBO
";
@@ -823,6 +876,14 @@ iris.features.optional = CUSTOM_IMAGES SSBO
p.image_formats(),
[("lightimg0".to_owned(), "rgba16f".to_owned())].into()
);
assert_eq!(
p.custom_textures(),
[CustomTexture {
stage: Some("composite".into()),
sampler: "colortex4".into(),
path: "textures/noise.png".into(),
}]
);
assert_eq!(p.features(), (vec![], vec!["CUSTOM_IMAGES", "SSBO"]));
// The preprocessed read: #if picked, values expanded, spelling kept.
assert!(!p.program_enabled("composite1", &set, &values));
+18 -4
View File
@@ -63,13 +63,27 @@ impl PackFiles {
Ok(Self::Zip(files))
}
/// Raw bytes of a file relative to `shaders/` (leading `/` or `./` stripped),
/// or `None` when it doesn't exist.
pub fn read_bytes(&self, rel: &str) -> Option<Vec<u8>> {
let clean = rel
.trim()
.trim_start_matches("./")
.trim_start_matches('/')
.trim_start_matches("shaders/");
if clean.is_empty() || clean.contains("..") {
return None;
}
match self {
Self::Folder(root) => fs::read(root.join(clean)).ok(),
Self::Zip(files) => files.get(clean).cloned(),
}
}
/// A text file, or `None` when it doesn't exist. Invalid UTF-8 is
/// replaced, as packs are often saved in Latin-1.
pub fn read(&self, rel: &str) -> Option<String> {
let bytes = match self {
Self::Folder(root) => fs::read(root.join(rel)).ok()?,
Self::Zip(files) => files.get(rel)?.clone(),
};
let bytes = self.read_bytes(rel)?;
Some(String::from_utf8_lossy(&bytes).into_owned())
}
+320 -119
View File
@@ -5,8 +5,9 @@
//! patches do for the core profile, prints GLSL 450 and has naga turn that
//! into a validated module and WGSL:
//!
//! - `attribute`/`varying` become `in`/`out` with locations; matrix and array
//! varyings are split into vectors (WGSL can pass neither between stages);
//! - `attribute`/`varying` become `in`/`out` with locations; matrix, nested
//! array and struct varyings are split into vectors (WGSL can pass none of
//! them directly between stages);
//! - loose uniforms go into one std140 block (`bool`s stored as `int`);
//! - `sampler2D` & co. become a texture and a sampler binding, rebuilt as
//! `sampler2D(t, s)` where used, also through function parameters, and not
@@ -16,13 +17,16 @@
//! (`vaPosition`, `modelViewMatrix`, ...) are declared;
//! - legacy texture calls are renamed, `shadow2D` returns a `vec4` again and a
//! swizzled shadow lookup is widened first (naga has no scalar swizzle);
//! - vertex and compute `texture(s, uv)` calls without an explicit LOD become
//! `textureLod(s, uv, 0.0)` so naga doesn't reject implicit derivatives;
//! - global initialisers run at the start of `main` (drivers accept
//! non-constant ones), unsized global arrays are sized from them;
//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none);
//! - what naga refuses and drivers accept: `%` goes through overloads (naga
//! won't take `ivec2 % int`), `sqrt` of a negative constant isn't folded,
//! constants naga can't fold (`?:`, `mix`) become globals set in `main`,
//! and 16/8-bit types are their 32-bit ones.
//! won't take `ivec2 % int`), `mat2(vec4)` goes through `iris_mat2`, `1 << 31`
//! shifts as unsigned before casting back to `int`, `sqrt` of a negative
//! constant isn't folded, constants naga can't fold (`?:`, `mix`, `<<`)
//! become globals set in `main`, and 16/8-bit types are their 32-bit ones.
//!
//! The programs of one pass share a [`Link`], so their locations, bindings and
//! uniform block agree.
@@ -238,6 +242,18 @@ vec3 iris_modf(vec3 x, out vec3 i) { i = trunc(x); return x - i; }
vec4 iris_modf(vec4 x, out vec4 i) { i = trunc(x); return x - i; }
";
/// Overloaded `mat2` constructor helper: drivers accept `mat2(vec4)` (Bloop),
/// which naga's GLSL front end refuses.
const MAT2_HELPERS: &str = "\
mat2 iris_mat2(float x) { return mat2(x); }
mat2 iris_mat2(vec2 a, vec2 b) { return mat2(a, b); }
mat2 iris_mat2(float a, float b, float c, float d) { return mat2(a, b, c, d); }
mat2 iris_mat2(vec4 v) { return mat2(v.xy, v.zw); }
mat2 iris_mat2(mat2 m) { return m; }
mat2 iris_mat2(mat3 m) { return mat2(m); }
mat2 iris_mat2(mat4 m) { return mat2(m); }
";
/// A fragment output narrower than four channels (`out vec3 color`,
/// Steadfast's `final`): the four-channel type it is written through and the
/// epilogue line that fills it, with alpha 1 and the rest 0. `None` when the
@@ -376,69 +392,62 @@ pub fn translate(
let wgsl =
naga::back::wgsl::write_string(&module, &info, naga::back::wgsl::WriterFlags::empty())
.map_err(|e| e.to_string())?;
let interface = std::mem::take(&mut legaliser.interface);
Ok(Translated {
glsl,
module,
info,
wgsl,
interface,
interface: legaliser.interface,
})
}
/// The GLSL built-ins naga's constant evaluator folds (`MathFunction`s it
/// implements), besides type constructors.
/// Built-in functions naga folds in `const` initialisers.
const FOLDABLE: &[&str] = &[
"abs",
"acos",
"acosh",
"asin",
"asinh",
"atan",
"atanh",
"ceil",
"clamp",
"cos",
"cosh",
"cross",
"radians",
"degrees",
"sin",
"cos",
"tan",
"asin",
"acos",
"atan",
"pow",
"exp",
"log",
"exp2",
"log2",
"sqrt",
"inversesqrt",
"abs",
"sign",
"floor",
"trunc",
"round",
"ceil",
"fract",
"mod",
"min",
"max",
"clamp",
"step",
"length",
"distance",
"dot",
"exp",
"exp2",
"floor",
"fma",
"fract",
"inversesqrt",
"length",
"log",
"log2",
"max",
"min",
"cross",
"normalize",
"pow",
"radians",
"round",
"sign",
"sin",
"sinh",
"sqrt",
"step",
"tan",
"tanh",
"trunc",
];
/// Whether a constant's initialisers need what naga can't fold and drivers
/// do: a `?:`, another built-in (Bliss's `mix`), or a constant that had to
/// become a global (`runtime`).
fn constructor(name: &str) -> bool {
["bool", "int", "uint", "float", "double"].contains(&name)
|| ["vec", "ivec", "uvec", "bvec", "dvec", "mat", "dmat"]
.iter()
.any(|p| name.starts_with(p))
}
/// Whether `list` has an initialiser naga's constant folder refuses (`?:`,
/// `mix`, `smoothstep`, `1 << 31`, or a reference to a constant already turned
/// into a global).
fn needs_runtime(list: &ast::InitDeclaratorList, runtime: &HashSet<String>) -> bool {
let constructor = |name: &str| {
let n = name.trim_start_matches(['i', 'u', 'b', 'd']);
matches!(name, "float" | "int" | "uint" | "bool" | "double")
|| n.starts_with("vec")
|| n.starts_with("mat")
};
let expr = |e: &ast::Expr| {
fn walk(e: &ast::Expr, f: &dyn Fn(&ast::Expr) -> bool) -> bool {
use ast::ExprData as E;
@@ -454,6 +463,14 @@ fn needs_runtime(list: &ast::InitDeclaratorList, runtime: &HashSet<String>) -> b
}
walk(e, &|e| match &e.content {
ast::ExprData::Ternary(..) => true,
ast::ExprData::Binary(op, _, _)
if matches!(
op.content,
ast::BinaryOpData::LShift | ast::BinaryOpData::RShift
) =>
{
true
}
ast::ExprData::Variable(v) => runtime.contains(v.as_str()),
ast::ExprData::FunCall(f, _) => {
callee(f).is_some_and(|c| !constructor(&c) && !FOLDABLE.contains(&c.as_str()))
@@ -503,6 +520,9 @@ enum Local {
Sampler(&'static str),
}
/// A struct field `(type_name, field_name, array_suffix)`.
type StructField = (String, String, String);
struct Legaliser<'a> {
stage: Stage,
link: &'a mut Link,
@@ -515,6 +535,8 @@ struct Legaliser<'a> {
/// User functions → indices of their sampler parameters.
sampler_params: HashMap<String, BTreeSet<usize>>,
functions: HashSet<String>,
/// User structs → their fields `(ty, name, array)` (for struct varyings).
structs: HashMap<String, Vec<StructField>>,
scopes: Vec<HashMap<String, Local>>,
/// Declarations before the program (bindings, block, inputs, outputs).
header: Vec<String>,
@@ -528,10 +550,11 @@ struct Legaliser<'a> {
errors: Vec<String>,
/// Inside a constant initialiser: no helper calls there.
constant: bool,
/// The program uses `%` ([`modulo_helpers`]) or `iris_sqrt`: their
/// helpers go in.
/// The program uses `%` ([`modulo_helpers`]), `iris_sqrt` or `iris_mat2`:
/// their helpers go in.
modulo: bool,
nan: bool,
mat2_ctor: bool,
/// Constants turned into globals ([`needs_runtime`]).
runtime_constants: HashSet<String>,
}
@@ -634,6 +657,38 @@ fn array_text(a: &Option<ast::ArraySpecifier>) -> String {
.collect()
}
/// Parse one or more `[N]` dimensions (`[9][9]` → `Some(vec![9, 9])`).
fn array_dims(array: &str) -> Option<Vec<usize>> {
if array.is_empty() {
return Some(Vec::new());
}
let mut dims = Vec::new();
let mut rest = array.trim();
while !rest.is_empty() {
let inner = rest.strip_prefix('[')?;
let (num, tail) = inner.split_once(']')?;
dims.push(num.trim().parse::<usize>().ok()?);
rest = tail.trim();
}
Some(dims)
}
/// Expand multi-dimensional indices `dims` into `(key_suffix, expr_suffix)`
/// pairs (`[2, 2]` → `("#0#0", "[0][0]")`, `("#0#1", "[0][1]")`, ...).
fn expand_dims(dims: &[usize]) -> Vec<(String, String)> {
let mut out = vec![(String::new(), String::new())];
for &n in dims {
let mut next = Vec::with_capacity(out.len() * n);
for (k, e) in &out {
for i in 0..n {
next.push((format!("{k}#{i}"), format!("{e}[{i}]")));
}
}
out = next;
}
out
}
/// The element count of `T[](a, b, c)`.
fn constructor_len(init: &Option<ast::Initializer>) -> Option<usize> {
match &init.as_ref()?.content {
@@ -718,6 +773,7 @@ impl<'a> Legaliser<'a> {
sampler_vars: HashSet::new(),
sampler_params: HashMap::new(),
functions: HashSet::new(),
structs: HashMap::new(),
scopes: Vec::new(),
header: Vec::new(),
prologue: Vec::new(),
@@ -728,14 +784,43 @@ impl<'a> Legaliser<'a> {
constant: false,
modulo: false,
nan: false,
mat2_ctor: false,
runtime_constants: HashSet::new(),
}
}
fn record_struct(&mut self, spec: &ast::StructSpecifier) {
let Some(name) = &spec.name else { return };
let mut fields = Vec::new();
for field in &spec.fields {
let base_ty = type_text(&field.ty);
let ty_arr = array_text(&field.ty.array_specifier);
for id in &field.identifiers {
let arr = format!("{ty_arr}{}", array_text(&id.array_spec));
fields.push((base_ty.clone(), id.ident.as_str().to_owned(), arr));
}
}
self.structs.insert(name.as_str().to_owned(), fields);
}
fn unit(&mut self, unit: &mut ast::TranslationUnit) -> Result<(), String> {
// Functions and their sampler parameters first: calls may precede
// definitions through prototypes.
// Functions, their sampler parameters, and struct definitions first.
for ed in &unit.0 {
if let ast::ExternalDeclarationData::Declaration(d) = &ed.content {
match &d.content {
ast::DeclarationData::InitDeclaratorList(list) => {
if let ast::TypeSpecifierNonArrayData::Struct(s) =
&list.head.ty.ty.ty.content
{
self.record_struct(s);
}
}
ast::DeclarationData::TypeOnly(q) => {
let _ = q;
}
_ => {}
}
}
let proto = match &ed.content {
ast::ExternalDeclarationData::FunctionDefinition(f) => &f.prototype,
ast::ExternalDeclarationData::Declaration(d) => match &d.content {
@@ -812,6 +897,22 @@ impl<'a> Legaliser<'a> {
}
fn global_list(&mut self, list: &mut ast::InitDeclaratorList) -> Result<bool, String> {
// If a standalone `struct S { ... };` has no declarator names, keep it
// in the header so varyings of type `S` can declare `S varname;` there.
if list.head.name.is_none()
&& list.tail.is_empty()
&& matches!(
list.head.ty.ty.ty.content,
ast::TypeSpecifierNonArrayData::Struct(_)
)
{
let mut text = String::new();
let decl = ast::DeclarationData::InitDeclaratorList(list.clone()).into_node();
show_declaration(&mut text, &decl, &mut FormattingState::default())
.map_err(|e| e.to_string())?;
self.header.push(text.trim().to_owned());
return Ok(false);
}
let qualifier = list.head.ty.qualifier.clone();
let storage = storage(&qualifier);
let has = |s: ast::StorageQualifierData| storage.contains(&s);
@@ -939,32 +1040,34 @@ impl<'a> Legaliser<'a> {
.find(|(k, _)| k == "location")
.and_then(|(_, v)| v?.parse().ok());
for (i, (name, array)) in names.iter().enumerate() {
let full = format!("{ty}{ty_array}");
let full_array = format!("{ty_array}{array}");
if input {
let at = Link::location(&mut self.link.attributes, name);
self.header
.push(format!("layout(location = {at}) in {full} {name}{array};"));
self.header.push(format!(
"layout(location = {at}) in {ty} {name}{full_array};"
));
self.interface.attributes.insert(name.clone());
} else if !varying {
let at = explicit
.map(|l: u32| l + i as u32)
.unwrap_or_else(|| self.next_output());
if let (Some(widened), "") = (widen_output(&full, name), array.as_str()) {
if let (Some(widened), "") = (widen_output(&ty, name), full_array.as_str()) {
// GL fills the missing channels of a narrow output;
// wgpu wants every channel of the target written.
let (wide, fill) = widened;
self.header.push(format!("{full} {name};"));
self.header.push(format!("{ty} {name};"));
self.header.push(format!(
"layout(location = {at}) out {wide} iris_out_{name};"
));
self.epilogue.push(fill);
} else {
self.header
.push(format!("layout(location = {at}) out {full} {name}{array};"));
self.header.push(format!(
"layout(location = {at}) out {ty} {name}{full_array};"
));
}
self.interface.outputs.insert(at, name.clone());
} else {
self.varying(dir, &interp, &full, name, array);
self.varying(dir, &interp, &ty, name, &full_array);
}
}
return Ok(false);
@@ -1001,64 +1104,106 @@ impl<'a> Legaliser<'a> {
.unwrap()
}
/// One varying: matrices and arrays split into vectors that a private
/// global of the original type is packed from or into.
fn varying(&mut self, dir: &str, interp: &str, ty: &str, name: &str, array: &str) {
/// Emit scalar/vector/matrix varying leaves for an expression `expr_path`
/// with key `key_prefix`.
fn varying_leaf(&mut self, dir: &str, interp: &str, ty: &str, key: &str, expr_path: &str) {
if let Some(fields) = self.structs.get(ty).cloned() {
for (f_ty, f_name, f_arr) in fields {
let sub_key = format!("{key}#{f_name}");
let sub_expr = format!("{expr_path}.{f_name}");
self.varying_composite(dir, interp, &f_ty, &sub_key, &sub_expr, &f_arr);
}
return;
}
if let Some((cols, column)) = matrix_columns(ty) {
let flat = if is_integer(&column) && !interp.contains("flat") {
"flat "
} else {
""
};
let mut columns = Vec::new();
for c in 0..cols {
let c_key = format!("{key}#{c}");
let at = Link::location(&mut self.link.varyings, &c_key);
let part = c_key.replace('#', "_iris");
self.header.push(format!(
"layout(location = {at}) {flat}{interp}{dir} {column} {part};"
));
if dir == "out" {
self.epilogue.push(format!("{part} = {expr_path}[{c}];"));
}
columns.push(part);
}
if dir == "in" {
self.prologue
.push(format!("{expr_path} = {ty}({});", columns.join(", ")));
}
return;
}
let flat = if is_integer(ty) && !interp.contains("flat") {
"flat "
} else {
""
};
let count: Option<usize> = array
.strip_prefix('[')
.and_then(|a| a.strip_suffix(']'))
.and_then(|n| n.parse().ok());
let parts: Vec<(String, String, String)> = match (matrix_columns(ty), count) {
(Some((cols, column)), None) => (0..cols)
.map(|c| {
(
format!("{name}#{c}"),
column.clone(),
format!("{name}[{c}]"),
)
})
.collect(),
(None, Some(n)) => (0..n)
.map(|e| (format!("{name}#{e}"), ty.to_owned(), format!("{name}[{e}]")))
.collect(),
(None, None) => {
let at = Link::location(&mut self.link.varyings, name);
self.header.push(format!(
"layout(location = {at}) {flat}{interp}{dir} {ty} {name};"
));
return;
}
(Some(_), Some(_)) => {
self.errors.push(format!(
"varying {name}: arrays of matrices are not supported"
));
return;
}
let at = Link::location(&mut self.link.varyings, key);
let part = key.replace('#', "_iris");
self.header.push(format!(
"layout(location = {at}) {flat}{interp}{dir} {ty} {part};"
));
if dir == "out" {
self.epilogue.push(format!("{part} = {expr_path};"));
} else {
self.prologue.push(format!("{expr_path} = {part};"));
}
}
fn varying_composite(
&mut self,
dir: &str,
interp: &str,
ty: &str,
key: &str,
expr_path: &str,
array: &str,
) {
let Some(dims) = array_dims(array) else {
self.errors
.push(format!("varying {expr_path}: unsupported array `{array}`"));
return;
};
self.header.push(format!("{ty} {name}{array};"));
let mut columns = Vec::new();
for (key, part_ty, element) in &parts {
let at = Link::location(&mut self.link.varyings, key);
let part = key.replace('#', "_iris");
self.header.push(format!(
"layout(location = {at}) {flat}{interp}{dir} {part_ty} {part};"
));
if dir == "out" {
self.epilogue.push(format!("{part} = {element};"));
} else if count.is_some() {
self.prologue.push(format!("{element} = {part};"));
if dims.is_empty() {
self.varying_leaf(dir, interp, ty, key, expr_path);
} else {
for (k_suf, e_suf) in expand_dims(&dims) {
self.varying_leaf(
dir,
interp,
ty,
&format!("{key}{k_suf}"),
&format!("{expr_path}{e_suf}"),
);
}
columns.push(part);
}
if dir == "in" && count.is_none() {
self.prologue
.push(format!("{name} = {ty}({});", columns.join(", ")));
}
/// One varying: matrices, arrays (including multi-dimensional `vec3[9][9]`)
/// and structs (`CloudsParameters`) split into vectors that a private
/// global of the original type is packed from or into.
fn varying(&mut self, dir: &str, interp: &str, ty: &str, name: &str, array: &str) {
if array.is_empty() && matrix_columns(ty).is_none() && !self.structs.contains_key(ty) {
let flat = if is_integer(ty) && !interp.contains("flat") {
"flat "
} else {
""
};
let at = Link::location(&mut self.link.varyings, name);
self.header.push(format!(
"layout(location = {at}) {flat}{interp}{dir} {ty} {name};"
));
return;
}
self.header.push(format!("{ty} {name}{array};"));
self.varying_composite(dir, interp, ty, name, name, array);
}
fn sized(&mut self, list: &mut ast::InitDeclaratorList) {
@@ -1404,13 +1549,30 @@ impl<'a> Legaliser<'a> {
self.expr(a);
self.expr(b);
self.modulo = true;
let (a, b) = (
std::mem::replace(&mut **a, var("_")),
std::mem::replace(&mut **b, var("_")),
);
*e = call("iris_mod", vec![a, b]);
let lhs = std::mem::replace(&mut **a, var("_"));
let rhs = std::mem::replace(&mut **b, var("_"));
*e = call("iris_mod", vec![lhs, rhs]);
}
E::Assignment(a, op, b) if op.content == ast::AssignmentOpData::Mod => {
E::Binary(op, a, b)
if op.content == ast::BinaryOpData::LShift
&& matches!(a.content, E::IntConst(_))
&& matches!(b.content, E::IntConst(n) if n >= 31) =>
{
self.expr(a);
self.expr(b);
let lhs = std::mem::replace(&mut **a, var("_"));
let rhs = std::mem::replace(&mut **b, var("_"));
let shifted = ast::ExprData::Binary(
ast::BinaryOpData::LShift.into_node(),
Box::new(call("uint", vec![lhs])),
Box::new(call("uint", vec![rhs])),
)
.into_node();
*e = call("int", vec![shifted]);
}
E::Assignment(a, op, b)
if op.content == ast::AssignmentOpData::Mod && !self.constant =>
{
self.expr(a);
self.expr(b);
self.modulo = true;
@@ -1538,17 +1700,53 @@ impl<'a> Legaliser<'a> {
if self.functions.contains(&name) {
return;
}
// `mat2(vec4)` (Bloop): naga refuses 1-argument `mat2` from a `vec4`.
if name == "mat2"
&& !self.constant
&& args.len() == 1
&& !matches!(
args[0].content,
ast::ExprData::FloatConst(_)
| ast::ExprData::IntConst(_)
| ast::ExprData::UIntConst(_)
| ast::ExprData::DoubleConst(_)
)
{
*f = ast::FunIdentifierData::Expr(Box::new(var("iris_mat2"))).into_node();
self.mat2_ctor = true;
return;
}
// `sqrt(-1.0)`, Bloop's NaN: naga folds it and fails, drivers give NaN.
if name == "sqrt" && !self.constant && args.len() == 1 && negative_constant(&args[0]) {
*f = ast::FunIdentifierData::Expr(Box::new(var("iris_sqrt"))).into_node();
self.nan = true;
return;
}
let mut target_name = name.as_str();
if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) {
*f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node();
target_name = new;
} else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) {
let args = std::mem::take(args);
*e = call("vec4", vec![call(new, args)]);
return;
}
// In vertex and compute shaders, `texture(sampler, coord)` uses implicit
// derivatives that WGSL/naga forbid outside fragment shaders (Bliss):
// rewrite 2-argument non-shadow `texture(s, uv)` to `textureLod(s, uv, 0.0)`.
if self.stage != Stage::Fragment && target_name == "texture" && args.len() == 2 {
let is_shadow = match &args[0].content {
ast::ExprData::FunCall(g, _) => {
callee(g).and_then(|c| opaque(&c)).is_some_and(|o| o.3)
}
_ => false,
};
if !is_shadow {
if let ast::ExprData::FunCall(f, args) = &mut e.content {
*f = ast::FunIdentifierData::Expr(Box::new(var("textureLod"))).into_node();
args.push(ast::ExprData::FloatConst(0.0).into_node());
}
}
}
}
@@ -1589,6 +1787,9 @@ impl<'a> Legaliser<'a> {
if self.nan {
out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n");
}
if self.mat2_ctor {
out.push_str(MAT2_HELPERS);
}
if !self.link.uniforms.is_empty() {
out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n");
for (_, decl) in &self.link.uniforms {
+39 -2
View File
@@ -292,14 +292,48 @@ fn reports_errors_with_their_place() {
/// What naga refuses and drivers accept: `vec % scalar` (Noble), `sqrt` of
/// a negative constant (Bloop's NaN), constants naga can't fold (Bliss's
/// `?:`, `mix`), and 16-bit types (Noble on NVIDIA).
/// `?:`, `mix`), 16-bit types (Noble on NVIDIA), `mat2(vec4)` (Bloop),
/// `1 << 31` (Rethinking Voxels), vertex `texture2D` without LOD (Bliss),
/// nested array varyings (Noble), and struct varyings (Photon).
#[test]
fn legalises_what_naga_refuses() {
let mut link = Link::default();
let vs = run(
Stage::Vertex,
"uniform sampler2D colortex0;
struct CloudsParameters {
vec3 color;
float density;
};
varying CloudsParameters clouds;
varying vec3 grid[2][2];
void main() {
vec4 s = texture2D(colortex0, vec2(0.5));
clouds.color = s.rgb;
clouds.density = s.a;
grid[0][0] = s.rgb;
grid[0][1] = s.gbr;
grid[1][0] = s.brg;
grid[1][1] = vec3(1.0);
gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
}
",
&mut link,
)
.unwrap();
reparse(&vs.wgsl).unwrap();
let fs = run(
Stage::Fragment,
"uniform vec2 uv;
struct CloudsParameters {
vec3 color;
float density;
};
varying CloudsParameters clouds;
varying vec3 grid[2][2];
const int RES = 256 % 100;
const int SIGN_BIT = 1 << 31;
const vec3 TARGET = length(vec3(1.0)) < 0.001 ? vec3(0.0) : normalize(vec3(1.0));
const vec3 TINT = mix(TARGET, vec3(1.0), 0.5);
const vec3 HALF = TINT * 0.5;
@@ -309,7 +343,9 @@ void main() {
ivec2 texel = ivec2(uv) % RES;
texel %= 7;
uint packed = packFloat2x16(f16vec2(HALF.xy));
gl_FragColor = vec4(vec2(texel), float(pack(packed).x), nan());
mat2 rot = mat2(vec4(1.0, 0.0, 0.0, 1.0));
vec2 r = rot * vec2(clouds.density, float(SIGN_BIT != 0));
gl_FragColor = vec4(vec2(texel) + r + clouds.color.xy + grid[1][0].xy, float(pack(packed).x), nan());
}
",
&mut link,
@@ -325,6 +361,7 @@ void main() {
"uvec2 pack(uint v)",
"return iris_sqrt(-1.);",
"uint packed = packHalf2x16(vec2(HALF.xy));",
"iris_mat2(",
] {
assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl);
}
+10 -10
View File
@@ -13,16 +13,16 @@ Both are off by default. With no pack selected the renderer draws exactly what i
| Part | State |
| --- | --- |
| Renderer layout (below) | today's code |
| Horizon shader packs: `composite` stage, uniforms, hot reload, Shader Packs page | done (the page: list, pick, open the folder) |
| Horizon shader packs: `deferred`, `gbuffer`, `shadow` stages, custom textures | planned |
| Java shader packs: preprocessing + GLSL parse coverage | spike done: 450 of 470 programs reach valid WGSL (below) |
| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros, JCPP's `#if` and `#define` rules) | done: every program of the three test packs preprocesses; ten packs tested (Compatibility, below) |
| Java shader packs: GLSL → WGSL (`horizon_shaderpack::translate`: syntax-tree legaliser, naga) | done: the 464 programs the three test packs enable by default translate (below) |
| Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes) | done, no screen yet: read like Iris for the three test packs |
| Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips) | done: planned for the three test packs |
| Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below) |
| Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done for the full-screen passes (below) |
| Java shader packs: `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned |
| Horizon shader packs: `composite`, `deferred`, `gbuffer`, `shadow`, `final` stages (API 2), uniforms, custom textures, hot reload | done (`examples/shaderpacks/horizon-ultra` + `horizon-sample`) |
| Shader Packs UI: import (`.zip`/folder dialog + drag-and-drop), profiles, sub-screens, sliders, toggles, reset to defaults | done (Horizon & Classic Video/Graphics settings) |
| Real-time shadow map pass (`"Horizon shadow"`, `shadowtex0/1`, `shadowModelView`, `shadowProjection`) & pre-translucent depth (`depthtex1/2`) | done |
| G-buffer normal & material pass (`"Horizon gbuffer"`, `scene_normal`, `scene_material`, `colortex1..3` initialization) | done |
| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros, JCPP's `#if` and `#define` rules, `.lang` files) | done: ten packs tested (Compatibility, below) |
| Java shader packs: GLSL → WGSL (`horizon_shaderpack::translate`: syntax-tree legaliser, naga, 2D array & struct varyings, vertex `textureLod`, `mat2(vec4)`, `1 << 31` shifts) | done |
| Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes, custom textures) | done, wired to UI and GPU passes |
| Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips, blend state) | done |
| Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | done: with shadow maps, `depthtex1/2`, custom PNG textures, GL blend modes, `wetness`, `centerDepthSmooth` |
| Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done |
## How the renderer draws a frame today
@@ -0,0 +1,13 @@
MIT License
Copyright (c) 2026 Horizon contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
@@ -0,0 +1,134 @@
# Horizon Ultra: multi-pass API 2 WGSL shader pack with PCF directional shadows,
# G-buffer GTAO, water SSR & absorption, volumetric godrays, HDR bloom and ACES tonemapping.
[pack]
name = "Horizon Ultra"
description = "PCF sun/moon shadows, GTAO, water reflections, volumetric godrays, bloom and ACES filmic tonemapping."
authors = ["Horizon contributors"]
version = "2.0.0"
license = "MIT"
api = 2
[[stage]]
kind = "deferred"
shader = "shaders/deferred_lighting.wgsl"
format = "rgba16float"
[[stage]]
kind = "composite"
shader = "shaders/water_reflections.wgsl"
format = "rgba16float"
[[stage]]
kind = "composite"
shader = "shaders/bloom_godrays.wgsl"
scale = 0.5
format = "rgba16float"
mipmap = true
[[stage]]
kind = "final"
shader = "shaders/final_tonemap.wgsl"
[profiles.low]
shadows = false
ao_strength = 0.25
water_ssr = false
godrays = false
bloom_strength = 0.15
tonemap_aces = true
vignette = false
[profiles.medium]
shadows = true
shadow_strength = 0.70
ao_strength = 0.50
water_ssr = true
godrays = true
bloom_strength = 0.25
tonemap_aces = true
vignette = true
[profiles.high]
shadows = true
shadow_strength = 0.85
ao_strength = 0.75
water_ssr = true
godrays = true
bloom_strength = 0.35
tonemap_aces = true
vignette = true
[profiles.ultra]
shadows = true
shadow_strength = 1.0
ao_strength = 1.0
water_ssr = true
godrays = true
bloom_strength = 0.45
tonemap_aces = true
vignette = true
[options.shadows]
label = "Directional Shadows"
description = "Cast real-time sun and moon PCF shadows across terrain and entities."
default = true
[options.shadow_strength]
label = "Shadow Strength"
description = "Intensity of directional sun and moon shadows."
default = 0.85
min = 0.0
max = 1.0
step = 0.05
[options.ao_strength]
label = "Ambient Occlusion (GTAO)"
description = "Screen-space horizon ambient occlusion in corners and crevices."
default = 0.75
min = 0.0
max = 1.5
step = 0.05
[options.water_ssr]
label = "Water Reflections & Refraction"
description = "Screen-space sky and terrain reflections on water and translucent surfaces."
default = true
[options.godrays]
label = "Volumetric Godrays"
description = "Atmospheric light shafts cast through trees and terrain towards the sun."
default = true
[options.bloom_strength]
label = "HDR Bloom"
description = "Soft glow around bright sky, lava, torches and emissive blocks."
default = 0.35
min = 0.0
max = 1.0
step = 0.05
[options.exposure]
label = "Exposure"
description = "Overall scene exposure multiplier before filmic tonemapping."
default = 1.10
min = 0.5
max = 2.0
step = 0.05
[options.saturation]
label = "Color Saturation"
description = "Color vibrancy of the final tonemapped image."
default = 1.12
min = 0.0
max = 2.0
step = 0.05
[options.tonemap_aces]
label = "ACES Filmic Tonemap"
description = "Apply ACES fitted filmic curve to preserve highlight detail."
default = true
[options.vignette]
label = "Cinematic Vignette"
description = "Subtle darkening at the edges of the viewport."
default = true
@@ -0,0 +1,61 @@
// Stage 3 (Composite, half-resolution): HDR bloom extraction + 9-tap tent filter
// and radial volumetric light shafts (godrays) towards the sun/moon.
override godrays: bool = true;
override bloom_strength: f32 = 0.35;
@fragment fn fs_main(in: StageIn) -> @location(0) vec4<f32> {
let base = textureSampleLevel(previous, linear_sampler, in.uv, 0.0).rgb;
let texel = frame.resolution.zw * 2.0;
// 9-tap soft bloom filter around bright highlights.
var bloom = vec3(0.0);
if bloom_strength > 0.001 {
let offsets = array<vec2<f32>, 9>(
vec2(0.0, 0.0),
vec2(1.0, 0.0),
vec2(-1.0, 0.0),
vec2(0.0, 1.0),
vec2(0.0, -1.0),
vec2(1.0, 1.0),
vec2(-1.0, 1.0),
vec2(1.0, -1.0),
vec2(-1.0, -1.0),
);
let weights = array<f32, 9>(0.25, 0.125, 0.125, 0.125, 0.125, 0.0625, 0.0625, 0.0625, 0.0625);
for (var i = 0u; i < 9u; i++) {
let sample_c = textureSampleLevel(previous, linear_sampler, in.uv + offsets[i] * texel, 0.0).rgb;
let lum = luminance(sample_c);
let bright = max(lum - 0.72, 0.0) / max(lum, 1e-4);
bloom += sample_c * bright * weights[i];
}
}
// Radial volumetric godrays cast from the sun's screen projection.
var shafts = vec3(0.0);
if godrays && frame.camera_state.x == 0.0 && frame.dimension.y > 0.5 {
let sun_clip = frame.projection * (frame.view * vec4(frame.sun.xyz * 128.0, 1.0));
if sun_clip.w > 0.0 {
let sun_ndc = sun_clip.xy / sun_clip.w;
let sun_uv = vec2(sun_ndc.x * 0.5 + 0.5, 0.5 - sun_ndc.y * 0.5);
let delta = (sun_uv - in.uv) / 12.0;
var uv_Cursor = in.uv;
var transmittance = 0.0;
var decay = 1.0;
for (var s = 0u; s < 12u; s++) {
uv_Cursor += delta;
let sample_uv = clamp(uv_Cursor, vec2(0.001), vec2(0.999));
if is_sky(depth_at(sample_uv)) {
transmittance += decay;
}
decay *= 0.92;
}
let ray = normalize(world_offset(in.uv, 1e-5));
let sun_facing = pow(max(dot(ray, frame.sun.xyz), 0.0), 4.0);
let sunset = smoothstep(-0.1, 0.25, frame.sun.y);
let shaft_color = mix(vec3(1.0, 0.55, 0.25), vec3(1.0, 0.92, 0.75), sunset);
shafts = shaft_color * (transmittance / 12.0) * sun_facing * 0.28 * (1.0 - frame.weather.x);
}
}
return vec4(base + bloom * bloom_strength + shafts, 1.0);
}
@@ -0,0 +1,92 @@
// Stage 1 (Deferred): G-buffer normal reconstruction, multi-tap GTAO ambient
// occlusion, directional sun/moon PCF shadow mapping, and rain puddle wetness.
override shadows: bool = true;
override shadow_strength: f32 = 0.85;
override ao_strength: f32 = 0.75;
fn compute_gtao(uv: vec2<f32>, depth: f32, view_pos: vec3<f32>) -> f32 {
if ao_strength <= 0.001 {
return 1.0;
}
let step_uv = frame.resolution.zw * 2.5;
let offsets = array<vec2<f32>, 8>(
vec2(1.0, 0.0),
vec2(-1.0, 0.0),
vec2(0.0, 1.0),
vec2(0.0, -1.0),
vec2(0.707, 0.707),
vec2(-0.707, 0.707),
vec2(0.707, -0.707),
vec2(-0.707, -0.707),
);
var occlusion = 0.0;
for (var i = 0u; i < 8u; i++) {
let sample_uv = clamp(uv + offsets[i] * step_uv, vec2(0.001), vec2(0.999));
let sd = opaque_depth_at(sample_uv);
if !is_sky(sd) {
let sp = view_position(sample_uv, sd);
let diff = sp - view_pos;
let dist = length(diff);
if dist > 0.02 && dist < 3.5 {
let horizon = clamp(diff.z / dist, 0.0, 1.0);
occlusion += horizon * smoothstep(3.5, 0.2, dist);
}
}
}
return clamp(1.0 - (occlusion * 0.18 * ao_strength), 0.15, 1.0);
}
@fragment fn fs_main(in: StageIn) -> @location(0) vec4<f32> {
let base_srgb = textureSampleLevel(scene_color, linear_sampler, in.uv, 0.0).rgb;
var color = srgb_to_linear(base_srgb);
let depth = opaque_depth_at(in.uv);
let light_dir = normalize(select(frame.moon.xyz, frame.sun.xyz, frame.sun.y >= -0.05));
let sun_elevation = clamp(frame.sun.y, -1.0, 1.0);
let day_factor = smoothstep(-0.08, 0.18, sun_elevation);
let sunset_factor = smoothstep(-0.12, 0.05, sun_elevation) * (1.0 - smoothstep(0.05, 0.35, sun_elevation));
if is_sky(depth) {
let ray = normalize(world_offset(in.uv, 1e-5));
let sun_dot = max(dot(ray, frame.sun.xyz), 0.0);
let mie = pow(sun_dot, 12.0) * (0.35 + 0.65 * sunset_factor) * (1.0 - frame.weather.x * 0.8);
let sun_tint = mix(vec3(1.0, 0.88, 0.68), vec3(1.0, 0.45, 0.18), sunset_factor);
color += sun_tint * mie * 0.85;
return vec4(color, 1.0);
}
let world_rel = world_offset(in.uv, depth);
let view_pos = view_position(in.uv, depth);
let normal = world_normal_at(in.uv);
let mat = material_at(in.uv);
// Ambient occlusion from depth discontinuity neighborhood.
let ao = compute_gtao(in.uv, depth, view_pos);
// Directional sun/moon shadow factor.
var shadow = 1.0;
if shadows && frame.dimension.y > 0.5 {
let raw_shadow = sample_shadow(world_rel, normal);
shadow = mix(1.0, raw_shadow, shadow_strength);
}
let ndotl = max(dot(normal, light_dir), 0.0);
let sun_color = mix(
vec3(0.22, 0.28, 0.48),
mix(vec3(1.05, 0.96, 0.86), vec3(1.18, 0.58, 0.28), sunset_factor),
day_factor,
);
let sky_ambient = mix(vec3(0.08, 0.11, 0.20), srgb_to_linear(frame.sky_color.rgb) * 0.55, day_factor);
let direct_light = sun_color * ndotl * shadow * (1.0 - frame.weather.x * 0.55);
let bounce_light = sky_ambient * (0.45 + 0.55 * max(normal.y, 0.0)) * ao;
// Wetness specular sheen during rain on upward-facing surfaces.
let wetness = frame_ext.environment.z;
let view_dir = normalize(-world_rel);
let half_vec = normalize(light_dir + view_dir);
let wet_mask = wetness * smoothstep(0.65, 0.95, normal.y) * mat.g;
let spec = pow(max(dot(normal, half_vec), 0.0), 48.0) * wet_mask * shadow * 0.65;
let shade_boost = mix(0.68 * ao, 1.0 + 0.35 * ndotl * shadow, 0.65);
color = color * shade_boost + color * direct_light * 0.32 + bounce_light * 0.08 + sun_color * spec;
return vec4(max(color, vec3(0.0)), 1.0);
}
@@ -0,0 +1,29 @@
// Stage 4 (Final): Combines full-resolution scene with bloom/godrays, applies
// exposure, ACES filmic tonemapping, saturation, and cinematic vignette.
override exposure: f32 = 1.10;
override saturation: f32 = 1.12;
override tonemap_aces: bool = true;
override vignette: bool = true;
@fragment fn fs_main(in: StageIn) -> @location(0) vec4<f32> {
var hdr = textureSampleLevel(previous, linear_sampler, in.uv, 0.0).rgb * exposure;
if tonemap_aces {
hdr = aces_tonemap(hdr);
} else {
hdr = clamp(hdr, vec3(0.0), vec3(1.0));
}
var srgb = linear_to_srgb(hdr);
let luma = luminance(srgb);
let rain_desat = 1.0 - 0.25 * max(frame.weather.x, frame.weather.y);
srgb = mix(vec3(luma), srgb, saturation * rain_desat);
if vignette {
let aspect = frame.resolution.x * frame.resolution.w;
let d = length((in.uv - 0.5) * vec2(aspect, 1.0));
srgb *= 1.0 - 0.26 * smoothstep(0.48, 0.98, d);
}
return vec4(clamp(srgb, vec3(0.0), vec3(1.0)), 1.0);
}
@@ -0,0 +1,58 @@
// Stage 2 (Composite): Screen-space water reflections (SSR), Fresnel Schlick,
// and Beer-Lambert underwater depth absorption using scene_depth vs opaque_depth.
override water_ssr: bool = true;
@fragment fn fs_main(in: StageIn) -> @location(0) vec4<f32> {
var color = textureSampleLevel(previous, linear_sampler, in.uv, 0.0).rgb;
let surface_depth = depth_at(in.uv);
let floor_depth = opaque_depth_at(in.uv);
let mat = material_at(in.uv);
// Translucent water/glass layer exists where surface_depth is closer than floor_depth
// (reversed depth: closer = larger value) or where the G-buffer water mask is set.
let is_translucent = (surface_depth > floor_depth + 1e-5) || (mat.b > 0.5);
if !water_ssr || is_sky(surface_depth) || !is_translucent {
return vec4(color, 1.0);
}
let water_pos = world_offset(in.uv, surface_depth);
let floor_pos = world_offset(in.uv, max(floor_depth, 1e-6));
let water_column = clamp(length(floor_pos - water_pos), 0.0, 32.0);
// Beer-Lambert depth absorption in deep water.
let absorption = exp(-vec3(0.22, 0.07, 0.03) * water_column * 0.35);
color *= mix(vec3(1.0), absorption, clamp(water_column * 0.08, 0.0, 0.65));
// Wave normal perturbation and Fresnel reflection.
let world_xz = (water_pos.xz + frame.camera_position.xz) * 0.08;
let wave_uv = world_xz + vec2(frame.time.x * 0.015, -frame.time.x * 0.011);
let noise_sample = textureSampleLevel(noise_texture, repeat_sampler, wave_uv, 0.0).rgb * 2.0 - 1.0;
let normal = normalize(vec3(noise_sample.x * 0.06, 1.0, noise_sample.y * 0.06));
let view_dir = normalize(-water_pos);
let refl_dir = reflect(-view_dir, normal);
let fresnel = clamp(0.04 + 0.96 * pow(1.0 - max(dot(view_dir, normal), 0.0), 4.0), 0.0, 0.85);
// Ray-march 8 steps in screen space along the reflection ray.
var refl_color = srgb_to_linear(frame.sky_color.rgb);
let sun_spec = pow(max(dot(refl_dir, frame.sun.xyz), 0.0), 96.0) * 2.5 * (1.0 - frame.weather.x);
refl_color += vec3(1.0, 0.9, 0.7) * sun_spec;
for (var step = 1u; step <= 8u; step++) {
let march_pos = water_pos + refl_dir * (f32(step) * 2.2);
let clip = frame.projection * (frame.view * vec4(march_pos, 1.0));
if clip.w > 0.0 {
let ndc = clip.xyz / clip.w;
let sample_uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
if all(sample_uv >= vec2(0.01)) && all(sample_uv <= vec2(0.99)) {
let scene_d = opaque_depth_at(sample_uv);
if !is_sky(scene_d) && ndc.z <= scene_d && (scene_d - ndc.z) < 0.08 {
refl_color = textureSampleLevel(previous, linear_sampler, sample_uv, 0.0).rgb;
break;
}
}
}
}
color = mix(color, refl_color, fresnel * 0.55);
return vec4(color, 1.0);
}