Merge pull request #1863 from ludovic111/feat/native-shaders-sky
🤖 Agent: verified: pr_ready --quick green, 80/80 affected harnesses pass locally, CI verify green, A/B shows no frame cost without a pack. A Horizon shader pack's sky stage now draws in the game.
This commit is contained in:
@@ -69,6 +69,7 @@ pub mod lightning;
|
||||
mod lod;
|
||||
mod native_pack;
|
||||
mod native_post;
|
||||
mod native_sky;
|
||||
mod occlusion;
|
||||
mod pack_atlas;
|
||||
pub mod pack_draw;
|
||||
@@ -2935,8 +2936,8 @@ impl Renderer {
|
||||
self.native = None;
|
||||
self.pack_atlas = None;
|
||||
}
|
||||
/// Runs the post stage of one of Horizon's own shader packs from now on (`None`: no
|
||||
/// pack), with its options' values; replaces a `shaders/` pack. Returns the passes'
|
||||
/// Runs the sky and post stages of one of Horizon's own shader packs from now on (`None`:
|
||||
/// no pack), with its options' values; replaces a `shaders/` pack. Returns the stages'
|
||||
/// labels; on an error the pack that ran keeps running.
|
||||
pub fn set_native_shader_pack(
|
||||
&mut self,
|
||||
@@ -2947,8 +2948,13 @@ impl Renderer {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let format = self.config.format.remove_srgb_suffix();
|
||||
let (pack, labels) =
|
||||
native_pack::NativePack::new(&self.device, report, &constants, format)?;
|
||||
let (pack, labels) = native_pack::NativePack::new(
|
||||
&self.device,
|
||||
&self.terrain_layout,
|
||||
report,
|
||||
&constants,
|
||||
format,
|
||||
)?;
|
||||
self.native = pack.draws().then_some(pack);
|
||||
if self.native.is_some() {
|
||||
self.pack_post = None;
|
||||
@@ -4110,7 +4116,20 @@ impl Renderer {
|
||||
cull.bind_depth(&self.device, world_depth);
|
||||
}
|
||||
let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0);
|
||||
// One of Horizon's own packs: this frame's inputs.
|
||||
let clear = if frame.title || (frame.end_sky && !frame.underwater) {
|
||||
wgpu::Color::BLACK
|
||||
} else {
|
||||
wgpu::Color {
|
||||
r: f64::from(fog_color[0]),
|
||||
g: f64::from(fog_color[1]),
|
||||
b: f64::from(fog_color[2]),
|
||||
a: 1.0,
|
||||
}
|
||||
};
|
||||
let sky_visible = sky_open(frame);
|
||||
// One of Horizon's own packs: this frame's inputs; in a timed frame its sky draws in a
|
||||
// pass of its own, so that it has a time of its own.
|
||||
let mut native_sky_pass = false;
|
||||
if !frame.title
|
||||
&& let Some(native) = &mut self.native
|
||||
{
|
||||
@@ -4122,26 +4141,54 @@ impl Renderer {
|
||||
native.frame.write(&self.queue, frame, size);
|
||||
if let Some(t) = &mut native.timing {
|
||||
t.begin(&self.device, &self.queue);
|
||||
native_sky_pass =
|
||||
native.sky.is_some() && t.recording() && sky_visible && frame.skybox;
|
||||
}
|
||||
}
|
||||
if native_sky_pass
|
||||
&& let Some(native) = &mut self.native
|
||||
&& let Some(sky) = &native.sky
|
||||
{
|
||||
if let Some(t) = &mut native.timing {
|
||||
let format = self.config.format.remove_srgb_suffix();
|
||||
t.mark(&self.device, &mut encoder, (world_view, format));
|
||||
}
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some(&sky.label),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: world_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(clear),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: world_depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(0.0),
|
||||
store: wgpu::StoreOp::Discard,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
timestamp_writes: native.timing.as_mut().and_then(|t| t.writes(&sky.label)),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
sky.draw(&mut pass, &native.frame);
|
||||
}
|
||||
{
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: world_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(
|
||||
if frame.title || (frame.end_sky && !frame.underwater) {
|
||||
wgpu::Color::BLACK
|
||||
} else {
|
||||
wgpu::Color {
|
||||
r: f64::from(fog_color[0]),
|
||||
g: f64::from(fog_color[1]),
|
||||
b: f64::from(fog_color[2]),
|
||||
a: 1.0,
|
||||
}
|
||||
},
|
||||
),
|
||||
load: if native_sky_pass {
|
||||
wgpu::LoadOp::Load
|
||||
} else {
|
||||
wgpu::LoadOp::Clear(clear)
|
||||
},
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
@@ -4164,11 +4211,19 @@ impl Renderer {
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
let sky_visible = sky_open(frame);
|
||||
if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) {
|
||||
if !frame.title && frame.skybox && !pack_draws_sky {
|
||||
pass.set_pipeline(&self.sky);
|
||||
pass.draw(0..3, 0..1);
|
||||
if !frame.title && frame.skybox && !pack_draws_sky && !native_sky_pass {
|
||||
match self
|
||||
.native
|
||||
.as_ref()
|
||||
.and_then(|n| Some((n.sky.as_ref()?, &n.frame)))
|
||||
{
|
||||
Some((sky, native)) => sky.draw(&mut pass, native),
|
||||
None => {
|
||||
pass.set_pipeline(&self.sky);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if frame.title {
|
||||
self.panorama.draw(&mut pass);
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
//! One of Horizon's own shader packs while it runs (docs/shaders.md): the frame its stages
|
||||
//! read, its post stage, and the timer of its passes.
|
||||
//! read, its sky and post stages, and the timer of their passes.
|
||||
|
||||
use horizon_shader_api::{Report, StageKind};
|
||||
|
||||
use super::native_post::{NativeFrame, NativePost};
|
||||
use super::native_sky::NativeSky;
|
||||
use super::pack_timing::PassTiming;
|
||||
|
||||
pub struct NativePack {
|
||||
pub frame: NativeFrame,
|
||||
pub sky: Option<NativeSky>,
|
||||
pub post: Option<NativePost>,
|
||||
/// GPU time of each pass, while the renderer asks for it (`pack_timing.rs`).
|
||||
pub timing: Option<PassTiming>,
|
||||
@@ -15,30 +17,36 @@ pub struct NativePack {
|
||||
|
||||
impl NativePack {
|
||||
/// The pack of the checked stages `report` with the option values `constants`, drawing
|
||||
/// onto targets of `format`. Also returns its stages' labels, in the order they draw.
|
||||
/// Errors name the stage wgpu refused.
|
||||
/// onto targets of `format`; `globals` is the terrain's group 0, which the sky reads.
|
||||
/// Also returns its stages' labels, in the order they draw. Errors name the stage wgpu
|
||||
/// refused.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
globals: &wgpu::BindGroupLayout,
|
||||
report: Report,
|
||||
constants: &[(String, f64)],
|
||||
format: wgpu::TextureFormat,
|
||||
) -> Result<(Self, Vec<String>), String> {
|
||||
let frame = NativeFrame::new(device);
|
||||
let post: Vec<_> = report
|
||||
let (post, others): (Vec<_>, Vec<_>) = report
|
||||
.stages
|
||||
.into_iter()
|
||||
.filter(|s| s.kind == StageKind::Post)
|
||||
.collect();
|
||||
.partition(|s| s.kind == StageKind::Post);
|
||||
let sky = others
|
||||
.iter()
|
||||
.find(|s| s.kind == StageKind::Sky)
|
||||
.map(|stage| NativeSky::new(device, globals, &frame, stage, constants, format))
|
||||
.transpose()?;
|
||||
let post = (!post.is_empty())
|
||||
.then(|| NativePost::new(device, post, constants, format, &frame))
|
||||
.transpose()?;
|
||||
let labels = post
|
||||
.iter()
|
||||
.flat_map(|p| p.labels())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let mut labels: Vec<String> = sky.iter().map(|s| s.label.clone()).collect();
|
||||
if let Some(post) = &post {
|
||||
labels.extend(post.labels().into_iter().map(str::to_owned));
|
||||
}
|
||||
let pack = Self {
|
||||
frame,
|
||||
sky,
|
||||
post,
|
||||
timing: None,
|
||||
};
|
||||
@@ -47,6 +55,6 @@ impl NativePack {
|
||||
|
||||
/// Whether the pack draws anything the game runs today.
|
||||
pub fn draws(&self) -> bool {
|
||||
self.post.is_some()
|
||||
self.sky.is_some() || self.post.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct NativePost {
|
||||
/// The `frame` every stage of a pack reads (group 3, binding 0), written once a frame.
|
||||
pub struct NativeFrame {
|
||||
pub(super) buffer: wgpu::Buffer,
|
||||
/// Group 3 of the stages that read only the frame (the sky).
|
||||
pub layout: wgpu::BindGroupLayout,
|
||||
pub group: wgpu::BindGroup,
|
||||
start: std::time::Instant,
|
||||
frames: u32,
|
||||
}
|
||||
@@ -59,8 +62,22 @@ impl NativeFrame {
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Native shader pack frame"),
|
||||
entries: &[frame_entry(wgpu::ShaderStages::VERTEX_FRAGMENT)],
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Native shader pack frame"),
|
||||
layout: &layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
Self {
|
||||
buffer,
|
||||
layout,
|
||||
group,
|
||||
start: std::time::Instant::now(),
|
||||
frames: 0,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
//! The sky stage of Horizon's own shader packs (docs/shaders.md): the pack's `sky` function,
|
||||
//! called for each pixel of the sky disc with vanilla's colour along its view ray. The
|
||||
//! pipeline's shader is the pack's stage (`CheckedStage::source`) followed by a copy of the
|
||||
//! renderer's sky (terrain.wgsl's `Globals`, `linear_fog` and sky section) whose names all
|
||||
//! take a `horizon_sky_` prefix, so none can meet a pack's (the check refuses `horizon_`
|
||||
//! names). It reads the renderer's globals (group 0) and the pack's frame (group 3), and
|
||||
//! draws where vanilla's sky draws; the sun, moon, stars and the dark disc are drawn over it.
|
||||
|
||||
use horizon_shader_api::{check::CheckedStage, stages::GROUP};
|
||||
|
||||
use super::native_post::{NativeFrame, present_constants};
|
||||
|
||||
const PREFIX: &str = "horizon_sky_";
|
||||
const TERRAIN: &str = include_str!("../terrain.wgsl");
|
||||
|
||||
/// The fragment entry that calls the pack: vanilla's colour in, an opaque colour out.
|
||||
const PACK_ENTRY: &str = "
|
||||
@fragment fn horizon_sky_fs_pack(in: horizon_sky_SkyOut) -> @location(0) vec4<f32> {
|
||||
let d = horizon_sky_view_ray(in.ndc);
|
||||
return vec4(sky(SkyInput(d, vec4(horizon_sky_sky_along_ray(d), 1.0))).rgb, 1.0);
|
||||
}
|
||||
";
|
||||
|
||||
pub struct NativeSky {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// The text of `source` from the line starting with `start` up to (not including) the one
|
||||
/// starting with `end`.
|
||||
fn section<'a>(source: &'a str, start: &str, end: &str) -> &'a str {
|
||||
let from = source
|
||||
.find(&format!("\n{start}"))
|
||||
.expect("terrain.wgsl has the section")
|
||||
+ 1;
|
||||
let to = from
|
||||
+ source[from..]
|
||||
.find(&format!("\n{end}"))
|
||||
.expect("terrain.wgsl ends the section")
|
||||
+ 1;
|
||||
&source[from..to]
|
||||
}
|
||||
|
||||
/// terrain.wgsl's sky with every name it declares (and `globals`) prefixed.
|
||||
fn vanilla_sky() -> String {
|
||||
let text = [
|
||||
section(TERRAIN, "struct Globals {", "@group(0) @binding(0)"),
|
||||
section(TERRAIN, "fn linear_fog(", "fn apply_fog("),
|
||||
section(TERRAIN, "struct SkyOut {", "// rendertype_lines"),
|
||||
]
|
||||
.concat();
|
||||
let mut names = vec!["globals"];
|
||||
for line in text.lines() {
|
||||
let line = line
|
||||
.trim_start_matches("@vertex ")
|
||||
.trim_start_matches("@fragment ");
|
||||
for keyword in ["fn ", "struct ", "const "] {
|
||||
if let Some(rest) = line.strip_prefix(keyword) {
|
||||
let end = rest
|
||||
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.unwrap_or(rest.len());
|
||||
names.push(&rest[..end]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::with_capacity(text.len() * 2);
|
||||
let mut word = String::new();
|
||||
let flush = |word: &mut String, out: &mut String| {
|
||||
if names.contains(&word.as_str()) {
|
||||
out.push_str(PREFIX);
|
||||
}
|
||||
out.push_str(word);
|
||||
word.clear();
|
||||
};
|
||||
for c in text.chars() {
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
word.push(c);
|
||||
} else {
|
||||
flush(&mut word, &mut out);
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
flush(&mut word, &mut out);
|
||||
out + &format!("@group(0) @binding(0) var<uniform> {PREFIX}globals: {PREFIX}Globals;\n")
|
||||
}
|
||||
|
||||
/// The sky shader for the pack's sky stage `source`.
|
||||
fn shader_source(source: &str) -> String {
|
||||
format!(
|
||||
"{source}\n// Horizon's sky (terrain.wgsl)\n{}{PACK_ENTRY}",
|
||||
vanilla_sky()
|
||||
)
|
||||
}
|
||||
|
||||
/// A sky pipeline over `module` whose fragment entry is `fragment`.
|
||||
fn pipeline(
|
||||
device: &wgpu::Device,
|
||||
layout: &wgpu::PipelineLayout,
|
||||
module: &wgpu::ShaderModule,
|
||||
fragment: &str,
|
||||
constants: &[(&str, f64)],
|
||||
format: wgpu::TextureFormat,
|
||||
) -> wgpu::RenderPipeline {
|
||||
let options = wgpu::PipelineCompilationOptions {
|
||||
constants,
|
||||
..Default::default()
|
||||
};
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Native shader pack sky"),
|
||||
layout: Some(layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some("horizon_sky_vs_sky"),
|
||||
compilation_options: options.clone(),
|
||||
buffers: &[],
|
||||
},
|
||||
primitive: Default::default(),
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(false),
|
||||
depth_compare: Some(wgpu::CompareFunction::Always),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some(fragment),
|
||||
compilation_options: options,
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The sky's naga module and the layout of its pipelines: `globals` at group 0, the frame
|
||||
/// at group 3.
|
||||
fn build(
|
||||
device: &wgpu::Device,
|
||||
globals: &wgpu::BindGroupLayout,
|
||||
frame: &NativeFrame,
|
||||
stage: &CheckedStage,
|
||||
) -> Result<(naga::Module, wgpu::PipelineLayout), String> {
|
||||
let text = shader_source(&stage.source);
|
||||
let module = naga::front::wgsl::parse_str(&text)
|
||||
.map_err(|e| format!("{}: {}", stage.file, e.emit_to_string(&text)))?;
|
||||
let mut groups: [Option<&wgpu::BindGroupLayout>; GROUP as usize + 1] = Default::default();
|
||||
groups[0] = Some(globals);
|
||||
groups[GROUP as usize] = Some(&frame.layout);
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Native shader pack sky"),
|
||||
bind_group_layouts: &groups,
|
||||
..Default::default()
|
||||
});
|
||||
Ok((module, layout))
|
||||
}
|
||||
|
||||
impl NativeSky {
|
||||
/// The pipeline of the pack's sky `stage` with the option values `constants`, drawing
|
||||
/// onto the world's target of `format`; `globals` is the terrain's group 0.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
globals: &wgpu::BindGroupLayout,
|
||||
frame: &NativeFrame,
|
||||
stage: &CheckedStage,
|
||||
constants: &[(String, f64)],
|
||||
format: wgpu::TextureFormat,
|
||||
) -> Result<Self, String> {
|
||||
let (module, layout) = build(device, globals, frame, stage)?;
|
||||
let present = present_constants(&module, constants);
|
||||
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some(&stage.label),
|
||||
source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)),
|
||||
});
|
||||
let pipeline = pipeline(
|
||||
device,
|
||||
&layout,
|
||||
&module,
|
||||
"horizon_sky_fs_pack",
|
||||
&present,
|
||||
format,
|
||||
);
|
||||
if let Some(e) = pollster::block_on(scope.pop()) {
|
||||
return Err(format!("{}: {e}", stage.file));
|
||||
}
|
||||
Ok(Self {
|
||||
pipeline,
|
||||
label: stage.label.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Draws the sky in a pass whose group 0 is the terrain's.
|
||||
pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>, frame: &NativeFrame) {
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(GROUP, &frame.group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_shader_api::{Frame as FrameInputs, MANIFEST, Pack, StageKind, check};
|
||||
|
||||
fn stage(sky: &str) -> CheckedStage {
|
||||
let mut manifest = "schema = 1\nid = \"t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.1\"\n\
|
||||
[sky]\nfile = \"sky.wgsl\"\n"
|
||||
.to_owned();
|
||||
if sky.contains("gain") {
|
||||
manifest += "[[options]]\nid = \"gain\"\nname = \"Gain\"\ntype = \"float\"\n\
|
||||
default = 1.0\nmin = 0.0\nmax = 2.0\n";
|
||||
}
|
||||
let manifest = manifest.as_str();
|
||||
let files = [(MANIFEST, manifest), ("sky.wgsl", sky)]
|
||||
.map(|(n, t)| (n.to_owned(), t.as_bytes().to_vec()))
|
||||
.into();
|
||||
let mut report = check(&Pack::from_files(files).unwrap()).unwrap();
|
||||
assert_eq!(report.stages[0].kind, StageKind::Sky);
|
||||
report.stages.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_renderer_s_sky_takes_a_prefix_and_validates_with_a_pack() {
|
||||
let sky = vanilla_sky();
|
||||
for name in [
|
||||
"Globals",
|
||||
"SkyOut",
|
||||
"view_ray",
|
||||
"PI",
|
||||
"sky_along_ray",
|
||||
"linear_fog",
|
||||
"fs_sky",
|
||||
] {
|
||||
assert!(sky.contains(&format!("{PREFIX}{name}")), "{name}");
|
||||
}
|
||||
// A pack may use the renderer's names for its own things.
|
||||
let own = "override gain: f32;\nconst PI: f32 = 3.0;\nfn view_ray() -> f32 { return PI; }\n\
|
||||
fn sky(input: SkyInput) -> vec4<f32> { return input.color * gain * view_ray(); }\n";
|
||||
let text = shader_source(&stage(own).source);
|
||||
let module = naga::front::wgsl::parse_str(&text).unwrap_or_else(|e| {
|
||||
panic!("{}", e.emit_to_string(&text));
|
||||
});
|
||||
naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::default(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Vanilla's sky and two packs over the same globals: one that returns its input draws
|
||||
/// vanilla's pixels, one that inverts them draws the inverse (and stays opaque).
|
||||
#[test]
|
||||
fn a_pack_gets_vanilla_s_colour_and_draws_opaque() {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
|
||||
return;
|
||||
};
|
||||
let (device, queue) =
|
||||
pollster::block_on(adapter.request_device(&Default::default())).unwrap();
|
||||
let format = wgpu::TextureFormat::Rgba8Unorm;
|
||||
let globals_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let mut globals: super::super::Globals = bytemuck::Zeroable::zeroed();
|
||||
globals.inverse_view = glam::Mat4::IDENTITY.to_cols_array_2d();
|
||||
globals.misc = [0.0, 0.0, 1.0, 1.0];
|
||||
globals.fog_color = [0.2, 0.4, 0.6, 1.0];
|
||||
globals.sky_color = [0.5, 0.7, 1.0, 1.0];
|
||||
globals.fog_ends = [64.0, 0.0, 0.0, 0.0];
|
||||
let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: size_of::<super::super::Globals>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
queue.write_buffer(&globals_buffer, 0, bytemuck::bytes_of(&globals));
|
||||
let globals_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &globals_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: globals_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
let frame = NativeFrame::new(&device);
|
||||
queue.write_buffer(
|
||||
&frame.buffer,
|
||||
0,
|
||||
bytemuck::bytes_of(&FrameInputs::default()),
|
||||
);
|
||||
|
||||
let gain = [("gain".to_owned(), 1.0)];
|
||||
let draw = |stage: &CheckedStage, vanilla: bool| -> Vec<u8> {
|
||||
let sky =
|
||||
NativeSky::new(&device, &globals_layout, &frame, stage, &gain, format).unwrap();
|
||||
let pipeline = if vanilla {
|
||||
let (module, layout) = build(&device, &globals_layout, &frame, stage).unwrap();
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)),
|
||||
});
|
||||
pipeline(&device, &layout, &module, "horizon_sky_fs_sky", &[], format)
|
||||
} else {
|
||||
sky.pipeline.clone()
|
||||
};
|
||||
let texture = |format, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d {
|
||||
width: 4,
|
||||
height: 4,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let color = texture(
|
||||
format,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
);
|
||||
let depth = texture(
|
||||
wgpu::TextureFormat::Depth32Float,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
);
|
||||
let (color_view, depth_view) = (
|
||||
color.create_view(&Default::default()),
|
||||
depth.create_view(&Default::default()),
|
||||
);
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: None,
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &color_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &depth_view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(0.0),
|
||||
store: wgpu::StoreOp::Discard,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &globals_group, &[]);
|
||||
pass.set_pipeline(&pipeline);
|
||||
pass.set_bind_group(GROUP, &frame.group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT * 4),
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
encoder.copy_texture_to_buffer(
|
||||
color.as_image_copy(),
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT),
|
||||
rows_per_image: Some(4),
|
||||
},
|
||||
},
|
||||
color.size(),
|
||||
);
|
||||
queue.submit([encoder.finish()]);
|
||||
buffer
|
||||
.slice(..)
|
||||
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
let bytes = buffer.slice(..).get_mapped_range().unwrap().to_vec();
|
||||
(0..4)
|
||||
.flat_map(|row| {
|
||||
let start = row * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
|
||||
bytes[start..start + 16].to_vec()
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let same = stage("fn sky(input: SkyInput) -> vec4<f32> { return input.color; }\n");
|
||||
let vanilla = draw(&same, true);
|
||||
assert_eq!(draw(&same, false), vanilla);
|
||||
// The top row looks up into the sky disc, the bottom one down into the fog.
|
||||
assert_ne!(vanilla[..4], vanilla[vanilla.len() - 4..]);
|
||||
let inverse = stage(
|
||||
"override gain: f32;\nfn sky(input: SkyInput) -> vec4<f32> { return vec4(vec3(gain) - input.color.rgb, 0.25); }\n",
|
||||
);
|
||||
let inverted = draw(&inverse, false);
|
||||
for (got, want) in inverted.chunks(4).zip(vanilla.chunks(4)) {
|
||||
assert_eq!(got[3], 255);
|
||||
for i in 0..3 {
|
||||
assert!(got[i].abs_diff(255 - want[i]) <= 1, "{got:?} {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,11 @@ impl PassTiming {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the frame being recorded is timed.
|
||||
pub fn recording(&self) -> bool {
|
||||
matches!(self.stage, Stage::Recording)
|
||||
}
|
||||
|
||||
/// Timestamp writes for the pass `name`, in a timed frame.
|
||||
pub fn writes(&mut self, name: &str) -> Option<wgpu::RenderPassTimestampWrites<'_>> {
|
||||
let i = self.push(name)?;
|
||||
|
||||
@@ -227,8 +227,9 @@ fn sunrise_weight(d: vec3<f32>) -> f32 {
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4<f32> {
|
||||
let d = view_ray(in.ndc);
|
||||
// The sky's colour along the view ray `d` (a shader pack's sky stage gets it as its input:
|
||||
// gfx/native_sky.rs builds that stage from this section).
|
||||
fn sky_along_ray(d: vec3<f32>) -> vec3<f32> {
|
||||
var color = globals.fog_color.rgb;
|
||||
let dist = disc_distance(d, 16.0);
|
||||
if dist.x >= 0.0 {
|
||||
@@ -238,7 +239,10 @@ fn sunrise_weight(d: vec3<f32>) -> f32 {
|
||||
if w > 0.0 {
|
||||
color = mix(color, globals.sunrise.rgb, w * globals.sunrise.a);
|
||||
}
|
||||
return vec4(color, 1.0);
|
||||
return color;
|
||||
}
|
||||
@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4<f32> {
|
||||
return vec4(sky_along_ray(view_ray(in.ndc)), 1.0);
|
||||
}
|
||||
@fragment fn fs_dark_disc(in: SkyOut) -> @location(0) vec4<f32> {
|
||||
let d = view_ray(in.ndc);
|
||||
|
||||
@@ -60,6 +60,10 @@ pub struct CheckedStage {
|
||||
pub label: String,
|
||||
pub module: naga::Module,
|
||||
pub info: ModuleInfo,
|
||||
/// The stage's WGSL without the entry points (the prelude, the shared
|
||||
/// files, the file), for a renderer that calls the stage function from
|
||||
/// its own shader (the sky).
|
||||
pub source: String,
|
||||
pub expressions: usize,
|
||||
pub texture_reads: usize,
|
||||
}
|
||||
@@ -169,6 +173,7 @@ pub fn check_stage(pack: &Pack, kind: StageKind, file: &str) -> Result<CheckedSt
|
||||
label: file.to_owned(),
|
||||
module,
|
||||
info,
|
||||
source: own.text,
|
||||
expressions,
|
||||
texture_reads,
|
||||
})
|
||||
|
||||
+3
-2
@@ -91,11 +91,12 @@ pack exist ([stability.md](stability.md)).
|
||||
|
||||
## Not there yet
|
||||
|
||||
The stages and everything that runs a pack (the format above is read and checked). The order: the renderer hooks shared with the format loader, then the material and post
|
||||
stages with options and hot reload, then the overlay, lighting, sky and shadow stages.
|
||||
The material stage in the game (the sky and post stages run, with hot reload), option values other than the defaults,
|
||||
then the overlay, lighting and shadow stages.
|
||||
|
||||
## Changelog
|
||||
|
||||
- 2026-10-26: the sky stage in the game: the pack's `sky` gets vanilla's colour along each ray.
|
||||
- 2026-10-26: the post stage in the game (`HORIZON_SHADER_PACK`, hot reload with the last good pack kept).
|
||||
- 2026-10-25: `horizon-shader` (`new`, `check`, `pack`), three templates, the example pack and the guide.
|
||||
- 2026-10-25: the check (naga validation, signatures, options, budgets, SPIR-V/Metal/HLSL translation).
|
||||
|
||||
+8
-7
@@ -13,8 +13,8 @@ Horizon's own format.
|
||||
| Authoring tool | `horizon-shader` (same crate) | `new`, `check`, `pack` |
|
||||
| Templates | `crates/horizon-shader-api/templates/` | post, sky, material |
|
||||
| Example pack | `crates/horizon-shader-api/packs/golden_hour` | a warm sky and two post passes |
|
||||
| In the game: the post stage | Options > Horizon Settings > Shader Packs | post passes, hot reload |
|
||||
| In the game: sky and material; the launcher and the registry | | not yet |
|
||||
| In the game: the sky and post stages | Options > Horizon Settings > Shader Packs | sky, post passes, hot reload |
|
||||
| In the game: the material stage; the launcher and the registry | | not yet |
|
||||
|
||||
## Quick start
|
||||
|
||||
@@ -52,8 +52,8 @@ it on Options > Horizon Settings > Shader Packs, which lists Horizon's packs, ma
|
||||
name>` runs a pack whatever the page says, for development. The game checks the pack first, and refuses one that
|
||||
fails, with its problems in the chat. While it runs, the game looks at the pack twice a second: save a file
|
||||
and the pack is checked and rebuilt in place ("Shader pack ... reloaded"); if the new version fails, the chat says
|
||||
where and the last good version keeps drawing. The post passes run today; the sky and material stages are checked
|
||||
but not drawn yet.
|
||||
where and the last good version keeps drawing. The sky and post stages run today; the material stage is checked but
|
||||
not drawn yet.
|
||||
|
||||
## A pack
|
||||
|
||||
@@ -88,7 +88,7 @@ by Horizon: a pack changes how things look, not how they are drawn.
|
||||
|
||||
| Stage | Your function | What it does |
|
||||
| --- | --- | --- |
|
||||
| `[sky]` | `fn sky(input: SkyInput) -> vec4<f32>` | the sky's colour along each view ray; the sun, moon, stars and clouds are drawn over it |
|
||||
| `[sky]` | `fn sky(input: SkyInput) -> vec4<f32>` | the sky's colour along each view ray, opaque (alpha is ignored), drawn where vanilla draws its sky dome (the Overworld's sky; not the Nether's or the End's); the sun, moon, stars and clouds are drawn over it |
|
||||
| `[material]` | `fn material(input: MaterialInput) -> Surface` | the lit colour of each point of a block's surface, before the alpha test and fog |
|
||||
| `[[post]]` | `fn post(input: PostInput) -> vec4<f32>` | a full-screen pass over the world's picture (up to 8, in order), under the hand and HUD |
|
||||
|
||||
@@ -131,8 +131,9 @@ one keeps drawing), the launcher before it installs one, and the registry's CI b
|
||||
|
||||
`[budget] gpu_ms` is the GPU time your pack aims to add to a frame. To compare, open F3 in the game: while it is
|
||||
open, each pass is timed on the GPU and the overlay shows the pack's total and its costliest passes, by their `name`
|
||||
(the median of the last 15 timed frames). Timing waits for nothing, so it does not slow the game.
|
||||
(the median of the last 15 timed frames). Timing waits for nothing, so it does not slow the game. In a timed frame the sky
|
||||
stage draws in a pass of its own (it shares the world's pass otherwise), so its time includes clearing the picture.
|
||||
|
||||
## Next
|
||||
|
||||
The material and sky stages in the game, and the registry's `shader` kind with installs from the launcher.
|
||||
The material stage in the game, and the registry's `shader` kind with installs from the launcher.
|
||||
|
||||
Reference in New Issue
Block a user