Add soft sun shadows (PCSS) through a translator patch

The deferred lighting shaders take the sun shadow as four explicit-LOD compares on the cascade array. Translator patch
0010 turns every explicit-LOD compare on a 2D array texture into a PCSS lookup when the support buffer's new pcss
field has x above 0: eight raw depth fetches within pcss.w find the blockers, (receiver - blocker) * pcss.x gives the
penumbra width clamped to pcss.y..pcss.z, and eight compares on a disc of that radius average to the result. With x at
0 the original single compare runs behind a branch. Radii are in UV, so they hold at any shadow_scale.

The support buffer grows to 1424 bytes; support_fill writes the field from pcss (percent of the default width, 0 to
200, default 0; TOTK_PCSS_K overrides the factor at 100 percent, default 0.5). build_xlate.py expects ten patches. The
setting is in totk.ini.example and on the Screen tab of the menu (English and Russian).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
itaskaev2andClaude Opus 5.5 committed 2026-10-30 16:00:23 +01:00
1 parent 4af60604de
commit 24571ec0b0
8 files changed
+174 -6

No files matched your search

+3 -2
View File
@@ -41,7 +41,7 @@ static const char *const known[] = {
"GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MENU_LANG", "MENU_TEST",
"MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE",
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
"PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
"PROFILE_MAIN", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REEXEC",
"RENDER_SCALE", "REPLAY_ASYNC",
@@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = {
{"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"},
{"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"},
{"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"},
{"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"},
{"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"PCSS", "display"},
{"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"},
{"VOLUME", "audio"},
{"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"},
@@ -95,6 +95,7 @@ static const CfgMeta metas[] = {
{"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE},
{"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART},
{"SHADOW_RANGE", "100", "50..400", RESTART}, {"CONTACT_SHADOWS", "0", "0..100", RESTART},
{"PCSS", "0", "0..200", RESTART},
// Game
{"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE},
{"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART},
+1
View File
@@ -550,6 +550,7 @@ static void tab_screen(float scale) {
row_aniso();
row_shadow_scale();
row_shadow_range();
opt_slider("TOTK_PCSS", UI_MENU_PCSS, 0, 200, UI_MENU_PCSS_DESC, 10, "%.0f %%");
opt_slider("TOTK_CONTACT_SHADOWS", UI_MENU_CONTACT_SHADOWS, 0, 100, UI_MENU_CONTACT_SHADOWS_DESC, 10, "%.0f %%");
opt_end();
}
+6
View File
@@ -70,6 +70,9 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_SHADOW_SCALE] = "Shadow resolution",
[UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: "
"sharper shadow edges and leaf shadows. Takes effect at the next start.",
[UI_MENU_PCSS] = "Soft shadows",
[UI_MENU_PCSS_DESC] = "Sun shadows sharp where an object meets the ground and softer the further the shadow falls "
"(PCSS). 0 keeps the game's filter. Takes effect at the next start.",
[UI_MENU_CONTACT_SHADOWS] = "Contact shadows",
[UI_MENU_CONTACT_SHADOWS_DESC] = "Small sun shadows the shadow maps miss: at feet, under stones, in grass and creases. "
"Traced on the screen after lighting. Takes effect at the next start.",
@@ -302,6 +305,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_SHADOW_SCALE] = "Разрешение теней",
[UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 "
"самой игры: края теней и тени листвы чётче. Действует после перезапуска.",
[UI_MENU_PCSS] = "Мягкие тени",
[UI_MENU_PCSS_DESC] = "Тени от солнца резкие там, где предмет касается земли, и мягче, чем дальше падает тень "
"(PCSS). 0 оставляет фильтр игры. Действует после перезапуска.",
[UI_MENU_CONTACT_SHADOWS] = "Контактные тени",
[UI_MENU_CONTACT_SHADOWS_DESC] = "Мелкие тени от солнца, которых нет на картах теней: у ног, под камнями, в траве и "
"складках. Считаются по экрану после освещения. Действует после перезапуска.",
+1
View File
@@ -40,6 +40,7 @@ typedef enum {
UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC,
UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC,
UI_MENU_CONTACT_SHADOWS, UI_MENU_CONTACT_SHADOWS_DESC,
UI_MENU_PCSS, UI_MENU_PCSS_DESC,
// Game
UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144,
+21 -1
View File
@@ -32,7 +32,7 @@
#define MAX_DESC 1024
#define CHUNK_BYTES (4u << 20)
#define ZERO_BYTES 65536u
#define SUPPORT_BYTES 1408u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ...
#define SUPPORT_BYTES 1424u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ...
#define NVN_STAGE_VS 0
#define NVN_STAGE_FS 1
#define NVN_STAGE_CS 5
@@ -1246,6 +1246,25 @@ static void support_in(const VkExec *ex, float in[3]) { // what support_fill r
in[2] = ex->point_size > 0 ? ex->point_size : 1.0f;
}
// TOTK_PCSS (percent, 0 = off): the pcss field of the support buffer, which translator patch 0010 reads in every
// explicit-LOD compare on a 2D array texture (the sun cascades). x: penumbra width in UV per unit of light-space depth
// between receiver and blocker (0 keeps the game's single compare), y and z: the narrowest and widest disc radius,
// w: the blocker search radius, all in UV of the cascade map. Radii are in UV, so they hold at any TOTK_SHADOW_SCALE.
// TOTK_PCSS_K overrides the depth-to-penumbra factor at 100 percent, for tuning.
static const float *pcss_params(void) {
static float p[4] = {-1, 0, 0, 0};
if (p[0] < 0) {
int pct = cfg_int("TOTK_PCSS");
pct = pct < 0 ? 0 : pct > 200 ? 200 : pct;
const char *k = cfg_get("TOTK_PCSS_K");
float k100 = k && *k ? (float)atof(k) : 0.5f;
p[0] = k100 * (float)pct / 100.0f;
p[1] = 0.35f / 960.0f, p[2] = 5.0f / 960.0f, p[3] = 4.0f / 960.0f;
if (pct) rt_log("vk: soft shadows (PCSS) at %d%% (depth factor %g)", pct, p[0]);
}
return p;
}
static void support_fill(uint8_t *b, float w, float h, float point_size) {
memset(b, 0, SUPPORT_BYTES);
float inv[4] = {w > 0 ? 2.0f / w : 0, h > 0 ? 2.0f / h : 0, 0, 0}, size[4] = {w, h, 0, 0};
@@ -1253,6 +1272,7 @@ static void support_fill(uint8_t *b, float w, float h, float point_size) {
memcpy(b + 160, size, 16);
const float one = 1.0f;
memcpy(b + 1392, &point_size, 4); // point_size (translator patch 0008): vertex shaders that write none output it
memcpy(b + 1408, pcss_params(), 16); // pcss (translator patch 0010): soft sun shadows in the cascade compares
for (int i = 0; i < 73; i++) memcpy(b + 192 + 16 * i, &one, 4); // render scale 1: the host renders at guest size
}
+3 -3
View File
@@ -1,7 +1,7 @@
"""Build the shader translator: build/xlate/totk_xlate.exe (Ryujinx 1.3.2 + patches, NativeAOT, SPIR-V for Vulkan).
Copies tools/vendor/ryujinx to build/xlate/ryujinx, applies tools/xlate/patches/*.patch there (tools/vendor stays
byte-identical; 0001-0004 are MNG's, 0005-0009 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build
byte-identical; 0001-0004 are MNG's, 0005-0010 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build
tools and vswhere.exe (docs/building.md). Run with .venv.
Next to the exe it writes totk_xlate.id: the translator identity, a sha256 over everything the build reads (this script,
@@ -96,8 +96,8 @@ def prepare_sources() -> Path:
for junk in list(src.glob("src/*/obj")) + list(src.glob("src/*/bin")):
shutil.rmtree(junk)
patches = sorted((XLATE / "patches").glob("*.patch"))
if len(patches) != 9:
sys.exit(f"expected 9 patches, found {len(patches)}")
if len(patches) != 10:
sys.exit(f"expected 10 patches, found {len(patches)}")
for patch in patches:
# git apply works outside a repository when given a directory; --check first so a failure names the patch.
for extra in (["--check"], []):
@@ -0,0 +1,135 @@
--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs
+++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs
@@ -1456,7 +1456,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
}
else if (isShadow)
{
- if (hasLodLevel)
+ if (hasLodLevel && isArray && coordsCount == 2 && operandsMask == ImageOperandsMask.Lod)
+ {
+ result = GeneratePcssSample(context, declaration, image, pCoords, dRef, lod);
+ }
+ else if (hasLodLevel)
{
result = context.ImageSampleDrefExplicitLod(resultType, image, pCoords, dRef, operandsMask, operands);
}
@@ -1486,6 +1490,92 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
return new OperationResult(swizzledResultType, result);
}
+ // TOTK: percentage-closer soft shadows for the sun. The deferred lighting shaders take the shadow as four
+ // explicit-LOD compares on a 2D array (the cascades) around the receiver; each of those becomes a PCSS lookup
+ // when the support buffer's pcss.x is above 0 (runtime/vk_exec_draw.c support_fill, TOTK_PCSS): a blocker
+ // search reads the raw depths at eight points within pcss.w (UV), the average depth of those nearer the light
+ // than the receiver gives the penumbra width (receiver - blocker) * pcss.x, clamped to pcss.y..pcss.z (UV), and
+ // eight compares on a disc of that radius average to the result. With pcss.x at 0 the original single compare
+ // runs. The cascades are orthographic, so the depth difference is a distance along the light.
+ private static readonly float[] PcssSearch = [-0.7f, -0.7f, 0.7f, -0.7f, -0.7f, 0.7f, 0.7f, 0.7f, 0f, -1f, 0f, 1f, -1f, 0f, 1f, 0f];
+ private static readonly float[] PcssDisk =
+ [
+ -0.9420f, -0.3991f, 0.9456f, -0.7689f, -0.0942f, -0.9294f, 0.3450f, 0.2939f,
+ -0.9159f, 0.4577f, -0.8154f, -0.8791f, -0.3828f, 0.2768f, 0.9748f, 0.7565f,
+ ];
+
+ private static SpvInstruction GeneratePcssSample(CodeGenContext context, SamplerDeclaration declaration, SpvInstruction image,
+ SpvInstruction pCoords, SpvInstruction dRef, SpvInstruction lod)
+ {
+ SpvInstruction f32 = context.TypeFP32(), s32 = context.TypeS32(), b = context.TypeBool();
+ SpvInstruction v2 = context.TypeVector(f32, 2), v3 = context.TypeVector(f32, 3), v4 = context.TypeVector(f32, 4);
+ SpvInstruction iv2 = context.TypeVector(s32, 2), iv3 = context.TypeVector(s32, 3);
+ SpvInstruction zero = context.Constant(f32, 0f), one = context.Constant(f32, 1f);
+
+ SpvInstruction prmPtr = context.AccessChain(context.TypePointer(StorageClass.Uniform, v4), context.ConstantBuffers[SupportBuffer.Binding],
+ context.Constant(s32, (int)SupportBufferField.Pcss));
+ SpvInstruction prm = context.Load(v4, prmPtr);
+ SpvInstruction lightSize = context.CompositeExtract(f32, prm, 0);
+ SpvInstruction minR = context.CompositeExtract(f32, prm, 1);
+ SpvInstruction maxR = context.CompositeExtract(f32, prm, 2);
+ SpvInstruction searchR = context.CompositeExtract(f32, prm, 3);
+
+ SpvInstruction pcssLabel = context.Label(), plainLabel = context.Label(), mergeLabel = context.Label();
+ SpvInstruction enabled = context.FOrdGreaterThan(b, lightSize, zero); // before the merge: it must precede the branch
+ context.SelectionMerge(mergeLabel, SelectionControlMask.MaskNone);
+ context.BranchConditional(enabled, pcssLabel, plainLabel);
+
+ context.AddLabel(plainLabel);
+ SpvInstruction plain = context.ImageSampleDrefExplicitLod(f32, image, pCoords, dRef, ImageOperandsMask.Lod, lod);
+ context.Branch(mergeLabel);
+
+ context.AddLabel(pcssLabel);
+ SpvInstruction raw = context.Image(declaration.ImageType, image);
+ SpvInstruction size3 = context.ImageQuerySizeLod(iv3, raw, context.Constant(s32, 0));
+ SpvInstruction sizeI = context.VectorShuffle(iv2, size3, size3, 0, 1);
+ SpvInstruction sizeF = context.ConvertSToF(v2, sizeI);
+ SpvInstruction maxI = context.ISub(iv2, sizeI, context.ConstantComposite(iv2, context.Constant(s32, 1), context.Constant(s32, 1)));
+ SpvInstruction zeroI = context.ConstantComposite(iv2, context.Constant(s32, 0), context.Constant(s32, 0));
+ SpvInstruction uv = context.VectorShuffle(v2, pCoords, pCoords, 0, 1);
+ SpvInstruction layerF = context.CompositeExtract(f32, pCoords, 2);
+ SpvInstruction layerI = context.ConvertFToS(s32, layerF);
+ SpvInstruction searchV = context.CompositeConstruct(v2, searchR, searchR);
+
+ SpvInstruction sum = zero, count = zero;
+ for (int i = 0; i < PcssSearch.Length; i += 2)
+ {
+ SpvInstruction off = context.ConstantComposite(v2, context.Constant(f32, PcssSearch[i]), context.Constant(f32, PcssSearch[i + 1]));
+ SpvInstruction p = context.FAdd(v2, uv, context.FMul(v2, off, searchV));
+ SpvInstruction t = context.GlslSClamp(iv2, context.ConvertFToS(iv2, context.FMul(v2, p, sizeF)), zeroI, maxI);
+ SpvInstruction c = context.CompositeConstruct(iv3, context.CompositeExtract(s32, t, 0), context.CompositeExtract(s32, t, 1), layerI);
+ SpvInstruction d = context.CompositeExtract(f32, context.ImageFetch(v4, raw, c, ImageOperandsMask.Lod, context.Constant(s32, 0)), 0);
+ SpvInstruction blocker = context.FOrdLessThan(b, d, dRef);
+ sum = context.FAdd(f32, sum, context.Select(f32, blocker, d, zero));
+ count = context.FAdd(f32, count, context.Select(f32, blocker, one, zero));
+ }
+
+ SpvInstruction avg = context.FDiv(f32, sum, context.GlslFMax(f32, count, one));
+ SpvInstruction penumbra = context.Select(f32, context.FOrdGreaterThan(b, count, zero),
+ context.FMul(f32, context.FSub(f32, dRef, avg), lightSize), zero);
+ SpvInstruction radius = context.GlslFClamp(f32, penumbra, minR, maxR);
+ SpvInstruction radiusV = context.CompositeConstruct(v2, radius, radius);
+
+ SpvInstruction acc = zero;
+ for (int i = 0; i < PcssDisk.Length; i += 2)
+ {
+ SpvInstruction off = context.ConstantComposite(v2, context.Constant(f32, PcssDisk[i]), context.Constant(f32, PcssDisk[i + 1]));
+ SpvInstruction p = context.FAdd(v2, uv, context.FMul(v2, off, radiusV));
+ SpvInstruction c = context.CompositeConstruct(v3, context.CompositeExtract(f32, p, 0), context.CompositeExtract(f32, p, 1), layerF);
+ acc = context.FAdd(f32, acc, context.ImageSampleDrefExplicitLod(f32, image, c, dRef, ImageOperandsMask.Lod, lod));
+ }
+
+ SpvInstruction pcss = context.FMul(f32, acc, context.Constant(f32, 2f / PcssDisk.Length));
+ context.Branch(mergeLabel);
+
+ context.AddLabel(mergeLabel);
+ return context.Phi(f32, pcss, pcssLabel, plain, plainLabel);
+ }
+
private static OperationResult GenerateTextureQuerySamples(CodeGenContext context, AstOperation operation)
{
AstTextureOperation texOp = (AstTextureOperation)operation;
--- a/src/Ryujinx.Graphics.Shader/SupportBuffer.cs
+++ b/src/Ryujinx.Graphics.Shader/SupportBuffer.cs
@@ -25,6 +25,7 @@ namespace Ryujinx.Graphics.Shader
TfeOffset,
TfeVertexCount,
PointSize,
+ Pcss,
}
public struct SupportBuffer
@@ -82,7 +83,8 @@ namespace Ryujinx.Graphics.Shader
new StructureField(AggregateType.Array | AggregateType.FP32, "render_scale", RenderScaleMaxCount),
new StructureField(AggregateType.Vector4 | AggregateType.S32, "tfe_offset"),
new StructureField(AggregateType.S32, "tfe_vertex_count"),
- new StructureField(AggregateType.FP32, "point_size")
+ new StructureField(AggregateType.FP32, "point_size"),
+ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss")
]);
}
@@ -98,5 +100,6 @@ namespace Ryujinx.Graphics.Shader
public Vector4<int> TfeOffset;
public Vector4<int> TfeVertexCount;
public Vector4<float> PointSize;
+ public Vector4<float> Pcss;
}
}
+4
View File
@@ -129,6 +129,10 @@
# short way toward the sun through the depth buffer and darkens where something close blocks it, adding the small
# shadows at feet, under stones and in grass that the shadow maps miss. Read at start.
# contact_shadows = 0
# Soft sun shadows (PCSS), percent of the default penumbra width (0 to 200; 0 = the game's own four-tap filter): sharp
# where an object meets the ground and softer the further its shadow falls. Done in the translated shaders (translator
# patch 0010), so the shader cache is rebuilt once after an update. Read at start.
# pcss = 0
[language]
# Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale.