Merge pull request #1822 from ludovic111/feat/native-shaders-sdk
🤖 Agent: merged after verify passed (horizon-shader-api only).
This commit is contained in:
Generated
+1
@@ -1444,6 +1444,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"naga",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"toml",
|
||||
"zip",
|
||||
|
||||
@@ -4,13 +4,14 @@ version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.85"
|
||||
description = "Horizon's own shader packs (WGSL, docs/api/shaders.md): horizon-shaders.toml, the .hshader package"
|
||||
description = "Horizon's own shader packs (WGSL, docs/shaders.md): the format, the stages, the check, and the horizon-shader tool"
|
||||
|
||||
[dependencies]
|
||||
bytemuck = { version = "1.24", features = ["derive"] }
|
||||
# Parses and validates a pack's WGSL, and translates it as wgpu does for Vulkan, Metal and DirectX 12.
|
||||
naga = { version = "30.0.1", features = ["wgsl-in", "spv-out", "msl-out", "hlsl-out"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
toml = "1.1.6"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# Golden Hour
|
||||
|
||||
Horizon's example shader pack (docs/shaders.md): a sky stage and two post passes, with five options. Check it with
|
||||
`horizon-shader check crates/horizon-shader-api/packs/golden_hour`.
|
||||
@@ -0,0 +1,13 @@
|
||||
fn luminance(c: vec3<f32>) -> f32 {
|
||||
return dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
|
||||
// 1 while the sun is up in the Overworld, fading out around the horizon.
|
||||
fn daylight() -> f32 {
|
||||
return select(0.0, smoothstep(-0.1, 0.1, frame.sun_direction.y), frame.dimension == 0);
|
||||
}
|
||||
|
||||
// 1 when the sun is on the horizon, 0 from a quarter of the way up.
|
||||
fn sun_low() -> f32 {
|
||||
return 1.0 - smoothstep(0.0, 0.35, abs(frame.sun_direction.y));
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
schema = 1
|
||||
id = "golden_hour"
|
||||
name = "Golden Hour"
|
||||
version = "1.0.0"
|
||||
api = "0.1"
|
||||
description = "Warm light at sunrise and sunset, a soft glow around bright things and a gentle colour grade."
|
||||
authors = ["Horizon"]
|
||||
license = "MIT"
|
||||
shared = ["common.wgsl"]
|
||||
|
||||
[sky]
|
||||
file = "sky.wgsl"
|
||||
name = "Warm horizon"
|
||||
|
||||
[[post]]
|
||||
file = "post/glow.wgsl"
|
||||
name = "Glow"
|
||||
|
||||
[[post]]
|
||||
file = "post/grade.wgsl"
|
||||
name = "Colour grade"
|
||||
|
||||
[[options]]
|
||||
id = "sun_glow"
|
||||
name = "Sunset glow"
|
||||
description = "How warm the sky is around a low sun."
|
||||
type = "float"
|
||||
default = 0.6
|
||||
min = 0.0
|
||||
max = 1.0
|
||||
step = 0.05
|
||||
|
||||
[[options]]
|
||||
id = "glow"
|
||||
name = "Glow"
|
||||
description = "The soft halo around bright things: the sun, lava, torches."
|
||||
type = "float"
|
||||
default = 0.35
|
||||
min = 0.0
|
||||
max = 1.0
|
||||
step = 0.05
|
||||
|
||||
[[options]]
|
||||
id = "warmth"
|
||||
name = "Warmth"
|
||||
description = "How golden the light turns when the sun is low."
|
||||
type = "float"
|
||||
default = 0.4
|
||||
min = 0.0
|
||||
max = 1.0
|
||||
step = 0.05
|
||||
|
||||
[[options]]
|
||||
id = "saturation"
|
||||
name = "Saturation"
|
||||
type = "float"
|
||||
default = 1.1
|
||||
min = 0.0
|
||||
max = 2.0
|
||||
step = 0.05
|
||||
|
||||
[[options]]
|
||||
id = "vignette"
|
||||
name = "Vignette"
|
||||
type = "bool"
|
||||
default = true
|
||||
|
||||
[budget]
|
||||
gpu_ms = 1.0
|
||||
@@ -0,0 +1,22 @@
|
||||
// A soft halo around bright pixels: twelve taps on two rings, scaled with
|
||||
// the picture's height so it looks the same at any resolution.
|
||||
override glow: f32 = 0.35;
|
||||
|
||||
fn bright(c: vec3<f32>) -> vec3<f32> {
|
||||
return c * smoothstep(0.7, 1.0, luminance(c));
|
||||
}
|
||||
|
||||
fn post(input: PostInput) -> vec4<f32> {
|
||||
if glow <= 0.0 {
|
||||
return input.color;
|
||||
}
|
||||
let step = frame.resolution.y / 720.0 / frame.resolution;
|
||||
var sum = vec3<f32>(0.0);
|
||||
for (var i = 0; i < 12; i++) {
|
||||
let angle = f32(i) * 0.5235988;
|
||||
let radius = select(3.0, 7.0, (i & 1) == 1);
|
||||
let offset = vec2<f32>(cos(angle), sin(angle)) * radius * step;
|
||||
sum += bright(textureSampleLevel(previous, linear_sampler, input.uv + offset, 0.0).rgb);
|
||||
}
|
||||
return vec4<f32>(input.color.rgb + sum * (glow / 6.0), input.color.a);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Golden light when the sun is low, a soft shoulder for the brightest
|
||||
// colours (white stays white), saturation and a light vignette.
|
||||
override warmth: f32 = 0.4;
|
||||
override saturation: f32 = 1.1;
|
||||
override vignette: bool = true;
|
||||
|
||||
fn post(input: PostInput) -> vec4<f32> {
|
||||
var c = input.color.rgb;
|
||||
let golden = warmth * mix(0.3, 1.0, sun_low()) * daylight() * (1.0 - frame.rain * 0.7);
|
||||
c *= mix(vec3<f32>(1.0), vec3<f32>(1.08, 1.0, 0.86), golden);
|
||||
c = c / (1.0 + 0.25 * c) * 1.25;
|
||||
c = mix(vec3<f32>(luminance(c)), c, saturation);
|
||||
if vignette {
|
||||
let aspect = frame.resolution.x / frame.resolution.y;
|
||||
let d = length((input.uv - 0.5) * vec2<f32>(aspect, 1.0)) / length(vec2<f32>(aspect, 1.0) * 0.5);
|
||||
c *= 1.0 - smoothstep(0.55, 1.1, d) * 0.3;
|
||||
}
|
||||
return vec4<f32>(clamp(c, vec3<f32>(0.0), vec3<f32>(1.0)), input.color.a);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Warms the sky around a low sun, and deepens the blue overhead by day.
|
||||
override sun_glow: f32 = 0.6;
|
||||
|
||||
fn sky(input: SkyInput) -> vec4<f32> {
|
||||
let d = input.direction;
|
||||
let toward = max(dot(d, frame.sun_direction), 0.0);
|
||||
let near_horizon = 1.0 - smoothstep(0.0, 0.4, abs(d.y));
|
||||
let day = daylight() * (1.0 - frame.rain);
|
||||
let halo = pow(toward, 6.0) * 0.6 + near_horizon * toward * toward * 0.4;
|
||||
let warm = vec3<f32>(1.0, 0.55, 0.25) * halo * sun_low() * day * sun_glow;
|
||||
let zenith = smoothstep(0.1, 1.0, d.y) * day * 0.12;
|
||||
let base = input.color.rgb * (1.0 - zenith * vec3<f32>(0.5, 0.25, 0.0));
|
||||
return vec4<f32>(base + warm, input.color.a);
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! `horizon-shader`: make Horizon shader packs (docs/shaders.md).
|
||||
//!
|
||||
//! - `new <dir> [--template post|sky|material] [--name "Name"]`: a pack from a template.
|
||||
//! - `check <pack>... [--json]`: the check the game, the launcher and the registry run.
|
||||
//! - `pack <dir> [--out <file.hshader>]`: check, then write the reproducible `.hshader`.
|
||||
use horizon_shader_api::{EXTENSION, MANIFEST, Pack, Problem, check, package::sha256_hex};
|
||||
use serde::Serialize;
|
||||
use std::{path::Path, process::ExitCode};
|
||||
|
||||
const USAGE: &str = "usage: horizon-shader new <dir> [--template post|sky|material] [--name \"Name\"] | check <pack>... [--json] | pack <dir> [--out <file.hshader>]";
|
||||
|
||||
/// (template, its files as (name, text)).
|
||||
const TEMPLATES: [(&str, [(&str, &str); 2]); 3] = [
|
||||
(
|
||||
"post",
|
||||
[
|
||||
(
|
||||
MANIFEST,
|
||||
include_str!("../../templates/post/horizon-shaders.toml"),
|
||||
),
|
||||
("post.wgsl", include_str!("../../templates/post/post.wgsl")),
|
||||
],
|
||||
),
|
||||
(
|
||||
"sky",
|
||||
[
|
||||
(
|
||||
MANIFEST,
|
||||
include_str!("../../templates/sky/horizon-shaders.toml"),
|
||||
),
|
||||
("sky.wgsl", include_str!("../../templates/sky/sky.wgsl")),
|
||||
],
|
||||
),
|
||||
(
|
||||
"material",
|
||||
[
|
||||
(
|
||||
MANIFEST,
|
||||
include_str!("../../templates/material/horizon-shaders.toml"),
|
||||
),
|
||||
(
|
||||
"material.wgsl",
|
||||
include_str!("../../templates/material/material.wgsl"),
|
||||
),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let result = match args.first().map(String::as_str) {
|
||||
Some("new") => new(&args[1..]),
|
||||
Some("check") => check_command(&args[1..]),
|
||||
Some("pack") => pack(&args[1..]),
|
||||
_ => Err(USAGE.into()),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The value after `flag` in `args`.
|
||||
fn flag<'a>(args: &'a [String], flag: &str) -> Option<&'a str> {
|
||||
let i = args.iter().position(|a| a == flag)?;
|
||||
args.get(i + 1).map(String::as_str)
|
||||
}
|
||||
|
||||
/// The arguments that are neither flags nor their values.
|
||||
fn positional(args: &[String], flags: &[&str]) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
if flags.contains(&a.as_str()) {
|
||||
it.next();
|
||||
} else if !a.starts_with("--") {
|
||||
out.push(a.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn new(args: &[String]) -> Result<(), String> {
|
||||
let [dir] = positional(args, &["--template", "--name"])
|
||||
.try_into()
|
||||
.map_err(|_| USAGE.to_string())?;
|
||||
let dir = Path::new(&dir);
|
||||
if dir.exists() {
|
||||
return Err(format!("{} already exists", dir.display()));
|
||||
}
|
||||
let template = flag(args, "--template").unwrap_or("post");
|
||||
let (_, files) = TEMPLATES
|
||||
.iter()
|
||||
.find(|(name, _)| *name == template)
|
||||
.ok_or_else(|| format!("no template {template:?}: post, sky or material"))?;
|
||||
let base = dir
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.ok_or("the path needs a folder name")?;
|
||||
let mut id: String = base
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'a'..='z' | '0'..='9' => c,
|
||||
'A'..='Z' => c.to_ascii_lowercase(),
|
||||
_ => '_',
|
||||
})
|
||||
.collect();
|
||||
id.truncate(64);
|
||||
let name = flag(args, "--name").map_or_else(|| base.replace(['-', '_'], " "), str::to_owned);
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
for (file, text) in files {
|
||||
let text = text
|
||||
.replace("{{id}}", &id)
|
||||
.replace("{{name}}", &name.replace('"', "'"));
|
||||
let path = dir.join(file);
|
||||
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
}
|
||||
println!(
|
||||
"Made {} from the {template} template. Edit it, then: horizon-shader check {}",
|
||||
dir.display(),
|
||||
dir.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct StageJson {
|
||||
stage: &'static str,
|
||||
file: String,
|
||||
label: String,
|
||||
expressions: usize,
|
||||
texture_reads: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ProblemJson {
|
||||
file: String,
|
||||
line: usize,
|
||||
column: usize,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct CheckJson {
|
||||
path: String,
|
||||
ok: bool,
|
||||
id: Option<String>,
|
||||
version: Option<String>,
|
||||
api: Option<String>,
|
||||
/// The file's own SHA-256 (a `.hshader`), else the reproducible package's.
|
||||
sha256: Option<String>,
|
||||
stages: Vec<StageJson>,
|
||||
problems: Vec<ProblemJson>,
|
||||
}
|
||||
|
||||
/// Reads and checks the pack at `path`.
|
||||
fn check_one(path: &Path) -> CheckJson {
|
||||
let mut out = CheckJson {
|
||||
path: path.display().to_string(),
|
||||
ok: false,
|
||||
id: None,
|
||||
version: None,
|
||||
api: None,
|
||||
sha256: None,
|
||||
stages: Vec::new(),
|
||||
problems: Vec::new(),
|
||||
};
|
||||
let problem = |message: String| ProblemJson {
|
||||
file: path.display().to_string(),
|
||||
line: 0,
|
||||
column: 0,
|
||||
message,
|
||||
};
|
||||
let pack = match Pack::read(path) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
out.problems.push(problem(e));
|
||||
return out;
|
||||
}
|
||||
};
|
||||
out.id = Some(pack.manifest.id.clone());
|
||||
out.version = Some(pack.manifest.version.clone());
|
||||
out.api = Some(pack.manifest.api.clone());
|
||||
out.sha256 = if path.is_dir() {
|
||||
pack.sha256().ok()
|
||||
} else {
|
||||
std::fs::read(path).ok().map(|b| sha256_hex(&b))
|
||||
};
|
||||
match check(&pack) {
|
||||
Ok(report) => {
|
||||
out.ok = true;
|
||||
out.stages = report
|
||||
.stages
|
||||
.into_iter()
|
||||
.map(|s| StageJson {
|
||||
stage: s.kind.name(),
|
||||
file: s.file,
|
||||
label: s.label,
|
||||
expressions: s.expressions,
|
||||
texture_reads: s.texture_reads,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
Err(problems) => {
|
||||
out.problems = problems
|
||||
.into_iter()
|
||||
.map(
|
||||
|Problem {
|
||||
file,
|
||||
line,
|
||||
column,
|
||||
message,
|
||||
}| ProblemJson {
|
||||
file,
|
||||
line,
|
||||
column,
|
||||
message,
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn check_command(args: &[String]) -> Result<(), String> {
|
||||
let paths = positional(args, &[]);
|
||||
if paths.is_empty() {
|
||||
return Err(USAGE.into());
|
||||
}
|
||||
let results: Vec<CheckJson> = paths.iter().map(|p| check_one(Path::new(p))).collect();
|
||||
let failed = results.iter().filter(|r| !r.ok).count();
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
let json = serde_json::to_string_pretty(&results).map_err(|e| e.to_string())?;
|
||||
println!("{json}");
|
||||
} else {
|
||||
for r in &results {
|
||||
print_result(r);
|
||||
}
|
||||
}
|
||||
match failed {
|
||||
0 => Ok(()),
|
||||
n => Err(format!("{n} of {} packs failed the check", results.len())),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_result(r: &CheckJson) {
|
||||
let what = match (&r.id, &r.version, &r.api) {
|
||||
(Some(id), Some(v), Some(api)) => format!("{id} {v} (shader API {api})"),
|
||||
_ => r.path.clone(),
|
||||
};
|
||||
if !r.ok {
|
||||
println!("{what}: FAILED");
|
||||
for p in &r.problems {
|
||||
if p.line == 0 {
|
||||
println!(" {}: {}", p.file, p.message);
|
||||
} else {
|
||||
println!(" {}:{}:{}: {}", p.file, p.line, p.column, p.message);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
println!("{what}: ok");
|
||||
for s in &r.stages {
|
||||
println!(
|
||||
" {:<9} {:<28} {:>6} expressions, {} texture reads",
|
||||
s.stage, s.label, s.expressions, s.texture_reads
|
||||
);
|
||||
}
|
||||
if let Some(sha) = &r.sha256 {
|
||||
println!(" sha256 {sha}");
|
||||
}
|
||||
}
|
||||
|
||||
fn pack(args: &[String]) -> Result<(), String> {
|
||||
let [dir] = positional(args, &["--out"])
|
||||
.try_into()
|
||||
.map_err(|_| USAGE.to_string())?;
|
||||
let dir = Path::new(&dir)
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("{dir}: {e}"))?;
|
||||
if !dir.is_dir() {
|
||||
return Err(format!("{} is not a pack folder", dir.display()));
|
||||
}
|
||||
let dir = dir.as_path();
|
||||
let pack = Pack::read(dir)?;
|
||||
if let Err(problems) = check(&pack) {
|
||||
for p in &problems {
|
||||
eprintln!("{p}");
|
||||
}
|
||||
return Err(format!("{} failed the check", dir.display()));
|
||||
}
|
||||
let bytes = pack.package()?;
|
||||
let out = flag(args, "--out").map_or_else(
|
||||
|| {
|
||||
let m = &pack.manifest;
|
||||
dir.with_file_name(format!("{}-{}.{EXTENSION}", m.id, m.version))
|
||||
},
|
||||
Into::into,
|
||||
);
|
||||
std::fs::write(&out, &bytes).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
println!("Wrote {} (sha256 {})", out.display(), sha256_hex(&bytes));
|
||||
Ok(())
|
||||
}
|
||||
@@ -193,7 +193,7 @@ fn parse(composed: &Composed) -> Result<naga::Module, Vec<Problem>> {
|
||||
naga::front::wgsl::parse_str(&composed.text).map_err(|e| {
|
||||
let label = e.labels().next();
|
||||
let mut message = e.message().to_owned();
|
||||
if let Some((_, text)) = label.filter(|(_, t)| !t.is_empty()) {
|
||||
if let Some((_, text)) = label.filter(|(_, t)| !t.is_empty() && !message.contains(*t)) {
|
||||
message += &format!(" ({text})");
|
||||
}
|
||||
let at = label.and_then(|(span, _)| span.to_range()).map(|r| r.start);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
schema = 1
|
||||
id = "{{id}}"
|
||||
name = "{{name}}"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
description = "How block surfaces are lit."
|
||||
|
||||
[material]
|
||||
file = "material.wgsl"
|
||||
|
||||
[[options]]
|
||||
id = "contrast"
|
||||
name = "Light contrast"
|
||||
type = "float"
|
||||
default = 1.2
|
||||
min = 0.5
|
||||
max = 2.0
|
||||
step = 0.05
|
||||
@@ -0,0 +1,9 @@
|
||||
// The colour of each point of a block's surface, before the alpha test and
|
||||
// fog. Vanilla's own: albedo * tint * vec4(lightmap, 1.0).
|
||||
// Reference: docs/api/shaders-reference.md.
|
||||
override contrast: f32 = 1.2;
|
||||
|
||||
fn material(input: MaterialInput) -> Surface {
|
||||
let light = pow(input.lightmap, vec3<f32>(contrast));
|
||||
return Surface(input.albedo * input.tint * vec4<f32>(light, 1.0));
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
schema = 1
|
||||
id = "{{id}}"
|
||||
name = "{{name}}"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
description = "A post-processing pass over the world."
|
||||
|
||||
[[post]]
|
||||
file = "post.wgsl"
|
||||
name = "Colour"
|
||||
|
||||
[[options]]
|
||||
id = "saturation"
|
||||
name = "Saturation"
|
||||
type = "float"
|
||||
default = 1.15
|
||||
min = 0.0
|
||||
max = 2.0
|
||||
step = 0.05
|
||||
|
||||
[budget]
|
||||
gpu_ms = 0.5
|
||||
@@ -0,0 +1,9 @@
|
||||
// Runs once per pixel of the world's picture, under the hand and the HUD.
|
||||
// Reference: docs/api/shaders-reference.md (the inputs, `frame` and the helpers).
|
||||
override saturation: f32 = 1.15;
|
||||
|
||||
fn post(input: PostInput) -> vec4<f32> {
|
||||
let grey = dot(input.color.rgb, vec3<f32>(0.2126, 0.7152, 0.0722));
|
||||
let color = mix(vec3<f32>(grey), input.color.rgb, saturation);
|
||||
return vec4<f32>(color, input.color.a);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
schema = 1
|
||||
id = "{{id}}"
|
||||
name = "{{name}}"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
description = "A sky of its own."
|
||||
|
||||
[sky]
|
||||
file = "sky.wgsl"
|
||||
|
||||
[[options]]
|
||||
id = "glow"
|
||||
name = "Sun glow"
|
||||
type = "float"
|
||||
default = 0.5
|
||||
min = 0.0
|
||||
max = 1.0
|
||||
step = 0.05
|
||||
@@ -0,0 +1,9 @@
|
||||
// The sky's colour along each view ray; the sun, moon, stars and clouds are
|
||||
// drawn over it. Reference: docs/api/shaders-reference.md.
|
||||
override glow: f32 = 0.5;
|
||||
|
||||
fn sky(input: SkyInput) -> vec4<f32> {
|
||||
let toward_sun = max(dot(input.direction, frame.sun_direction), 0.0);
|
||||
let warm = vec3<f32>(1.0, 0.6, 0.3) * pow(toward_sun, 8.0) * glow;
|
||||
return vec4<f32>(input.color.rgb + warm, input.color.a);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! The SDK: every template and the example pack pass the check, and the
|
||||
//! `horizon-shader` tool makes, checks and packages a pack.
|
||||
use horizon_shader_api::{Pack, check};
|
||||
use std::{path::Path, process::Command};
|
||||
|
||||
const TOOL: &str = env!("CARGO_BIN_EXE_horizon-shader");
|
||||
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-shader-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> (bool, String) {
|
||||
let out = Command::new(TOOL).args(args).output().unwrap();
|
||||
let text =
|
||||
String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
|
||||
(out.status.success(), text)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_example_pack_passes() {
|
||||
let dir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/packs/golden_hour"));
|
||||
let report = check(&Pack::read(dir).unwrap()).unwrap();
|
||||
let labels: Vec<_> = report.stages.iter().map(|s| s.label.as_str()).collect();
|
||||
assert_eq!(labels, ["Warm horizon", "Glow", "Colour grade"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_template_makes_a_pack_that_passes() {
|
||||
let root = scratch("templates");
|
||||
for template in ["post", "sky", "material"] {
|
||||
let dir = root.join(format!("My-{template}"));
|
||||
let dir_s = dir.to_str().unwrap();
|
||||
let (ok, text) = run(&["new", dir_s, "--template", template]);
|
||||
assert!(ok, "{text}");
|
||||
let pack = Pack::read(&dir).unwrap();
|
||||
assert_eq!(pack.manifest.id, format!("my_{template}"));
|
||||
assert_eq!(pack.manifest.name, format!("My {template}"));
|
||||
let (ok, text) = run(&["check", dir_s]);
|
||||
assert!(ok && text.contains(": ok"), "{text}");
|
||||
}
|
||||
let (ok, text) = run(&[
|
||||
"new",
|
||||
root.join("x").to_str().unwrap(),
|
||||
"--template",
|
||||
"water",
|
||||
]);
|
||||
assert!(!ok && text.contains("no template \"water\""), "{text}");
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packs_and_checks_the_package() {
|
||||
let root = scratch("pack");
|
||||
let dir = root.join("glow");
|
||||
let dir_s = dir.to_str().unwrap();
|
||||
assert!(run(&["new", dir_s, "--name", "Glow"]).0);
|
||||
let out = root.join("glow.hshader");
|
||||
let (ok, text) = run(&["pack", dir_s, "--out", out.to_str().unwrap()]);
|
||||
assert!(ok, "{text}");
|
||||
let sha = text
|
||||
.split("sha256 ")
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.trim_end_matches([')', '\n'])
|
||||
.to_owned();
|
||||
let (ok, json) = run(&["check", out.to_str().unwrap(), "--json"]);
|
||||
assert!(ok, "{json}");
|
||||
let report: serde_json::Value = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(report[0]["ok"], true);
|
||||
assert_eq!(report[0]["id"], "glow");
|
||||
assert_eq!(report[0]["sha256"], sha.as_str());
|
||||
assert_eq!(report[0]["stages"][0]["stage"], "post");
|
||||
|
||||
std::fs::write(
|
||||
dir.join("post.wgsl"),
|
||||
"fn post(input: PostInput) -> vec4<f32> { return input.color }\n",
|
||||
)
|
||||
.unwrap();
|
||||
let (ok, json) = run(&["check", dir_s, "--json"]);
|
||||
assert!(!ok);
|
||||
let report: serde_json::Value =
|
||||
serde_json::from_str(json.split("\nerror:").next().unwrap()).unwrap();
|
||||
assert_eq!(report[0]["ok"], false);
|
||||
assert_eq!(report[0]["problems"][0]["file"], "post.wgsl");
|
||||
assert_eq!(report[0]["problems"][0]["line"], 1);
|
||||
let (ok, text) = run(&["pack", dir_s]);
|
||||
assert!(!ok && text.contains("failed the check"), "{text}");
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
@@ -13,6 +13,7 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor
|
||||
- [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured.
|
||||
- [Benchmark](benchmark.md): Horizon against vanilla 26.3 and vanilla with performance mods, on the same machine, world, path and settings: what is measured, how it is kept fair, how to reproduce it.
|
||||
- [Extras](extras.md): optional zoom, minimap, FPS and keystroke overlays and auto-reconnect, all off by default.
|
||||
- [Shader packs](shaders.md): Horizon's own WGSL shader packs, how to make and check one (`horizon-shader`).
|
||||
- [Mods](mods.md): Horizon's own mod system (Rust, sandboxed WebAssembly), how to make and install mods.
|
||||
- [Modpacks](modpacks.md): porting whole packs (ATM10 and smaller): import, inventory, carry-over, an agent per mod with a harness against the Java original, coverage, and how "10x" is measured.
|
||||
- [Launcher](../launcher/README.md): installs, updates and starts builds; its CLI and MCP server; releasing it.
|
||||
|
||||
+4
-1
@@ -81,7 +81,8 @@ the same way every time (files in path order, fixed dates), so a pack's SHA-256
|
||||
|
||||
- [shaders-reference.md](shaders-reference.md): every stage's signature, input and output structs, resources and
|
||||
helpers, the frame's fields with their units, option types and limits, generated from `crates/horizon-shader-api`.
|
||||
- The guide and an example pack come with `horizon-shader check`.
|
||||
- [The guide](../shaders.md): making a pack with `horizon-shader new`, `check` and `pack`; the templates and the
|
||||
example pack (`crates/horizon-shader-api/packs/golden_hour`).
|
||||
|
||||
## Stability
|
||||
|
||||
@@ -95,6 +96,8 @@ stages with options and hot reload, then the overlay, lighting, sky and shadow s
|
||||
|
||||
## Changelog
|
||||
|
||||
- 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).
|
||||
- 2026-10-25: the stages of API 0.1 (sky, material, post), their inputs and the generated reference.
|
||||
- 2026-10-25: the pack format, schema 1: `horizon-shaders.toml` and the `.hshader` package.
|
||||
- 2026-10-24: the earlier shader pack code was removed; this API is designed from scratch.
|
||||
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
# Horizon shader packs
|
||||
|
||||
Horizon has its own shader packs: WGSL written against stages of Horizon's renderer, checked before they run. This page
|
||||
is the guide for pack authors. The design and the pack format are in [api/shaders.md](api/shaders.md); every stage's
|
||||
signature, input, resource and limit is in the generated [api/shaders-reference.md](api/shaders-reference.md).
|
||||
|
||||
Shader packs in the Iris/OptiFine format are a separate feature with its own loader; this page is only about
|
||||
Horizon's own format.
|
||||
|
||||
| Part | Where | State |
|
||||
|---|---|---|
|
||||
| Format, stages, check | `crates/horizon-shader-api` | API 0.1, experimental |
|
||||
| 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 launcher, the registry | | not yet: the renderer hooks come next |
|
||||
|
||||
## Quick start
|
||||
|
||||
```sh
|
||||
cargo install --path crates/horizon-shader-api # or: cargo run -p horizon-shader-api --bin horizon-shader -- <command>
|
||||
horizon-shader new my_pack --template post # also: --template sky, --template material; --name "My Pack"
|
||||
horizon-shader check my_pack # what the game, the launcher and the registry will check
|
||||
horizon-shader pack my_pack # check, then write my_pack-0.1.0.hshader beside the folder
|
||||
```
|
||||
|
||||
`check` prints each stage with its cost, and the pack's SHA-256:
|
||||
|
||||
```
|
||||
golden_hour 1.0.0 (shader API 0.1): ok
|
||||
sky Warm horizon 99 expressions, 0 texture reads
|
||||
post Glow 185 expressions, 3 texture reads
|
||||
post Colour grade 201 expressions, 2 texture reads
|
||||
sha256 fd92a294...
|
||||
```
|
||||
|
||||
or every problem, at its file, line and column:
|
||||
|
||||
```
|
||||
my_pack 0.1.0 (shader API 0.1): FAILED
|
||||
post.wgsl:9:1: expected `;`, found "}"
|
||||
```
|
||||
|
||||
`--json` prints the same for tools (`ok`, `id`, `version`, `api`, `sha256`, `stages`, `problems`).
|
||||
|
||||
## A pack
|
||||
|
||||
A folder (or the same files zipped as a `.hshader`) with `horizon-shaders.toml` and WGSL files:
|
||||
|
||||
```toml
|
||||
schema = 1
|
||||
id = "my_pack"
|
||||
name = "My Pack"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
|
||||
[[post]]
|
||||
file = "post.wgsl"
|
||||
|
||||
[[options]]
|
||||
id = "saturation"
|
||||
name = "Saturation"
|
||||
type = "float"
|
||||
default = 1.15
|
||||
min = 0.0
|
||||
max = 2.0
|
||||
```
|
||||
|
||||
Every key is in [api/shaders.md](api/shaders.md#the-pack-format-schema-1).
|
||||
|
||||
## Stages
|
||||
|
||||
A stage is one function your file defines. Horizon puts its prelude (the structs, `frame`, the stage's resources and
|
||||
helpers) before your file and calls the function from its own pass, so the world is still culled, batched and meshed
|
||||
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 |
|
||||
| `[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 |
|
||||
|
||||
A pack has at least one stage; a stage it leaves out keeps vanilla's look. Each input says what vanilla would draw
|
||||
(`input.color` in the sky and post stages; `albedo * tint * vec4(lightmap, 1.0)` for a material), so a pack can start
|
||||
from vanilla and change only what it means to.
|
||||
|
||||
Every stage can read `frame`: the camera's matrices and position, the sun and moon directions, the time of day,
|
||||
vanilla's sky and fog colours, rain and thunder, fog distances, the light at the camera, effects and the dimension.
|
||||
Post passes also read `scene_color`, `scene_depth`, `previous` (the last pass's output), two samplers and the helpers
|
||||
`depth_at(uv)` and `view_position(uv, depth)`.
|
||||
|
||||
Rules the check enforces: your files declare no bindings (`@group`/`@binding`), no entry points and no names starting
|
||||
with `horizon_`. Code shared by several stages goes in files listed in `shared`, put before every stage.
|
||||
|
||||
## Options
|
||||
|
||||
Each `[[options]]` entry is a WGSL `override` of the same name, set when the game builds the pipeline: no text
|
||||
substitution, no recompiling a different program per value.
|
||||
|
||||
```wgsl
|
||||
override saturation: f32 = 1.15; // type = "float"; bool → bool, int → i32, choice → u32 (the value's index)
|
||||
```
|
||||
|
||||
The game shows the options on the pack's settings screen. Branches on an option are on a constant, so the GPU
|
||||
skips the side that isn't taken.
|
||||
|
||||
## What the check does
|
||||
|
||||
The game runs the same check when it loads a pack (a pack that fails is refused with the message, and the last good
|
||||
one keeps drawing), the launcher before it installs one, and the registry's CI before a pack is listed:
|
||||
|
||||
1. The manifest and the package: known keys, valid ids, every file used, sizes.
|
||||
2. Each stage built as the renderer builds it and validated by naga.
|
||||
3. The stage function's signature, and the rules above.
|
||||
4. Each `override` matches its option's type (or has a default); each option is used.
|
||||
5. Budgets: 20 000 expressions and 64 texture reads per stage.
|
||||
6. Every entry point translated for Vulkan (SPIR-V), Metal and DirectX 12 (HLSL), with the options at their
|
||||
defaults, minimums and maximums.
|
||||
|
||||
`[budget] gpu_ms` is the GPU time your pack aims to add to a frame; the game's overlay will show each pass's time
|
||||
against it.
|
||||
|
||||
## Next
|
||||
|
||||
The renderer hooks (shared with the Iris/OptiFine loader), then the post stage in the game with hot reload and the
|
||||
GPU time per pass, Options > Shader packs listing these packs, then the material and sky stages, and the registry's
|
||||
`shader` kind with installs from the launcher.
|
||||
Reference in New Issue
Block a user