New sample renderer and UI (#10)

No changes to simulation
This commit is contained in:
Erin Catto 2026-06-06 10:06:05 -07:00 • committed by GitHub
commit 9e02b7f3b3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
196 changed files with 116992 additions and 29969 deletions

View file

@ -0,0 +1,180 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Depth-only pre-pass for capsules. Mirrors
// depth_only_sphere: analytic ray-capsule hit, writes linear view-space
// depth into R32F + reverse-Z clip depth into gl_FragDepth.
#pragma sokol @module depth_only_capsule
#pragma sokol @ctype mat4 Mat4
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype vec3 b3Vec3
#pragma sokol @ctype vec2 b3Vec2
#pragma sokol @vs vs
layout(binding = 0) uniform ub_frame
{
mat4 view_proj;
};
struct instance
{
vec4 xform_row0; // .xyz = R row 0, .w = center.x
vec4 xform_row1; // .xyz = R row 1, .w = center.y
vec4 xform_row2; // .xyz = R row 2, .w = center.z
vec4 base_color; // unused, layout match
vec4 params; // .x = halfLength, .y = radius
vec4 material; // unused, layout match
};
layout(binding = 0) readonly buffer instances
{
instance items[];
};
in vec3 in_pos; // unit-cube corner, half-extent 0.5
sample out vec3 v_world_pos_proxy;
flat out vec3 v_center;
flat out float v_half_length;
flat out float v_radius;
flat out vec3 v_axis_x_world;
void main()
{
instance inst = items[gl_InstanceIndex];
vec3 center = vec3(inst.xform_row0.w, inst.xform_row1.w, inst.xform_row2.w);
float halfLength = inst.params.x;
float radius = inst.params.y;
vec3 obj_pos = vec3(
in_pos.x * 2.0 * (halfLength + radius),
in_pos.y * 2.0 * radius,
in_pos.z * 2.0 * radius
);
vec3 world_pos = center + vec3(
dot(inst.xform_row0.xyz, obj_pos),
dot(inst.xform_row1.xyz, obj_pos),
dot(inst.xform_row2.xyz, obj_pos)
);
v_world_pos_proxy = world_pos;
v_center = center;
v_half_length = halfLength;
v_radius = radius;
v_axis_x_world = vec3(inst.xform_row0.x, inst.xform_row1.x, inst.xform_row2.x);
gl_Position = view_proj * vec4(world_pos, 1.0);
}
#pragma sokol @end
#pragma sokol @fs fs
layout(binding = 1) uniform ub_pass
{
mat4 view_proj;
mat4 view;
vec4 camera_pos; // .xyz = world camera position
};
sample in vec3 v_world_pos_proxy;
flat in vec3 v_center;
flat in float v_half_length;
flat in float v_radius;
flat in vec3 v_axis_x_world;
out vec4 out_linear_depth;
void main()
{
vec3 ro = camera_pos.xyz;
vec3 rd = normalize(v_world_pos_proxy - ro);
vec3 axis = v_axis_x_world;
vec3 pa = v_center - v_half_length * axis;
vec3 pb = v_center + v_half_length * axis;
vec3 ba = pb - pa;
vec3 oa = ro - pa;
float baba = dot(ba, ba);
float bard = dot(ba, rd);
float baoa = dot(ba, oa);
float rdoa = dot(rd, oa);
float oaoa = dot(oa, oa);
float a_c = baba - bard * bard;
float b_c = baba * rdoa - baoa * bard;
float c_c = baba * oaoa - baoa * baoa - v_radius * v_radius * baba;
float h_c = b_c * b_c - a_c * c_c;
float t = -1.0;
if (h_c >= 0.0 && a_c > 1e-8)
{
float t_body = (-b_c - sqrt(h_c)) / a_c;
float y = baoa + t_body * bard;
if (t_body > 0.0 && y > 0.0 && y < baba)
{
t = t_body;
}
}
// Cap A (-X).
{
vec3 oc = ro - pa;
float b = dot(oc, rd);
float c = dot(oc, oc) - v_radius * v_radius;
float h = b * b - c;
if (h >= 0.0)
{
float tc = -b - sqrt(h);
if (tc > 0.0 &&(t < 0.0 || tc < t))
{
vec3 hit = ro + tc * rd;
if (dot(hit - pa, axis) <= 0.0)
{
t = tc;
}
}
}
}
// Cap B (+X).
{
vec3 oc = ro - pb;
float b = dot(oc, rd);
float c = dot(oc, oc) - v_radius * v_radius;
float h = b * b - c;
if (h >= 0.0)
{
float tc = -b - sqrt(h);
if (tc > 0.0 &&(t < 0.0 || tc < t))
{
vec3 hit = ro + tc * rd;
if (dot(hit - pb, axis) >= 0.0)
{
t = tc;
}
}
}
}
if (t < 0.0)
{
discard;
}
vec3 hit_world = ro + t * rd;
float view_z = -(view * vec4(hit_world, 1.0)).z;
vec4 hit_clip = view_proj * vec4(hit_world, 1.0);
gl_FragDepth = hit_clip.z / hit_clip.w;
out_linear_depth = vec4(view_z, 0.0, 0.0, 0.0);
}
#pragma sokol @end
#pragma sokol @program prog vs fs

View file

@ -0,0 +1,70 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Depth-only pre-pass for cubes. Writes positive
// linear view-space depth to an R32F color attachment, the D32F depth
// attachment is transient (rasterizer / early-Z only, never sampled). The
// full XeGTAO port reconstructs normals from depth derivatives inside
// MainPass, so the prepass produces no normal channel.
#pragma sokol @module depth_only_cube
#pragma sokol @ctype mat4 Mat4
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype vec3 b3Vec3
#pragma sokol @ctype vec2 b3Vec2
#pragma sokol @vs vs
layout(binding = 0) uniform ub_frame
{
mat4 view_proj;
mat4 view;
};
struct cube_instance
{
vec4 xform_row0;
vec4 xform_row1;
vec4 xform_row2;
vec4 base_color; // unused, layout match with lit pipeline
vec4 material; // unused, layout match with lit pipeline
};
layout(binding = 0) readonly buffer cube_instances
{
cube_instance instances[];
};
in vec3 in_pos;
out float v_linear_view_z;
void main()
{
cube_instance inst = instances[gl_InstanceIndex];
vec4 local_pos = vec4(in_pos, 1.0);
vec3 world_pos = vec3(
dot(inst.xform_row0, local_pos),
dot(inst.xform_row1, local_pos),
dot(inst.xform_row2, local_pos)
);
vec4 view_h = view * vec4(world_pos, 1.0);
v_linear_view_z = -view_h.z;
gl_Position = view_proj * vec4(world_pos, 1.0);
}
#pragma sokol @end
#pragma sokol @fs fs
in float v_linear_view_z;
out vec4 out_linear_depth;
void main()
{
out_linear_depth = vec4(v_linear_view_z, 0.0, 0.0, 0.0);
}
#pragma sokol @end
#pragma sokol @program prog vs fs

View file

@ -0,0 +1,84 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Depth-only pre-pass for triangle geometries (hulls, meshes,
// height fields). Same vertex math as the lit
// geom pipeline, FS writes positive linear view-space depth only.
#pragma sokol @module depth_only_geom
#pragma sokol @ctype mat4 Mat4
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype vec3 b3Vec3
#pragma sokol @ctype vec2 b3Vec2
#pragma sokol @vs vs
layout(binding = 0) uniform ub_frame
{
mat4 view_proj;
mat4 view;
};
layout(binding = 2) uniform ub_draw
{
ivec4 inst_base; // .x = base index into the global instance array
};
struct instance
{
vec4 xform_row0;
vec4 xform_row1;
vec4 xform_row2;
vec4 base_color; // unused, layout match
vec4 scale; // .xyz = per-instance scale
vec4 material; // unused, layout match
};
layout(binding = 0) readonly buffer instances
{
instance items[];
};
// Position-only input. The shared vertex buffer carries position+normal
// (stride 24 bytes), but this pre-pass doesn't read the normal. We just
// don't declare an `in_normal` attribute so glslang doesn't keep it
// around (and the GL driver doesn't warn about an unused attribute slot
// after stripping). The C-side pipeline desc skips the in_normal binding
// to match.
in vec3 in_pos;
out float v_linear_view_z;
void main()
{
instance inst = items[inst_base.x + gl_InstanceIndex];
vec3 scaled_pos = in_pos * inst.scale.xyz;
vec4 local_pos = vec4(scaled_pos, 1.0);
vec3 world_pos = vec3(
dot(inst.xform_row0, local_pos),
dot(inst.xform_row1, local_pos),
dot(inst.xform_row2, local_pos)
);
vec4 view_h = view * vec4(world_pos, 1.0);
v_linear_view_z = -view_h.z;
gl_Position = view_proj * vec4(world_pos, 1.0);
}
#pragma sokol @end
#pragma sokol @fs fs
in float v_linear_view_z;
out vec4 out_linear_depth;
void main()
{
out_linear_depth = vec4(v_linear_view_z, 0.0, 0.0, 0.0);
}
#pragma sokol @end
#pragma sokol @program prog vs fs

View file

@ -0,0 +1,100 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Depth-only pre-pass for spheres. Same shape as
// the lit sphere impostor: bounding-cube proxy in the VS, analytic
// ray-sphere intersection in the FS. Writes the analytic surface's linear
// view-space depth to an R32F color attachment and the reverse-Z clip
// depth to gl_FragDepth (transient D32F attachment, rasterizer only).
#pragma sokol @module depth_only_sphere
#pragma sokol @ctype mat4 Mat4
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype vec3 b3Vec3
#pragma sokol @ctype vec2 b3Vec2
#pragma sokol @vs vs
layout(binding = 0) uniform ub_frame
{
mat4 view_proj;
};
struct instance
{
vec4 xform_row0; // .w = center.x
vec4 xform_row1; // .w = center.y
vec4 xform_row2; // .w = center.z
vec4 base_color; // unused, layout match
vec4 params; // .x = radius
vec4 material; // unused, layout match
};
layout(binding = 0) readonly buffer instances
{
instance items[];
};
in vec3 in_pos; // unit-cube corner, half-extent 0.5
sample out vec3 v_world_pos_proxy;
flat out vec3 v_center;
flat out float v_radius;
void main()
{
instance inst = items[gl_InstanceIndex];
vec3 center = vec3(inst.xform_row0.w, inst.xform_row1.w, inst.xform_row2.w);
float radius = inst.params.x;
vec3 world_pos = center + (2.0 * radius) * in_pos;
v_world_pos_proxy = world_pos;
v_center = center;
v_radius = radius;
gl_Position = view_proj * vec4(world_pos, 1.0);
}
#pragma sokol @end
#pragma sokol @fs fs
layout(binding = 1) uniform ub_pass
{
mat4 view_proj; // for gl_FragDepth (reverse-Z)
mat4 view; // for linear view-space depth
vec4 camera_pos; // .xyz = world camera position
};
sample in vec3 v_world_pos_proxy;
flat in vec3 v_center;
flat in float v_radius;
out vec4 out_linear_depth;
void main()
{
vec3 ro = camera_pos.xyz;
vec3 rd = normalize(v_world_pos_proxy - ro);
vec3 oc = ro - v_center;
float b = dot(oc, rd);
float c2 = dot(oc, oc) - v_radius * v_radius;
float h = b * b - c2;
if (h < 0.0) discard;
float t = -b - sqrt(h);
if (t < 0.0) discard;
vec3 hit_world = ro + t * rd;
float view_z = -(view * vec4(hit_world, 1.0)).z;
vec4 hit_clip = view_proj * vec4(hit_world, 1.0);
gl_FragDepth = hit_clip.z / hit_clip.w;
out_linear_depth = vec4(view_z, 0.0, 0.0, 0.0);
}
#pragma sokol @end
#pragma sokol @program prog vs fs

View file

@ -0,0 +1,260 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// GTAO Denoise compute shader.
//
// Port of Esoterica's Denoise.esf (which is XeGTAO's XeGTAO_Denoise), a
// cross-bilateral 3x3 blur of the noisy AO term, weighted by the packed
// per-pixel edges that MainPass wrote alongside the noise. The renderer
// runs N dispatches per frame: (N - 1) intermediate dispatches with
// finalApply = 0 ping-pong noisy0 <-> noisy1, then one final dispatch with
// finalApply = 1 that rescales by XE_GTAO_OCCLUSION_TERM_SCALE (1.5) on
// write and lands in `result` for the lit shaders to sample. N is chosen
// renderer-side and may be 1 (final dispatch only, no intermediates).
//
// 8x8 numthreads, each thread processes 2 horizontal pixels at coords
// (2*tid.x, tid.y) and (2*tid.x + 1, tid.y). Mirrors MainPass.esf's
// "2 pixels per thread" optimization, Esoterica calls this out explicitly
// at line 52.
//
// Departures from Esoterica's Denoise.esf / XeGTAO_Denoise:
//
// * The 3 edges + 4 AO GatherRed calls in XeGTAO.esh:815-822 are
// replaced by direct texelFetch reads of the same 12-texel
// neighbourhood (4-wide x 3-tall around pixCoordBase). Same
// rationale as gtao_prefilter_depth.glsl and gtao_main_pass.glsl:
// sidesteps the textureGather channel-ordering / backend-Y-flip
// ambiguity. Cost is 24 single-channel R32F fetches vs 7 gather ops
// per thread, predictably slower but a non-issue for a debug
// renderer.
//
// * Dispatch sized as ceil(W / 16) x ceil(H / 8) workgroups (each
// workgroup writes 16 horizontal x 8 vertical pixels). Esoterica
// dispatches ceil(W / 8) x ceil(H / 8), twice as many threads in X,
// which over-covers by 2x with the surplus writes landing OOB
// (silent no-op in D3D11/Vulkan/Metal compute). The visible output
// is identical, we just skip the wasted threads. Recorded as a
// deviation.
//
// * `lpfloat` collapses to `float` (matches Esoterica's config.
// XE_GTAO_USE_HALF_FLOAT_PRECISION=0).
//
// * `AOTermType` is a plain `float`, XE_GTAO_COMPUTE_BENT_NORMALS is
// undefined on our side (matches Esoterica's default). The
// XeGTAO_DecodeGatherPartial path collapses to identity, we inline it.
//
// * `XE_GTAO_SHOW_EDGES` / `XE_GTAO_SHOW_BENT_NORMALS` debug-viz
// branches dropped, render3d uses its own debug_view_mode plumbing.
//
// * `finalApply` is delivered as a per-dispatch UBO field instead
// HLSL root constants. Lives in a small dedicated ub_denoise UBO at
// binding=1, the shared ub_gtao at binding=0 carries the same byte
// layout as the prefilter + main_pass shaders so the renderer can
// reuse one C-side build of the constants.
//
// * Bounds clamping for the 12 neighbours uses
// `clamp(coord, 0, ViewportSize - 1)` per fetch. The edge-clamped
// duplicates feed back through the same XeGTAO weighting math, same
// replicated-edge approximation Esoterica gets implicitly through
// the gather + clamp_to_edge sampler.
#pragma sokol @module gtao_denoise
#pragma sokol @ctype vec2 b3Vec2
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype mat4 Mat4
#pragma sokol @cs cs
// Per-shader subset of Esoterica's XeGTAO::GTAOConstants. Denoise only
// reads `ViewportSize` (bounds checks) and `DenoiseBlurBeta` (blur
// strength). Explicit `gtao.X` instance name prevents SPIRV-Cross
// synthesizing one (`_NNN.X`), trimming to just-the-read fields
// prevents the GL linker's per-field dead-strip from producing
// `glGetUniformLocation` warnings. See the matching comment in
// gtao_prefilter_depth.glsl.
layout( binding = 0 ) uniform ub_gtao
{
ivec2 ViewportSize;
float DenoiseBlurBeta;
}
gtao;
// NoiseIndex intentionally omitted, see gtao_prefilter_depth.glsl.
// Per-dispatch knob. `FinalApply` non-zero on the final (3rd) denoise
// dispatch, rescales the AO term by XE_GTAO_OCCLUSION_TERM_SCALE before
// writing so lit shaders see the over-bright [0, 1.5] visibility range.
layout( binding = 1 ) uniform ub_denoise
{
int FinalApply;
int _Pad0;
int _Pad1;
int _Pad2;
};
// Storage-image output (R32F, same access-format rationale as MainPass
// / PrefilterDepth: sokol-shdc / SPIRV-Cross restrict storage_image
// access formats to r32f / r32i / r32ui plus rgba/rg{32,16} variants).
layout( binding = 0, r32f ) uniform writeonly image2D out_ao;
// Sampled inputs. Bind base 1: storage images take 0..0, textures start
// at 1. Same point-clamp sampler used by every GTAO compute shader.
layout( binding = 1 ) uniform texture2D tex_edges;
layout( binding = 2 ) uniform texture2D tex_noisy_ao;
layout( binding = 0 ) uniform sampler smp_point_clamp;
#pragma sokol @include ../common/xe_gtao_common.glsl
// XeGTAO.esh:745-751, additive sample with edge weight. Inlined here
// because GLSL's lack of `inout` arrays makes the HLSL helper awkward,
// the math is unchanged.
void XeGTAO_AddSample( float ssaoValue, float edgeValue, inout float sum, inout float sumWeight )
{
float weight = edgeValue;
sum += weight * ssaoValue;
sumWeight += weight;
}
// Edge-clamped texelFetch helpers. We fetch a 4x3 neighbourhood around
// each pixel pair (pixCoordBase, pixCoordBase + (1, 0)). The diagonals
// reach one step out on each side and one step up/down, so the inclusive
// fetch range is (pixCoordBase + (-1, -1)).. (pixCoordBase + (2, 1)).
float fetchEdge( ivec2 coord )
{
ivec2 vmax = gtao.ViewportSize - 1;
ivec2 c = clamp( coord, ivec2( 0 ), vmax );
return texelFetch( sampler2D( tex_edges, smp_point_clamp ), c, 0 ).r;
}
float fetchAO( ivec2 coord )
{
ivec2 vmax = gtao.ViewportSize - 1;
ivec2 c = clamp( coord, ivec2( 0 ), vmax );
return texelFetch( sampler2D( tex_noisy_ao, smp_point_clamp ), c, 0 ).r;
}
// Output helper, XeGTAO.esh:757-774 collapsed to the "kirill: float AO
// term" patch (lines 771-772) since we always carry the float term, not
// the packed-UINT variant.
void XeGTAO_Output( ivec2 pixCoord, float outputValue, bool finalApply )
{
float scale = finalApply ? XE_GTAO_OCCLUSION_TERM_SCALE : 1.0;
imageStore( out_ao, pixCoord, vec4( outputValue * scale, 0.0, 0.0, 0.0 ) );
}
layout( local_size_x = 8, local_size_y = 8, local_size_z = 1 ) in;
void main()
{
ivec2 dispatchThreadID = ivec2( gl_GlobalInvocationID.xy );
// pixCoordBase = (2 * tid.x, tid.y). With the proper "2 horizontal
// pixels per thread" dispatch sizing (groups = ceil(W/16) x
// ceil(H/8)), tid.x ranges 0..ceil(W/16)*8 - 1, so pixCoordBase.x
// ranges 0..2*ceil(W/16)*8 - 2, at most one pixel past W when W is
// odd. The early-out + per-side bounds guard handles that tail.
ivec2 pixCoordBase = ivec2( dispatchThreadID.x * 2, dispatchThreadID.y );
if ( any( greaterThanEqual( pixCoordBase, gtao.ViewportSize ) ) )
{
return;
}
bool finalApply = ( FinalApply != 0 );
float blurAmount = finalApply ? gtao.DenoiseBlurBeta : ( gtao.DenoiseBlurBeta / 5.0 );
const float diagWeight = 0.85 * 0.5;
// 4 x 3 neighbourhood of edges + AO, indexed [x = -1..2][y = -1..1].
// Reading them up-front lets the per-side code below be a direct
// index lookup, mirroring Esoterica's per-side `visQk[index]` extracts
// from the gather results.
float edgesN[4][3];
float ao[4][3];
for ( int i = 0; i < 4; ++i )
{
for ( int j = 0; j < 3; ++j )
{
ivec2 c = pixCoordBase + ivec2( i - 1, j - 1 );
edgesN[i][j] = fetchEdge( c );
ao[i][j] = fetchAO( c );
}
}
// Process side 0 (pixel at pixCoordBase) then side 1 (pixCoordBase +
// (1, 0)). The unrolled per-side block matches XeGTAO.esh:824-892.
for ( int side = 0; side < 2; ++side )
{
ivec2 pixCoord = pixCoordBase + ivec2( side, 0 );
if ( pixCoord.x >= gtao.ViewportSize.x )
{
break;
}
// Index helpers: column `c` in the 4-wide patch corresponds to
// x = pixCoordBase.x + (c - 1). For side==0 the C column is 1
// (the L/R neighbours sit at columns 0 / 2), for side==1 the C
// column is 2 (neighbours at 1 / 3).
int cC = 1 + side;
int cL = cC - 1;
int cR = cC + 1;
vec4 edgesC_LRTB = XeGTAO_UnpackEdges( edgesN[cC][1] );
vec4 edgesL_LRTB = XeGTAO_UnpackEdges( edgesN[cL][1] );
vec4 edgesR_LRTB = XeGTAO_UnpackEdges( edgesN[cR][1] );
vec4 edgesT_LRTB = XeGTAO_UnpackEdges( edgesN[cC][0] );
vec4 edgesB_LRTB = XeGTAO_UnpackEdges( edgesN[cC][2] );
// Edge symmetricity nudge, XeGTAO.esh:836-837. Clamps the center
// pixel's per-direction edge weight against the matching edge on
// the neighbour pixel, sharpens the blur, especially under TAA
// (which we don't have, kept for A/B parity).
edgesC_LRTB *= vec4( edgesL_LRTB.y, edgesR_LRTB.x, edgesT_LRTB.w, edgesB_LRTB.z );
// Leak, XeGTAO.esh:839-843 (`#if 1` branch is the default and
// only path Esoterica ships). Allows a small amount of bleed
// when a pixel is surrounded by 3-4 edges, reducing aliasing.
const float leak_threshold = 2.5;
const float leak_strength = 0.5;
float edginess =
( clamp( 4.0 - leak_threshold - dot( edgesC_LRTB, vec4( 1.0 ) ), 0.0, 1.0 ) / ( 4.0 - leak_threshold ) ) *
leak_strength;
edgesC_LRTB = clamp( edgesC_LRTB + edginess, 0.0, 1.0 );
// Diagonal weights, XeGTAO.esh:852-855.
float weightTL = diagWeight * ( edgesC_LRTB.x * edgesL_LRTB.z + edgesC_LRTB.z * edgesT_LRTB.x );
float weightTR = diagWeight * ( edgesC_LRTB.z * edgesT_LRTB.y + edgesC_LRTB.y * edgesR_LRTB.z );
float weightBL = diagWeight * ( edgesC_LRTB.w * edgesB_LRTB.x + edgesC_LRTB.x * edgesL_LRTB.w );
float weightBR = diagWeight * ( edgesC_LRTB.y * edgesR_LRTB.w + edgesC_LRTB.w * edgesB_LRTB.y );
// AO neighbourhood for this side. Center at (cC, 1), L/R at
// (cL, 1) / (cR, 1), T/B at (cC, 0) / (cC, 2), diagonals at the
// 4 corners of the 3x3 around (cC, 1).
float ssaoValue = ao[cC][1];
float ssaoValueL = ao[cL][1];
float ssaoValueR = ao[cR][1];
float ssaoValueT = ao[cC][0];
float ssaoValueB = ao[cC][2];
float ssaoValueTL = ao[cL][0];
float ssaoValueTR = ao[cR][0];
float ssaoValueBL = ao[cL][2];
float ssaoValueBR = ao[cR][2];
float sumWeight = blurAmount;
float sum = ssaoValue * sumWeight;
XeGTAO_AddSample( ssaoValueL, edgesC_LRTB.x, sum, sumWeight );
XeGTAO_AddSample( ssaoValueR, edgesC_LRTB.y, sum, sumWeight );
XeGTAO_AddSample( ssaoValueT, edgesC_LRTB.z, sum, sumWeight );
XeGTAO_AddSample( ssaoValueB, edgesC_LRTB.w, sum, sumWeight );
XeGTAO_AddSample( ssaoValueTL, weightTL, sum, sumWeight );
XeGTAO_AddSample( ssaoValueTR, weightTR, sum, sumWeight );
XeGTAO_AddSample( ssaoValueBL, weightBL, sum, sumWeight );
XeGTAO_AddSample( ssaoValueBR, weightBR, sum, sumWeight );
float aoTerm = sum / sumWeight;
XeGTAO_Output( pixCoord, aoTerm, finalApply );
}
}
#pragma sokol @end
#pragma sokol @program prog cs

View file

@ -0,0 +1,412 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// GTAO MainPass compute shader.
//
// Port of Esoterica's MainPass.esf (which is XeGTAO's MainPass with
// XE_GTAO_GENERATE_NORMALS_INPLACE enabled). For each viewport pixel,
// reconstructs the view-space normal from depth derivatives, generates a
// Hilbert+R2 spatial noise pair, and runs the XeGTAO slice trace against
// the prefiltered depth chain. Slice count and steps-per-slice come from
// the ub_gtao UBO (the AmbientOcclusionQuality preset on the C side) rather than the
// hardcoded Ultra tier.
//
// Outputs:
// * out_noisy_ao (R32F, storage_image): the visibility term divided
// by XE_GTAO_OCCLUSION_TERM_SCALE (1.5) and saturated to [0,1].
// XeGTAO_OutputWorkingTerm's pre-denoise format. Denoise
// will multiply by 1.5 on finalApply to restore the over-bright
// occlusion term. (Deviation: Esoterica uses R16F. sokol-shdc /
// SPIRV-Cross only permit r32f/r32i/r32ui plus rgba/rg{32,16}
// variants for storage_image access formats, mirrors D3D11's
// typed-UAV restriction. R32F is the cheapest single-channel
// fp format that survives cross-compilation.)
// * out_edges (R32F, storage_image): packed edge gradients
// consumed by Denoise. Same R8->R32F deviation rationale as
// out_noisy_ao, the value range still fits in [0,1] so
// XeGTAO_UnpackEdges on the read side is unchanged.
//
// Departures from Esoterica's MainPass.esf:
//
// * Cardinal depth taps (center, L, R, T, B) use texelFetch on the raw
// depth target instead of two GatherRed calls. Two reasons: avoids
// the GatherRed channel-ordering / backend Y-flip ambiguity, and
// matches the same pattern already adopted by
// gtao_prefilter_depth.glsl.
//
// * The trace samples DO use textureLod since they sample at fractional
// mip levels, texelFetch can't pick a mip. The prefilter chain was
// written by the PrefilterDepth compute via imageStore, so the
// UV->texel mapping is internally consistent within the chain even
// across backends (no fragment-shader Y-flip in the producer).
//
// * `lpfloat` collapses to `float` (XE_GTAO_USE_HALF_FLOAT_PRECISION=0,
// XE_GTAO_FP32_DEPTHS=1, matches Esoterica's config).
//
// * SpatioTemporalNoise is called with temporalIndex=0 hardcoded
// (no TAA), producing the same noise pattern every frame. The
// original NoiseIndex UBO field is gone, see the comment under
// ub_gtao.
//
// * The "early-out for OOB threads" at the top of MainPass.esf is kept.
// Unlike PrefilterDepth there is no inter-thread groupshared
// reduction, so divergent control flow at the top is safe (no
// barriers).
#pragma sokol @module gtao_main_pass
#pragma sokol @ctype vec2 b3Vec2
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype mat4 Mat4
#pragma sokol @cs cs
// Per-shader subset of Esoterica's XeGTAO::GTAOConstants, only the
// fields MainPass actually reads (14 of 16). Explicit `gtao.X` instance
// name prevents SPIRV-Cross synthesizing one (`_NNN.X`), trimming to
// just-the-read fields prevents the GL linker's per-field dead-strip
// from producing `glGetUniformLocation` warnings. See the matching
// comment in gtao_prefilter_depth.glsl.
layout( binding = 0 ) uniform ub_gtao
{
ivec2 ViewportSize;
vec2 ViewportPixelSize;
vec2 NDCToViewMul;
vec2 NDCToViewAdd;
vec2 NDCToViewMul_x_PixelSize;
float EffectRadius;
float EffectFalloffRange;
float RadiusMultiplier;
float FinalValuePower;
float SampleDistributionPower;
float ThinOccluderCompensation;
float DepthMIPSamplingOffset;
// Runtime trace quality: slice count and steps-per-slice. Driven by
// the AmbientOcclusionQuality preset on the C side (Low/Medium/High/Ultra), the
// trace loops read these instead of hardcoded Ultra-tier constants.
float SliceCount;
float StepsPerSlice;
}
gtao;
// NoiseIndex intentionally omitted, see gtao_prefilter_depth.glsl.
// Storage-image outputs. Bindings 0..1. r32f instead of r16f/r8 (see
// header, sokol-shdc storage_image access-format restriction).
layout( binding = 0, r32f ) uniform writeonly image2D out_noisy_ao;
layout( binding = 1, r32f ) uniform writeonly image2D out_edges;
// Sampled textures. Binding base 2 (sokol-shdc shares the
// storage_image/texture bind-space across the compute stage, storage
// images take 0..1, so textures start at 2). The sampler is point-clamp,
// linear sampling on a prefiltered depth chain would inter-mip-level
// blend depth values which corrupts the trace (see XeGTAO.esh:476).
layout( binding = 2 ) uniform texture2D tex_raw_depth;
layout( binding = 3 ) uniform texture2D tex_prefilter_depth;
layout( binding = 0 ) uniform sampler smp_point_clamp;
#pragma sokol @include ../common/xe_gtao_common.glsl
// SpatioTemporalNoise, MainPass.esf:43-60 with the
// XE_GTAO_HILBERT_LUT_AVAILABLE branch removed (we generate the index
// in-shader, mirrors Esoterica's default). With NoiseIndex=0 the
// `288 * (temporalIndex % 64)` term is zero, the (288*0) is kept as a
// no-op so this function reads verbatim against the reference.
vec2 SpatioTemporalNoise( uvec2 pixCoord, int temporalIndex )
{
uint index = HilbertIndex( pixCoord.x, pixCoord.y );
index += 288u * ( uint( temporalIndex ) % 64u );
// R2 sequence, Roberts 2018.
return fract( 0.5 + float( index ) * vec2( 0.75487766624669276005, 0.5698402909980532659114 ) );
}
// XeGTAO.esh:897-921 with cardinal taps coming from texelFetch instead
// of GatherRed (see header). Identical math.
vec3 XeGTAO_ComputeViewspaceNormal( ivec2 pixCoord, GTAOConsts consts )
{
vec2 normalizedScreenPos = ( vec2( pixCoord ) + 0.5 ) * consts.ViewportPixelSize;
// Clamp the 4 cardinal taps into the viewport. At the viewport edge
// we replicate the center pixel, same approximation as gather-with-
// sampler-clamp.
ivec2 vmax = gtao.ViewportSize - 1;
ivec2 cC = clamp( pixCoord, ivec2( 0 ), vmax );
ivec2 cL = clamp( pixCoord + ivec2( -1, 0 ), ivec2( 0 ), vmax );
ivec2 cR = clamp( pixCoord + ivec2( 1, 0 ), ivec2( 0 ), vmax );
ivec2 cT = clamp( pixCoord + ivec2( 0, -1 ), ivec2( 0 ), vmax );
ivec2 cB = clamp( pixCoord + ivec2( 0, 1 ), ivec2( 0 ), vmax );
float viewspaceZ =
XeGTAO_ScreenSpaceToViewSpaceDepth( texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), cC, 0 ).r, consts );
float pixLZ =
XeGTAO_ScreenSpaceToViewSpaceDepth( texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), cL, 0 ).r, consts );
float pixRZ =
XeGTAO_ScreenSpaceToViewSpaceDepth( texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), cR, 0 ).r, consts );
float pixTZ =
XeGTAO_ScreenSpaceToViewSpaceDepth( texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), cT, 0 ).r, consts );
float pixBZ =
XeGTAO_ScreenSpaceToViewSpaceDepth( texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), cB, 0 ).r, consts );
vec4 edgesLRTB = XeGTAO_CalculateEdges( viewspaceZ, pixLZ, pixRZ, pixTZ, pixBZ );
vec3 CENTER = XeGTAO_ComputeViewspacePosition( normalizedScreenPos, viewspaceZ, consts );
vec3 LEFT =
XeGTAO_ComputeViewspacePosition( normalizedScreenPos + vec2( -1.0, 0.0 ) * consts.ViewportPixelSize, pixLZ, consts );
vec3 RIGHT =
XeGTAO_ComputeViewspacePosition( normalizedScreenPos + vec2( 1.0, 0.0 ) * consts.ViewportPixelSize, pixRZ, consts );
vec3 TOP =
XeGTAO_ComputeViewspacePosition( normalizedScreenPos + vec2( 0.0, -1.0 ) * consts.ViewportPixelSize, pixTZ, consts );
vec3 BOTTOM =
XeGTAO_ComputeViewspacePosition( normalizedScreenPos + vec2( 0.0, 1.0 ) * consts.ViewportPixelSize, pixBZ, consts );
return XeGTAO_CalculateNormal( edgesLRTB, CENTER, LEFT, RIGHT, TOP, BOTTOM );
}
// XeGTAO.esh:213-231. Stores the visibility/scale-divided term and
// returns it. `bentNormal` arg dropped, XE_GTAO_COMPUTE_BENT_NORMALS is
// undefined on our side (matches Esoterica).
float XeGTAO_OutputWorkingTerm( ivec2 pixCoord, float visibility )
{
visibility = clamp( visibility / XE_GTAO_OCCLUSION_TERM_SCALE, 0.0, 1.0 );
imageStore( out_noisy_ao, pixCoord, vec4( visibility, 0.0, 0.0, 0.0 ) );
return visibility;
}
// XeGTAO.esh:270-617 with:
// * Cardinal taps via texelFetch (see header).
// * Bent-normals branch (`XE_GTAO_COMPUTE_BENT_NORMALS`) removed,
// undefined in our config.
// * In-place normals branch (`XE_GTAO_GENERATE_NORMALS_INPLACE`) always
// taken. The cardinal-tap reads above already happened, so this
// is just the same XeGTAO_CalculateNormal call as in
// XeGTAO_ComputeViewspaceNormal. We share the call by computing the
// normal in main before invoking MainPass, and pass it in.
// * Debug-viz (`XE_GTAO_SHOW_DEBUG_VIZ`, `XE_GTAO_SHOW_NORMALS`, etc.)
// branches dropped, we use the renderer's debug_view_mode plumbing
// instead.
// * `sliceCount`/`stepsPerSlice` come from the ub_gtao UBO (the
// AmbientOcclusionQuality preset on the C side), not the hardcoded 9/3 Ultra tier of
// MainPass.esf:135. The two `for` loops iterate `float` counters with a
// `<` comparison so the runtime bound cross-compiles cleanly, the
// trade-off is the inner loop can no longer be statically unrolled.
// * Edges are packed and written before the trace, exactly as in
// MainPass.esf. The Denoise pass reads them as bilateral weights.
//
// pixCoord = dispatchThreadID.xy. Returns the saturated visibility scalar
// for visualisation in the renderer's debug_view_mode == 4.
float XeGTAO_MainPass( ivec2 pixCoord, vec2 localNoise, vec3 viewspaceNormal,
float centerViewspaceZ, // value already fetched for normal recon
vec4 edgesLRTB, // ditto, written below
GTAOConsts consts )
{
vec2 normalizedScreenPos = ( vec2( pixCoord ) + 0.5 ) * consts.ViewportPixelSize;
float viewspaceZ = centerViewspaceZ;
imageStore( out_edges, pixCoord, vec4( XeGTAO_PackEdges( edgesLRTB ), 0.0, 0.0, 0.0 ) );
// FP32 depth: push the center pixel slightly towards camera to avoid
// self-occlusion from depth imprecision. XeGTAO.esh:318-322. With
// positive linear view-Z + reverse-Z, "towards camera" is multiply by
// (1 - epsilon).
viewspaceZ *= 0.99999;
vec3 pixCenterPos = XeGTAO_ComputeViewspacePosition( normalizedScreenPos, viewspaceZ, consts );
vec3 viewVec = normalize( -pixCenterPos );
float sliceCount = consts.SliceCount;
float stepsPerSlice = consts.StepsPerSlice;
const float effectRadius = consts.EffectRadius * consts.RadiusMultiplier;
const float falloffRange = consts.EffectFalloffRange * effectRadius;
const float falloffFrom = effectRadius * ( 1.0 - consts.EffectFalloffRange );
const float falloffMul = -1.0 / falloffRange;
const float falloffAdd = falloffFrom / falloffRange + 1.0;
const float sampleDistributionPower = consts.SampleDistributionPower;
const float thinOccluderCompensation = consts.ThinOccluderCompensation;
float visibility = 0.0;
{
const float noiseSlice = localNoise.x;
const float noiseSample = localNoise.y;
const float pixelTooCloseThreshold = 1.3;
// Approx viewspace pixel size at pixCoord. XeGTAO.esh:377.
vec2 pixelDirRBViewspaceSizeAtCenterZ = vec2( viewspaceZ, viewspaceZ ) * consts.NDCToViewMul_x_PixelSize;
float screenspaceRadius = effectRadius / pixelDirRBViewspaceSizeAtCenterZ.x;
// Fade out for small screen radii, XeGTAO.esh:382.
visibility += clamp( ( 10.0 - screenspaceRadius ) / 100.0, 0.0, 1.0 ) * 0.5;
float minS = pixelTooCloseThreshold / screenspaceRadius;
for ( float slice = 0.0; slice < sliceCount; slice += 1.0 )
{
float sliceK = ( slice + noiseSlice ) / sliceCount;
float phi = sliceK * XE_GTAO_PI;
float cosPhi = cos( phi );
float sinPhi = sin( phi );
vec2 omega = vec2( cosPhi, -sinPhi );
omega *= screenspaceRadius;
vec3 directionVec = vec3( cosPhi, sinPhi, 0.0 );
vec3 orthoDirectionVec = directionVec - ( dot( directionVec, viewVec ) * viewVec );
vec3 axisVec = normalize( cross( orthoDirectionVec, viewVec ) );
vec3 projectedNormalVec = viewspaceNormal - axisVec * dot( viewspaceNormal, axisVec );
float signNorm = sign( dot( orthoDirectionVec, projectedNormalVec ) );
float projectedNormalVecLength = length( projectedNormalVec );
float cosNorm = clamp( dot( projectedNormalVec, viewVec ) / projectedNormalVecLength, 0.0, 1.0 );
float n = signNorm * XeGTAO_FastACos( cosNorm );
const float lowHorizonCos0 = cos( n + XE_GTAO_PI_HALF );
const float lowHorizonCos1 = cos( n - XE_GTAO_PI_HALF );
float horizonCos0 = lowHorizonCos0;
float horizonCos1 = lowHorizonCos1;
for ( float step_ = 0.0; step_ < stepsPerSlice; step_ += 1.0 )
{
// R1 sequence, XeGTAO.esh:459.
float stepBaseNoise = ( slice + step_ * stepsPerSlice ) * 0.6180339887498948482;
float stepNoise = fract( noiseSample + stepBaseNoise );
float s = ( step_ + stepNoise ) / stepsPerSlice;
// step_, stepNoise (=fract(.)), stepsPerSlice are all >= 0
// by construction, max(0, .) is redundant at runtime but
// silences HLSL's pow(negative, n) warning (X3571).
s = pow( max( 0.0, s ), sampleDistributionPower );
s += minS;
vec2 sampleOffset = s * omega;
float sampleOffsetLength = length( sampleOffset );
float mipLevel =
clamp( log2( sampleOffsetLength ) - consts.DepthMIPSamplingOffset, 0.0, XE_GTAO_DEPTH_MIP_LEVELS );
// Snap to pixel centers, XeGTAO.esh:481.
sampleOffset = round( sampleOffset ) * consts.ViewportPixelSize;
vec2 sampleScreenPos0 = normalizedScreenPos + sampleOffset;
float SZ0 = textureLod( sampler2D( tex_prefilter_depth, smp_point_clamp ), sampleScreenPos0, mipLevel ).x;
vec3 samplePos0 = XeGTAO_ComputeViewspacePosition( sampleScreenPos0, SZ0, consts );
vec2 sampleScreenPos1 = normalizedScreenPos - sampleOffset;
float SZ1 = textureLod( sampler2D( tex_prefilter_depth, smp_point_clamp ), sampleScreenPos1, mipLevel ).x;
vec3 samplePos1 = XeGTAO_ComputeViewspacePosition( sampleScreenPos1, SZ1, consts );
vec3 sampleDelta0 = samplePos0 - pixCenterPos;
vec3 sampleDelta1 = samplePos1 - pixCenterPos;
float sampleDist0 = length( sampleDelta0 );
float sampleDist1 = length( sampleDelta1 );
vec3 sampleHorizonVec0 = sampleDelta0 / sampleDist0;
vec3 sampleHorizonVec1 = sampleDelta1 / sampleDist1;
// Esoterica branch: thin-object heuristic (XeGTAO.esh:518-524).
// XE_GTAO_USE_DEFAULT_CONSTANTS=0 path so falloffBase uses
// thinOccluderCompensation. With thinOccluderCompensation = 0
// this is equivalent to the simpler XeGTAO.esh:516-517 form
// since the z-axis factor becomes 1.
float falloffBase0 =
length( vec3( sampleDelta0.x, sampleDelta0.y, sampleDelta0.z * ( 1.0 + thinOccluderCompensation ) ) );
float falloffBase1 =
length( vec3( sampleDelta1.x, sampleDelta1.y, sampleDelta1.z * ( 1.0 + thinOccluderCompensation ) ) );
float weight0 = clamp( falloffBase0 * falloffMul + falloffAdd, 0.0, 1.0 );
float weight1 = clamp( falloffBase1 * falloffMul + falloffAdd, 0.0, 1.0 );
float shc0 = dot( sampleHorizonVec0, viewVec );
float shc1 = dot( sampleHorizonVec1, viewVec );
shc0 = mix( lowHorizonCos0, shc0, weight0 );
shc1 = mix( lowHorizonCos1, shc1, weight1 );
horizonCos0 = max( horizonCos0, shc0 );
horizonCos1 = max( horizonCos1, shc1 );
}
// Slight over-darkening fudge, XeGTAO.esh:571.
projectedNormalVecLength = mix( projectedNormalVecLength, 1.0, 0.05 );
float h0 = -XeGTAO_FastACos( horizonCos1 );
float h1 = XeGTAO_FastACos( horizonCos0 );
float iarc0 = ( cosNorm + 2.0 * h0 * sin( n ) - cos( 2.0 * h0 - n ) ) * 0.25;
float iarc1 = ( cosNorm + 2.0 * h1 * sin( n ) - cos( 2.0 * h1 - n ) ) * 0.25;
float localVisibility = projectedNormalVecLength * ( iarc0 + iarc1 );
visibility += localVisibility;
}
visibility /= sliceCount;
// visibility is summed from non-negative localVisibility terms and
// divided by positive sliceCount, so always >= 0. max(0, .) is a
// no-op at runtime, silences HLSL's pow(negative, n) warning.
visibility = pow( max( 0.0, visibility ), consts.FinalValuePower );
// Disallow total occlusion, XeGTAO.esh:597.
visibility = max( 0.03, visibility );
}
return XeGTAO_OutputWorkingTerm( pixCoord, visibility );
}
layout( local_size_x = 8, local_size_y = 8, local_size_z = 1 ) in;
void main()
{
ivec2 pixCoord = ivec2( gl_GlobalInvocationID.xy );
if ( any( greaterThanEqual( pixCoord, gtao.ViewportSize ) ) )
{
return;
}
// Populate GTAOConsts from the UBO, gives the helpers in
// xe_gtao_common.glsl + the inlined XeGTAO_MainPass a single by-
// value argument matching the HLSL reference.
GTAOConsts consts;
consts.ViewportPixelSize = gtao.ViewportPixelSize;
consts.NDCToViewMul = gtao.NDCToViewMul;
consts.NDCToViewAdd = gtao.NDCToViewAdd;
consts.NDCToViewMul_x_PixelSize = gtao.NDCToViewMul_x_PixelSize;
consts.EffectRadius = gtao.EffectRadius;
consts.EffectFalloffRange = gtao.EffectFalloffRange;
consts.RadiusMultiplier = gtao.RadiusMultiplier;
consts.FinalValuePower = gtao.FinalValuePower;
consts.SampleDistributionPower = gtao.SampleDistributionPower;
consts.ThinOccluderCompensation = gtao.ThinOccluderCompensation;
consts.DepthMIPSamplingOffset = gtao.DepthMIPSamplingOffset;
consts.SliceCount = gtao.SliceCount;
consts.StepsPerSlice = gtao.StepsPerSlice;
// Cardinal-tap reads happen inside ComputeViewspaceNormal, redo the
// center read so MainPass has its viewspaceZ + edges without
// re-fetching the 4 neighbours. Cheaper to repeat the 1-tap fetch
// than to plumb the 5-tap state through a return struct.
vec3 viewspaceNormal = XeGTAO_ComputeViewspaceNormal( pixCoord, consts );
ivec2 vmax = gtao.ViewportSize - 1;
float centerZ = XeGTAO_ScreenSpaceToViewSpaceDepth(
texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), clamp( pixCoord, ivec2( 0 ), vmax ), 0 ).r, consts );
float leftZ = XeGTAO_ScreenSpaceToViewSpaceDepth(
texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), clamp( pixCoord + ivec2( -1, 0 ), ivec2( 0 ), vmax ), 0 ).r,
consts );
float rightZ = XeGTAO_ScreenSpaceToViewSpaceDepth(
texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), clamp( pixCoord + ivec2( 1, 0 ), ivec2( 0 ), vmax ), 0 ).r,
consts );
float topZ = XeGTAO_ScreenSpaceToViewSpaceDepth(
texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), clamp( pixCoord + ivec2( 0, -1 ), ivec2( 0 ), vmax ), 0 ).r,
consts );
float botZ = XeGTAO_ScreenSpaceToViewSpaceDepth(
texelFetch( sampler2D( tex_raw_depth, smp_point_clamp ), clamp( pixCoord + ivec2( 0, 1 ), ivec2( 0 ), vmax ), 0 ).r,
consts );
vec4 edgesLRTB = XeGTAO_CalculateEdges( centerZ, leftZ, rightZ, topZ, botZ );
vec2 noise = SpatioTemporalNoise( uvec2( pixCoord ), 0 );
XeGTAO_MainPass( pixCoord, noise, viewspaceNormal, centerZ, edgesLRTB, consts );
}
#pragma sokol @end
#pragma sokol @program prog cs

View file

@ -0,0 +1,248 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// GTAO PrefilterDepth compute shader.
//
// Port of Esoterica's PrefilterDepth.esf, which is XeGTAO's
// XeGTAO_PrefilterDepths16x16, a single 16x16-pixel tile per group,
// 8x8 threads, each thread handling 2x2 destination pixels. Builds the
// 5-mip prefiltered linear-depth chain consumed by the GTAO main pass.
// Mip0 is the raw input, mips 1..4 use the XeGTAO weighted-
// average depth-MIP filter which biases toward the closer of the four
// taps in each 2x2 footprint (suppresses thin-feature pulled mips).
//
// Departures from XeGTAO_PrefilterDepths16x16:
//
// * Input depth is **already positive linear view-Z** (render3d's
// R32F prepass target), not NDC reverse-Z. Esoterica's
// XeGTAO_ScreenSpaceToViewSpaceDepth call collapses to a pass-
// through, we just clamp. GTAOConstants.DepthUnpackConsts is
// therefore unused (kept in the UBO for layout parity).
//
// * Mip-0 fetches use texelFetch on the source texture instead
// GatherRed + offset(1,1). The mathematical result is identical
// (point-sampled raw texels at a 2x2 footprint), but texelFetch
// sidesteps the documented textureGather channel-ordering /
// Y-flip pitfalls. Cost is 4 texel reads vs 1 gather op,
// a single dispatch per frame, doesn't matter.
//
// * lpfloat is `float`. Matches Esoterica's
// XE_GTAO_USE_HALF_FLOAT_PRECISION=0 / XE_GTAO_FP32_DEPTHS=1
// configuration, min16float / float16_t paths don't survive
// sokol-shdc cleanly.
//
// Dispatch: ceil(width / 16) x ceil(height / 16) x 1. Each group writes
// a 16x16 mip-0 region, 8x8 mip-1, 4x4 mip-2, 2x2 mip-3, 1x1 mip-4.
//
// Esoterica early-returns OOB threads at the top of the shader. FXC
// (D3D11) rejects that as "thread sync operation in varying flow"
// (HLSL X3663) when the subsequent barrier participations diverge.
// We instead let every thread run the full reduction so all barriers
// see uniform participation, and guard each imageStore individually
// against the viewport bound. Source-texel reads are clamped to the
// in-bounds edge so OOB threads contribute consistent (replicated-
// edge) depth values to the mip-1..4 reductions. These values are
// only used to keep the groupshared scratch populated, the actual
// mip writes for those threads are skipped by the bounds guard.
#pragma sokol @module gtao_prefilter_depth
#pragma sokol @ctype vec2 b3Vec2
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype mat4 Mat4
#pragma sokol @cs cs
// Per-shader subset of Esoterica's XeGTAO::GTAOConstants, only the
// fields PrefilterDepth's `XeGTAO_DepthMIPFilter` and `main ` actually
// read. The block has an explicit instance name (`gtao.X`) so SPIRV-
// Cross doesn't synthesize one (`_NNN.X`) when emitting GLSL for the GL
// backend. Without that, each unread field that the driver's GLSL
// linker dead-strips triggers a sokol_gfx `glGetUniformLocation` warning
// with an unreadable synthetic name. Keeping the block trimmed to only
// the read fields means there's nothing for the linker to strip.
layout(binding = 0) uniform ub_gtao
{
ivec2 ViewportSize;
float EffectRadius;
float EffectFalloffRange;
float RadiusMultiplier;
} gtao;
// Outputs: one storage_image per mip level. R32F write-only. Each mip
// has its own bind slot (0..4), sokol-gfx wires each to a sg_view that
// targets a specific mip of the 5-mip prefilterDepth image.
layout(binding = 0, r32f) uniform writeonly image2D out_depth0;
layout(binding = 1, r32f) uniform writeonly image2D out_depth1;
layout(binding = 2, r32f) uniform writeonly image2D out_depth2;
layout(binding = 3, r32f) uniform writeonly image2D out_depth3;
layout(binding = 4, r32f) uniform writeonly image2D out_depth4;
// Source: full-res positive linear view-Z. Bound as a sampled texture so
// texelFetch is available. The sampler is point-clamp (texelFetch ignores
// it but sokol-gfx requires a sampler binding for any texture binding).
// Binding 5 because sokol-shdc shares the storage_image/texture bind-
// space across the compute stage even though the underlying backends
// use disjoint SRV/UAV register banks, storage images take 0..4 so the
// texture starts at 5.
layout(binding = 5) uniform texture2D tex_src_depth;
layout(binding = 0) uniform sampler smp_src_depth;
// XeGTAO_ClampDepth, clamps to fp32 finite. Matches XeGTAO.esh:648-655
// for the XE_GTAO_USE_HALF_FLOAT_PRECISION=0 branch (FLT_MAX upper
// bound). Our sky sentinel of 1e9 sits comfortably below this.
float XeGTAO_ClampDepth(float depth) {
return clamp(depth, 0.0, 3.402823466e+38);
}
// XeGTAO_DepthMIPFilter, weighted average that biases toward the
// closest tap (smallest depth) and suppresses contributions from taps
// outside an effect-radius-scaled falloff window. Verbatim port
// XeGTAO.esh:619-644, with XE_GTAO_USE_DEFAULT_CONSTANTS=0 branches
// since we drive everything from the UBO.
float XeGTAO_DepthMIPFilter(float depth0, float depth1, float depth2, float depth3) {
float maxDepth = max(max(depth0, depth1), max(depth2, depth3));
const float depthRangeScaleFactor = 0.75; // "found empirically :)" XeGTAO.esh:624
float effectRadius = depthRangeScaleFactor * gtao.EffectRadius * gtao.RadiusMultiplier;
float falloffRange = gtao.EffectFalloffRange * effectRadius;
float falloffFrom = effectRadius * (1.0 - gtao.EffectFalloffRange);
float falloffMul = -1.0 / falloffRange;
float falloffAdd = falloffFrom / falloffRange + 1.0;
float weight0 = clamp((maxDepth - depth0) * falloffMul + falloffAdd, 0.0, 1.0);
float weight1 = clamp((maxDepth - depth1) * falloffMul + falloffAdd, 0.0, 1.0);
float weight2 = clamp((maxDepth - depth2) * falloffMul + falloffAdd, 0.0, 1.0);
float weight3 = clamp((maxDepth - depth3) * falloffMul + falloffAdd, 0.0, 1.0);
float weightSum = weight0 + weight1 + weight2 + weight3;
return (weight0 * depth0 + weight1 * depth1 +
weight2 * depth2 + weight3 * depth3) / weightSum;
}
// Mip-2..4 inter-thread reduction scratch. groupshared, written by the
// mip-N producer threads and read by the mip-(N+1) producers after a
// barrier. Mirrors XeGTAO.esh:657.
shared float g_scratchDepths[8][8];
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1)in;
void main() {
ivec2 dispatchThreadID = ivec2(gl_GlobalInvocationID.xy);
ivec2 groupThreadID = ivec2(gl_LocalInvocationID.xy);
ivec2 viewportMax = ivec2(gtao.ViewportSize) - 1;
// MIP 0
// Esoterica reads via GatherRed at the texel-corner UV with offset
// (1,1), we read the same four texels via texelFetch to avoid the
// textureGather channel-ordering / backend-Y-flip ambiguity (see
// header). Indexing matches Esoterica's (depth0, depth1, depth2,
// depth3) = (top-left, top-right, bottom-left, bottom-right) within
// the 2x2 destination block. Source coords are clamped to the
// in-bounds edge so OOB threads still feed valid (replicated-edge)
// depths into the mip-1..4 reductions, the actual mip writes for
// those threads are gated below.
ivec2 pixCoord = dispatchThreadID * 2;
ivec2 p0 = clamp(pixCoord + ivec2(0, 0), ivec2(0), viewportMax);
ivec2 p1 = clamp(pixCoord + ivec2(1, 0), ivec2(0), viewportMax);
ivec2 p2 = clamp(pixCoord + ivec2(0, 1), ivec2(0), viewportMax);
ivec2 p3 = clamp(pixCoord + ivec2(1, 1), ivec2(0), viewportMax);
float depth0 = XeGTAO_ClampDepth(texelFetch(sampler2D(tex_src_depth, smp_src_depth), p0, 0).r);
float depth1 = XeGTAO_ClampDepth(texelFetch(sampler2D(tex_src_depth, smp_src_depth), p1, 0).r);
float depth2 = XeGTAO_ClampDepth(texelFetch(sampler2D(tex_src_depth, smp_src_depth), p2, 0).r);
float depth3 = XeGTAO_ClampDepth(texelFetch(sampler2D(tex_src_depth, smp_src_depth), p3, 0).r);
if (all(lessThan(pixCoord + ivec2(0, 0), ivec2(gtao.ViewportSize)))) {
imageStore(out_depth0, pixCoord + ivec2(0, 0), vec4(depth0, 0.0, 0.0, 0.0));
}
if (all(lessThan(pixCoord + ivec2(1, 0), ivec2(gtao.ViewportSize)))) {
imageStore(out_depth0, pixCoord + ivec2(1, 0), vec4(depth1, 0.0, 0.0, 0.0));
}
if (all(lessThan(pixCoord + ivec2(0, 1), ivec2(gtao.ViewportSize)))) {
imageStore(out_depth0, pixCoord + ivec2(0, 1), vec4(depth2, 0.0, 0.0, 0.0));
}
if (all(lessThan(pixCoord + ivec2(1, 1), ivec2(gtao.ViewportSize)))) {
imageStore(out_depth0, pixCoord + ivec2(1, 1), vec4(depth3, 0.0, 0.0, 0.0));
}
// MIP 1
// Every thread produces one mip-1 candidate (always stored in
// scratch so the mip-2 reduction has a uniform view), conditionally
// written to the mip-1 image only if dispatchThreadID is in bounds.
float dm1 = XeGTAO_DepthMIPFilter(depth0, depth1, depth2, depth3);
if (all(lessThan(dispatchThreadID, ivec2(gtao.ViewportSize)))) {
imageStore(out_depth1, dispatchThreadID, vec4(dm1, 0.0, 0.0, 0.0));
}
g_scratchDepths[groupThreadID.x][groupThreadID.y] = dm1;
barrier();
// MIP 2
// 2x2 reduction over the group's 8x8 mip-1 footprint, one thread per
// mip-2 texel, picked at the (x%2,y%2)==(0,0) corner. Reads stride 1.
// The reduction itself happens uniformly (predicated only on local
// group coords), the bounds check gates the imageStore, never the
// barrier path.
float dm2 = 0.0;
bool isMip2Producer = all(equal(groupThreadID & ivec2(1), ivec2(0)));
if (isMip2Producer) {
float inTL = g_scratchDepths[groupThreadID.x + 0][groupThreadID.y + 0];
float inTR = g_scratchDepths[groupThreadID.x + 1][groupThreadID.y + 0];
float inBL = g_scratchDepths[groupThreadID.x + 0][groupThreadID.y + 1];
float inBR = g_scratchDepths[groupThreadID.x + 1][groupThreadID.y + 1];
dm2 = XeGTAO_DepthMIPFilter(inTL, inTR, inBL, inBR);
// gl_GlobalInvocationID is unsigned by spec -> dispatchThreadID is
// always >= 0, so an unsigned right-shift produces the same value as
// `dispatchThreadID / 2` without the HLSL signed-divide warning
// (X3556). Compute once + reuse for the bounds-check + imageStore.
ivec2 dispatchID2 = ivec2(uvec2(dispatchThreadID) >> 1u);
if (all(lessThan(dispatchID2, ivec2(gtao.ViewportSize)))) {
imageStore(out_depth2, dispatchID2, vec4(dm2, 0.0, 0.0, 0.0));
}
g_scratchDepths[groupThreadID.x][groupThreadID.y] = dm2;
}
barrier();
// MIP 3
// Reads stride 2 from the same scratch slab, one mip-3 texel per
// 4x4 thread block, picked at the (x%4,y%4)==(0,0) corner.
float dm3 = 0.0;
bool isMip3Producer = all(equal(groupThreadID & ivec2(3), ivec2(0)));
if (isMip3Producer) {
float inTL = g_scratchDepths[groupThreadID.x + 0][groupThreadID.y + 0];
float inTR = g_scratchDepths[groupThreadID.x + 2][groupThreadID.y + 0];
float inBL = g_scratchDepths[groupThreadID.x + 0][groupThreadID.y + 2];
float inBR = g_scratchDepths[groupThreadID.x + 2][groupThreadID.y + 2];
dm3 = XeGTAO_DepthMIPFilter(inTL, inTR, inBL, inBR);
ivec2 dispatchID4 = ivec2(uvec2(dispatchThreadID) >> 2u);
if (all(lessThan(dispatchID4, ivec2(gtao.ViewportSize)))) {
imageStore(out_depth3, dispatchID4, vec4(dm3, 0.0, 0.0, 0.0));
}
g_scratchDepths[groupThreadID.x][groupThreadID.y] = dm3;
}
barrier();
// MIP 4
// Final reduction, single thread per group writes a single texel.
// Esoterica's commented-out scratch write at the end is dead code
// (no consumer), we drop the comment.
if (all(equal(groupThreadID, ivec2(0)))) {
float inTL = g_scratchDepths[0][0];
float inTR = g_scratchDepths[4][0];
float inBL = g_scratchDepths[0][4];
float inBR = g_scratchDepths[4][4];
float dm4 = XeGTAO_DepthMIPFilter(inTL, inTR, inBL, inBR);
ivec2 dispatchID8 = ivec2(uvec2(dispatchThreadID) >> 3u);
if (all(lessThan(dispatchID8, ivec2(gtao.ViewportSize)))) {
imageStore(out_depth4, dispatchID8, vec4(dm4, 0.0, 0.0, 0.0));
}
}
}
#pragma sokol @end
#pragma sokol @program prog cs

View file

@ -0,0 +1,132 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Highlight outline post-pass.
//
// Fullscreen triangle (no vbuf). Reads the R8 UNORM highlight mask written by
// the mask_sphere/mask_capsule/mask_hull pipelines. Each non-zero pixel is
// inside a highlighted shape (encoded 0.5 = hover, 1.0 = select). The shader
// detects silhouette pixels (center is empty but a neighbor is filled)
// and emits the appropriate outline color premultiplied for blend-over the
// resolved scene color.
//
// Two ring radii tunable from C: hoverThicknessPx, selectThicknessPx.
// Select takes priority over hover when both rings catch a neighbor.
#pragma sokol @module highlight_outline
#pragma sokol @ctype vec4 Vec4
#pragma sokol @vs vs
// Fullscreen triangle by gl_VertexIndex, 3 verts covering NDC
// [-1, 3] x [-1, 3], clipped to the [-1,1] viewport. No vertex buffer.
void main()
{
vec2 p = vec2( ( gl_VertexIndex == 1 ) ? 3.0 : -1.0, ( gl_VertexIndex == 2 ) ? 3.0 : -1.0 );
gl_Position = vec4( p, 0.0, 1.0 );
}
#pragma sokol @end
#pragma sokol @fs fs
layout( binding = 0 ) uniform ub_pass
{
vec4 hover_color; // premultiplied linear RGBA
vec4 select_color; // premultiplied linear RGBA
vec4 thickness_px; // .x = hover thickness, .y = select thickness, .zw unused
};
layout( binding = 0 ) uniform texture2D tex_mask;
layout( binding = 0 ) uniform sampler smp_mask;
layout( location = 0 ) out vec4 out_color;
// Discrete-kind threshold. 0.5 encodes hover, 1.0 encodes select. Threshold
// at 0.75 splits them. Values < 0.25 are "empty".
const float KIND_EMPTY_THRESHOLD = 0.25;
const float KIND_SELECT_THRESHOLD = 0.75;
void main()
{
ivec2 px = ivec2( gl_FragCoord.xy );
ivec2 sz = textureSize( sampler2D( tex_mask, smp_mask ), 0 );
// Inside a highlighted shape, keep the scene color (output 0 alpha).
float center = texelFetch( sampler2D( tex_mask, smp_mask ), px, 0 ).x;
if ( center > KIND_EMPTY_THRESHOLD )
{
out_color = vec4( 0.0 );
return;
}
int hoverR = clamp( int( thickness_px.x + 0.5 ), 1, 4 );
int selectR = clamp( int( thickness_px.y + 0.5 ), 1, 4 );
int maxR = max( hoverR, selectR );
// Track the strongest neighbor kind found, and the smallest radius at
// which we found a select-kind / hover-kind neighbor. The outline rules:
// * a select-kind pixel anywhere within selectR -> draw select
// * else a hover-kind pixel within hoverR -> draw hover
// * else a hover-kind pixel within selectR -> still draw hover
// (so the wider ring of a hover-only shape stays visible if the
// user widened thickness).
bool sawSelectInSelectR = false;
bool sawHoverInHoverR = false;
bool sawHoverInSelectR = false;
for ( int r = 1; r <= maxR; ++r )
{
for ( int i = 0; i < 4; ++i )
{
ivec2 off;
if ( i == 0 )
off = ivec2( r, 0 );
else if ( i == 1 )
off = ivec2( -r, 0 );
else if ( i == 2 )
off = ivec2( 0, r );
else
off = ivec2( 0, -r );
ivec2 q = px + off;
if ( q.x < 0 || q.y < 0 || q.x >= sz.x || q.y >= sz.y )
continue;
float k = texelFetch( sampler2D( tex_mask, smp_mask ), q, 0 ).x;
if ( k <= KIND_EMPTY_THRESHOLD )
continue;
if ( k >= KIND_SELECT_THRESHOLD )
{
if ( r <= selectR )
sawSelectInSelectR = true;
}
else
{
if ( r <= hoverR )
sawHoverInHoverR = true;
if ( r <= selectR )
sawHoverInSelectR = true;
}
}
}
if ( sawSelectInSelectR )
{
out_color = select_color;
return;
}
if ( sawHoverInHoverR )
{
out_color = hover_color;
return;
}
if ( sawHoverInSelectR )
{
out_color = hover_color;
return;
}
out_color = vec4( 0.0 );
}
#pragma sokol @end
#pragma sokol @program prog vs fs

View file

@ -0,0 +1,164 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Highlight mask, capsule impostor.
//
// Stripped sibling of depth_only_capsule. Same OBB proxy + analytic
// ray-capsule intersection in the FS, outputs a uint highlight kind to the
// R8_UINT mask attachment. Writes gl_FragDepth so the GREATER_EQUAL depth
// test compares against the prepass depth at the analytic surface.
#pragma sokol @module mask_capsule
#pragma sokol @ctype mat4 Mat4
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype vec3 b3Vec3
#pragma sokol @vs vs
layout( binding = 0 ) uniform ub_frame
{
mat4 view_proj;
};
struct instance
{
vec4 xform_row0; // .xyz = R row 0, .w = center.x
vec4 xform_row1; // .xyz = R row 1, .w = center.y
vec4 xform_row2; // .xyz = R row 2, .w = center.z
vec4 params; // .x = halfLength, .y = radius, .z = highlight kind (float)
};
layout( binding = 0 ) readonly buffer instances
{
instance items[];
};
in vec3 in_pos; // unit-cube corner, half-extent 0.5
sample out vec3 v_world_pos_proxy;
flat out vec3 v_center;
flat out float v_half_length;
flat out float v_radius;
flat out vec3 v_axis_x_world;
flat out float v_kind;
void main()
{
instance inst = items[gl_InstanceIndex];
vec3 center = vec3( inst.xform_row0.w, inst.xform_row1.w, inst.xform_row2.w );
float halfLength = inst.params.x;
float radius = inst.params.y;
vec3 obj_pos = vec3( in_pos.x * 2.0 * ( halfLength + radius ), in_pos.y * 2.0 * radius, in_pos.z * 2.0 * radius );
vec3 world_pos = center + vec3( dot( inst.xform_row0.xyz, obj_pos ), dot( inst.xform_row1.xyz, obj_pos ),
dot( inst.xform_row2.xyz, obj_pos ) );
v_world_pos_proxy = world_pos;
v_center = center;
v_half_length = halfLength;
v_radius = radius;
v_axis_x_world = vec3( inst.xform_row0.x, inst.xform_row1.x, inst.xform_row2.x );
v_kind = inst.params.z;
gl_Position = view_proj * vec4( world_pos, 1.0 );
}
#pragma sokol @end
#pragma sokol @fs fs
layout( binding = 1 ) uniform ub_pass
{
mat4 view_proj; // for reverse-Z gl_FragDepth
vec4 camera_pos; // .xyz = world camera position
};
sample in vec3 v_world_pos_proxy;
flat in vec3 v_center;
flat in float v_half_length;
flat in float v_radius;
flat in vec3 v_axis_x_world;
flat in float v_kind;
layout( location = 0 ) out vec4 out_kind;
void main()
{
vec3 ro = camera_pos.xyz;
vec3 rd = normalize( v_world_pos_proxy - ro );
vec3 axis = v_axis_x_world;
vec3 pa = v_center - v_half_length * axis;
vec3 pb = v_center + v_half_length * axis;
vec3 ba = pb - pa;
vec3 oa = ro - pa;
float baba = dot( ba, ba );
float bard = dot( ba, rd );
float baoa = dot( ba, oa );
float rdoa = dot( rd, oa );
float oaoa = dot( oa, oa );
float a_c = baba - bard * bard;
float b_c = baba * rdoa - baoa * bard;
float c_c = baba * oaoa - baoa * baoa - v_radius * v_radius * baba;
float h_c = b_c * b_c - a_c * c_c;
float t = -1.0;
if ( h_c >= 0.0 && a_c > 1e-8 )
{
float t_body = ( -b_c - sqrt( h_c ) ) / a_c;
float y = baoa + t_body * bard;
if ( t_body > 0.0 && y > 0.0 && y < baba )
{
t = t_body;
}
}
// Cap A.
{
vec3 oc = ro - pa;
float b = dot( oc, rd );
float c = dot( oc, oc ) - v_radius * v_radius;
float h = b * b - c;
if ( h >= 0.0 )
{
float tc = -b - sqrt( h );
if ( tc > 0.0 && ( t < 0.0 || tc < t ) )
{
vec3 hit = ro + tc * rd;
if ( dot( hit - pa, axis ) <= 0.0 )
t = tc;
}
}
}
// Cap B.
{
vec3 oc = ro - pb;
float b = dot( oc, rd );
float c = dot( oc, oc ) - v_radius * v_radius;
float h = b * b - c;
if ( h >= 0.0 )
{
float tc = -b - sqrt( h );
if ( tc > 0.0 && ( t < 0.0 || tc < t ) )
{
vec3 hit = ro + tc * rd;
if ( dot( hit - pb, axis ) >= 0.0 )
t = tc;
}
}
}
if ( t < 0.0 )
discard;
vec3 hit_world = ro + t * rd;
vec4 hit_clip = view_proj * vec4( hit_world, 1.0 );
gl_FragDepth = hit_clip.z / hit_clip.w;
// R8 UNORM mask: 1.0=hover, 2.0=select -> 0.5, 1.0.
out_kind = vec4( v_kind * 0.5, 0.0, 0.0, 1.0 );
}
#pragma sokol @end
#pragma sokol @program prog vs fs

View file

@ -0,0 +1,78 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Highlight mask, convex hull (triangle-rasterized).
//
// Same vertex math as depth_only_geom (transform + per-instance scale), but the
// FS just emits the highlight kind into the R8_UINT mask. Rasterized depth
// is correct as-is, no gl_FragDepth write. Pipeline depth-tests GREATER_EQUAL
// against the prepass depth.
#pragma sokol @module mask_hull
#pragma sokol @ctype mat4 Mat4
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype vec3 b3Vec3
#pragma sokol @vs vs
layout( binding = 0 ) uniform ub_frame
{
mat4 view_proj;
};
layout( binding = 2 ) uniform ub_draw
{
ivec4 inst_base; // .x = base index into the hull-mask instance array
};
struct instance
{
vec4 xform_row0;
vec4 xform_row1;
vec4 xform_row2;
vec4 scale_kind; // .xyz = per-instance scale, .w = highlight kind
};
layout( binding = 0 ) readonly buffer instances
{
instance items[];
};
// Position-only input. The shared geom vbo carries position+normal
// (stride 24 bytes), but the mask FS only needs world position. We
// don't declare an `in_normal` attribute so the GL linker doesn't strip
// it and warn. The C-side pipeline desc skips the in_normal binding to
// match.
in vec3 in_pos;
flat out float v_kind;
void main()
{
instance inst = items[inst_base.x + gl_InstanceIndex];
vec3 scaled_pos = in_pos * inst.scale_kind.xyz;
vec4 local_pos = vec4( scaled_pos, 1.0 );
vec3 world_pos =
vec3( dot( inst.xform_row0, local_pos ), dot( inst.xform_row1, local_pos ), dot( inst.xform_row2, local_pos ) );
v_kind = inst.scale_kind.w;
gl_Position = view_proj * vec4( world_pos, 1.0 );
}
#pragma sokol @end
#pragma sokol @fs fs
flat in float v_kind;
layout( location = 0 ) out vec4 out_kind;
void main()
{
// R8 UNORM mask: 1.0=hover, 2.0=select -> 0.5, 1.0.
out_kind = vec4( v_kind * 0.5, 0.0, 0.0, 1.0 );
}
#pragma sokol @end
#pragma sokol @program prog vs fs

