From e38be0dbf5816338ff97e2ee2f9adfff2902dc2b Mon Sep 17 00:00:00 2001 From: skal Date: Sat, 14 Feb 2026 15:13:09 +0100 Subject: refactor(wgsl): modularize common shader functions Extracted common WGSL functions into separate files in `common/shaders/` to improve reusability and maintainability. - Created `common/shaders/render/fullscreen_vs.wgsl` for a reusable fullscreen vertex shader. - Created `common/shaders/math/color.wgsl` for color conversion and tone mapping functions. - Created `common/shaders/math/utils.wgsl` for general math utilities. - Created `common/shaders/render/raymarching.wgsl` for SDF raymarching logic. - Updated multiple shaders to use these new common snippets via `#include`. - Fixed the shader asset validation test to correctly handle shaders that include the common vertex shader. This refactoring makes the shader code more modular and easier to manage. --- common/shaders/math/color.wgsl | 27 +++++++++++++++++++++++++++ common/shaders/math/utils.wgsl | 14 ++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 common/shaders/math/color.wgsl create mode 100644 common/shaders/math/utils.wgsl (limited to 'common/shaders/math') diff --git a/common/shaders/math/color.wgsl b/common/shaders/math/color.wgsl new file mode 100644 index 0000000..b63c915 --- /dev/null +++ b/common/shaders/math/color.wgsl @@ -0,0 +1,27 @@ +// Common color space and tone mapping functions. + +// sRGB to Linear approximation +// Note: Assumes input is in sRGB color space. +fn sRGB(t: vec3) -> vec3 { + return mix(1.055 * pow(t, vec3(1.0/2.4)) - 0.055, 12.92 * t, step(t, vec3(0.0031308))); +} + +// ACES Filmic Tone Mapping (Approximate) +// A common tone mapping algorithm used in games and film. +fn aces_approx(v_in: vec3) -> vec3 { + var v = max(v_in, vec3(0.0)); + v *= 0.6; + let a = 2.51; + let b = 0.03; + let c = 2.43; + let d = 0.59; + let e = 0.14; + return clamp((v * (a * v + b)) / (v * (c * v + d) + e), vec3(0.0), vec3(1.0)); +} + +// HSV to RGB conversion +const hsv2rgb_K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); +fn hsv2rgb(c: vec3) -> vec3 { + let p = abs(fract(c.xxx + hsv2rgb_K.xyz) * 6.0 - hsv2rgb_K.www); + return c.z * mix(hsv2rgb_K.xxx, clamp(p - hsv2rgb_K.xxx, vec3(0.0), vec3(1.0)), c.y); +} diff --git a/common/shaders/math/utils.wgsl b/common/shaders/math/utils.wgsl new file mode 100644 index 0000000..85f0bdf --- /dev/null +++ b/common/shaders/math/utils.wgsl @@ -0,0 +1,14 @@ +// General-purpose math utility functions. + +// Returns a 2x2 rotation matrix. +fn rot(a: f32) -> mat2x2 { + let c = cos(a); + let s = sin(a); + return mat2x2(c, s, -s, c); +} + +// Fast approximation of tanh. +fn tanh_approx(x: f32) -> f32 { + let x2 = x * x; + return clamp(x * (27.0 + x2) / (27.0 + 9.0 * x2), -1.0, 1.0); +} -- cgit v1.2.3