View file

@ -0,0 +1,103 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Highlight mask, sphere impostor.
//
// Stripped sibling of depth_only_sphere. Same bounding-cube proxy + analytic
// ray-sphere intersection in the FS, outputs a uint highlight kind to the
// R8_UINT mask attachment instead of writing depth. Depth-TEST against the
// existing GTAO prepass depth (reverse-Z GREATER, no depth write) so
// highlighted shapes behind opaque geometry don't bleed outlines.
#pragma sokol @module mask_sphere
#pragma sokol @ctype mat4 Mat4
#pragma sokol @ctype vec4 Vec4
#pragma sokol @ctype vec3 b3Vec3
#pragma sokol @vs vs
layout( binding = 0 ) uniform ub_frame
{
mat4 view_proj;
};
struct instance
{
vec4 center_radius; // .xyz = center, .w = radius
vec4 kind; // .x = highlight kind (1.0 = hover, 2.0 = select), .yzw unused
};
layout( binding = 0 ) readonly buffer instances
{
instance items[];
};
in vec3 in_pos; // unit-cube corner, half-extent 0.5
sample out vec3 v_world_pos_proxy;
flat out vec3 v_center;
flat out float v_radius;
flat out float v_kind;
void main()
{
instance inst = items[gl_InstanceIndex];
vec3 center = inst.center_radius.xyz;
float radius = inst.center_radius.w;
vec3 world_pos = center + ( 2.0 * radius ) * in_pos;
v_world_pos_proxy = world_pos;
v_center = center;
v_radius = radius;
v_kind = inst.kind.x;
gl_Position = view_proj * vec4( world_pos, 1.0 );
}
#pragma sokol @end
#pragma sokol @fs fs
layout( binding = 1 ) uniform ub_pass
{
mat4 view_proj; // for reverse-Z gl_FragDepth
vec4 camera_pos; // .xyz = world camera position
};
sample in vec3 v_world_pos_proxy;
flat in vec3 v_center;
flat in float v_radius;
flat in float v_kind;
layout( location = 0 ) out vec4 out_kind;
void main()
{
vec3 ro = camera_pos.xyz;
vec3 rd = normalize( v_world_pos_proxy - ro );
vec3 oc = ro - v_center;
float b = dot( oc, rd );
float c2 = dot( oc, oc ) - v_radius * v_radius;
float h = b * b - c2;
if ( h < 0.0 )
discard;
float t = -b - sqrt( h );
if ( t < 0.0 )
discard;
// Write analytic surface depth so the depth test compares at the
// sphere's true surface, not at the bounding-cube proxy. Matches the
// prepass depth's contents bit-for-bit, so GREATER_EQUAL passes when
// unoccluded and fails when an opaque shape is in front.
vec3 hit_world = ro + t * rd;
vec4 hit_clip = view_proj * vec4( hit_world, 1.0 );
gl_FragDepth = hit_clip.z / hit_clip.w;
// R8 UNORM mask: 1.0=hover, 2.0=select -> 0.5, 1.0.
out_kind = vec4( v_kind * 0.5, 0.0, 0.0, 1.0 );
}
#pragma sokol @end
#pragma sokol @program prog vs fs

View file

@ -0,0 +1,138 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// AgX tonemap fullscreen pass.
//
// Reads the resolved HDR scene color (RGBA16F), applies an exposure stop,
// runs AgX (Standard look, identity ASC-CDL), and writes display-encoded
// sRGB to a linear-format (non-sRGB) framebuffer.
//
// Implementation is the "Minimal AgX" port of Troy Sobotka's reference
// (https://iolite-engine.com/blog_posts/minimal_agx_implementation),
// the same shader form used by Three.js and Filament. The 6th-order
// polynomial in agxDefaultContrastApprox is a fit of the AgX sigmoid,
// mean error^2 vs. the reference curve is ~3.7e-6.
//
// Color path:
// 1. linear sRGB HDR (scene)
// 2. x exposure (pow(2, ev))
// 3. AgX inset matrix -> "AgX color space"
// 4. clamp(log2(.), MIN_EV, MAX_EV) -> [0,1] log-space
// 5. polynomial sigmoid -> [0,1] log-space, S-shaped
// 6. AgX look -> luma-preserving saturation (params.z, 1.0 = identity)
// 7. AgX outset matrix -> display-encoded sRGB (no further EOTF)
//
// Output target format is linear unorm (BGRA8/RGBA8, NOT SRGB), so the
// outset-matrix result writes verbatim, no pow(., 2.2) at the end. If
// the target ever becomes sRGB-formatted (driver does linear->sRGB encode
// on store), add `v = pow(max(v, 0.0), vec3(2.2))` after the outset
// matrix to give the driver linear values.
//
// UV handling: the scene RT was written by the rasterizer at SV_Position
// (top-origin on D3D11/Metal/WGPU, bottom-origin on GL). Sampling it here
// with `v_uv = ndc * 0.5 + 0.5` reads the wrong row on D3D11/Metal/WGPU
// because v_uv.y=1 always means "max-V texel", which is top on GL but
// bottom on the others. The C side passes a backend-conditional uvYSign
// (+1 GL, -1 D3D/Metal/WGPU), we flip v_uv.y at sample time on the
// negative-sign backends. Same pattern as brdf_lut.glsl, just applied at
// the consumer (sample-time) instead of the producer (write-time).
#pragma sokol @module tonemap
#pragma sokol @ctype vec4 Vec4
#pragma sokol @vs vs
out vec2 v_uv;
void main()
{
vec2 ndc = vec2( float( ( gl_VertexIndex << 1 ) & 2 ), float( gl_VertexIndex & 2 ) ) * 2.0 - 1.0;
v_uv = ndc * 0.5 + 0.5;
gl_Position = vec4( ndc, 0.0, 1.0 );
}
#pragma sokol @end
#pragma sokol @fs fs
layout( binding = 0 ) uniform ub_tonemap
{
// .x = ev (exposure stops, final multiplier = pow(2, ev))
// .y = uvYSign (+1 GL, -1 D3D11/Metal/WGPU), flips sample-time v_uv.y
// so the scene RT reads back upright on every backend.
// .z = AgX look saturation (1.0 = identity / stock AgX Standard look)
// .w reserved
vec4 params;
};
layout( binding = 0 ) uniform texture2D tex_scene;
layout( binding = 0 ) uniform sampler smp_scene;
in vec2 v_uv;
out vec4 out_color;
// 6th-order polynomial fit of the AgX sigmoid (Sobotka). Operates on the
// [0,1] log-space encoded value, output stays in [0,1] log-space but
// S-shaped to match the AgX contrast curve.
vec3 agxDefaultContrastApprox( vec3 x )
{
vec3 x2 = x * x;
vec3 x4 = x2 * x2;
return +15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232;
}
vec3 agx( vec3 v )
{
// Inset matrix: linear sRGB primaries -> AgX inset primaries.
const mat3 inset = mat3( 0.842479062253094, 0.0423282422610123, 0.0423756549057051, 0.0784335999999992, 0.878468636469772,
0.0784336, 0.0792237451477643, 0.0791661274605434, 0.879142973793104 );
const float MIN_EV = -12.47393;
const float MAX_EV = 4.026069;
v = inset * v;
// Floor to a tiny positive so log2 stays finite at black.
v = max( v, vec3( 1.0e-10 ) );
v = clamp( log2( v ), MIN_EV, MAX_EV );
v = ( v - MIN_EV ) / ( MAX_EV - MIN_EV );
v = agxDefaultContrastApprox( v );
return v;
}
vec3 agxOutset( vec3 v )
{
// Inverse of the inset matrix, brings the sigmoid output back to display
// sRGB primaries. Result is display-encoded sRGB (ready for an unorm RT).
const mat3 outset = mat3( 1.19687900512017, -0.0528968517574562, -0.0529716355144438, -0.0980208811401368, 1.15190312990417,
-0.0980434501171241, -0.0990297440797205, -0.0989611768448433, 1.15107367264116 );
return outset * v;
}
// AgX "look": luma-preserving saturation, applied to the sigmoid output
// while it's still in AgX-encoded [0,1] space (before the outset matrix).
// saturation 1.0 is identity: AgX's stock Standard look. AgX walks bright
// colors toward white ("path to white"), which reads as desaturation.
// saturation > 1.0 pushes them back out, < 1.0 mutes them. Rec.709 luma
// weights hold perceived brightness fixed. The reference Minimal AgX look
// also exposes per-channel slope/power ("Punchy"/"Golden" presets), we
// wire only saturation, the one knob this debug renderer needs.
vec3 agxLook( vec3 v, float saturation )
{
const vec3 LUMA = vec3( 0.2126, 0.7152, 0.0722 );
float luma = dot( v, LUMA );
return luma + saturation * ( v - luma );
}
void main()
{
// Backend-conditional v_uv.y flip: when params.y < 0 (D3D11/Metal/WGPU),
// replace v_uv.y with (1 - v_uv.y) so the sample reads the correct row.
// Equivalent to `mix(1.0-y, y, step(0.0, params.y))` but cheaper.
float sampleY = ( params.y > 0.0 ) ? v_uv.y : ( 1.0 - v_uv.y );
vec3 hdr = textureLod( sampler2D( tex_scene, smp_scene ), vec2( v_uv.x, sampleY ), 0.0 ).rgb;
hdr *= pow( 2.0, params.x );
vec3 ldr = agxOutset( agxLook( agx( hdr ), params.z ) );
out_color = vec4( clamp( ldr, 0.0, 1.0 ), 1.0 );
}
#pragma sokol @end
#pragma sokol @program prog vs fs