Import the base tree (MIT, see LICENSE)

This commit is contained in:
Valiantsin Dzerakh
2026-11-04 22:16:41 +03:00
committed by chrg6
commit 0478c13e45
734 changed files with 233953 additions and 0 deletions

21
tools/xlate/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 jhaizhou
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

195
tools/xlate/Program.cs Normal file
View File

@@ -0,0 +1,195 @@
// NX2NAVI Vulkan adaptation of MacNativeGames games/<game>/tools/nx2navi_xlate/Program.cs (MIT, see LICENSE; MNG commit b75be8cf).
// Provenance: that file is based on D2R Mobile dm/gfx/tools/dmsh_xlate/Program.cs. Changes here: SPIR-V for Vulkan is the final
// output (no MSL service, no VertexCounterLowering, no NEAR_IS_MINUS_W rewrite), depth clip control reported as supported,
// non-constant texture offsets reported as unsupported, --disasm dropped.
// Protocol (stdout carries replies only; diagnostics go to stderr):
// nx2navi_xlate --serve one request per stdin line: {"job": {...}, "out": "<dir>"}; one reply line per request:
// "ok <key>" or "fail <key> <message>"; a malformed line gets "fail ? <message>" and the loop continues.
// nx2navi_xlate <jobs.json> <outdir> batch mode: a JSON array of jobs, prints a summary, exit 1 if any failed.
// job: { "key", "stage": "vs|ps|cs", "code": path (graphics = 0x50-byte SPH + instructions, compute = instructions), "c1": hex,
// "tex": {slot: type}, "img": {slot: {type, fmt}}, "attr": {loc: float|sint|uint}, "fout": {idx: float|sint|uint},
// "local": [x, y, z], "shared": bytes, "debug": bool, "reduced": bool, "softfloat64": bool, "zero_locals": bool,
// "sbuf_align": int, "subgroup": int }
// Output: <out>/<key>.spv and <out>/<key>.res.json (bindings, queried slots, notes).
using Ryujinx.Common.Memory;
using Ryujinx.Graphics.Shader;
using Ryujinx.Graphics.Shader.Translation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Nodes;
static class SwshXlate
{
const int TexBase = 0x168, SampBase = 0x568; // NVN 分离贴图 / 采样器句柄在 c[2] 的字节基址(每槽 8 字节;dm/gfx/tools/maxwell_refs.py 全量实测) | byte base of NVN separate texture / sampler handles in c[2] (8 bytes per slot; full measurement in dm/gfx/tools/maxwell_refs.py)
sealed class Accessor : IGpuAccessor
{
readonly byte[] _code; readonly JsonObject _job; int _binding = 1; public readonly List<string> Notes = new(); public readonly SortedSet<int> TexQueried = new(), ImgQueried = new();
readonly byte[] _c1;
public Accessor(byte[] code, JsonObject job) { _code = code; _job = job; _c1 = job["c1"] is JsonNode h ? Convert.FromHexString((string)h) : Array.Empty<byte>(); }
// c1 常数段(着色器包控制段前 0x100 字节):间接跳转 BRX 的跳转表在这里(LDC c[1]);不提供时翻译器解不出跳转目标、控制流出错(粒子着色器死循环)
// c1 constant segment (the 0x100 bytes before the control segment in the shader package): the jump table of indirect jump BRX lives here (LDC c[1]); without it the translator cannot resolve jump targets and control flow goes wrong (particle shaders loop forever)
public uint ConstantBuffer1Read(int offset) { if (offset >= 0 && offset + 4 <= _c1.Length) return BitConverter.ToUInt32(_c1, offset); Notes.Add($"c1 读越界 +{offset:X}(c1 长 {_c1.Length})"); return 0; }
// 全部资源放进第 0 组,各占不同绑定号(spirv-cross 出成一个参数缓冲);常量段号 index 的缓冲由翻译器给 binding = index+1 的惯例不依赖
// All resources go into set 0, each with a distinct binding number (spirv-cross emits them as one argument buffer); the translator's convention of giving the buffer of constant segment number index binding = index+1 is not relied on
public SetBindingPair CreateConstantBufferBinding(int index) => new(0, _binding++);
public SetBindingPair CreateImageBinding(int count, bool isBuffer) { int b = _binding; _binding += count; return new(0, b); }
public SetBindingPair CreateStorageBufferBinding(int index) => new(0, _binding++);
public SetBindingPair CreateTextureBinding(int count, bool isBuffer) { int b = _binding; _binding += count; return new(0, b); }
public ReadOnlySpan<ulong> GetCode(ulong address, int minimumSize) => MemoryMarshal.Cast<byte, ulong>(new ReadOnlySpan<byte>(_code)[(int)address..]);
public int QuerySamplerArrayLengthFromPool() => 32;
public int QueryTextureArrayLengthFromBuffer(int slot) => 32;
public int QueryTextureArrayLengthFromPool() => 32;
string Get(string table, int slot) => _job[table] is JsonObject t && t[slot.ToString()] is JsonNode n ? (n is JsonObject o ? (string)o["type"] : (string)n) : null;
int TexSlot(int handle, int cbufSlot)
{
(int off0, _, _) = TextureHandle.UnpackOffsets(handle);
int bytes = off0 * 4;
return (cbufSlot < 0 || (cbufSlot & 0xffff) == 2) && bytes >= TexBase && bytes < SampBase && (bytes - TexBase) % 8 == 0 ? (bytes - TexBase) / 8 : -1;
}
public SamplerType QuerySamplerType(int handle, int cbufSlot = -1)
{
int slot = TexSlot(handle, cbufSlot);
if (slot >= 0) TexQueried.Add(slot);
string t = slot >= 0 ? Get("tex", slot) ?? Get("img", slot) : null;
if (t == null) { Notes.Add($"贴图句柄 {handle:X}(常量段 {cbufSlot},槽 {slot})无 PC 类型,按 2D"); return SamplerType.Texture2D; }
if (t.EndsWith("_depth")) t = t.Substring(0, t.Length - 6); // depth-format texture: same sampler type here; the host binds a depth view
return t switch
{
"1d" => SamplerType.Texture1D, "1darray" => SamplerType.Texture1D | SamplerType.Array,
"buffer" => SamplerType.TextureBuffer, "2d" => SamplerType.Texture2D, "2darray" => SamplerType.Texture2D | SamplerType.Array,
"2dms" => SamplerType.Texture2D | SamplerType.Multisample, "2dmsarray" => SamplerType.Texture2D | SamplerType.Multisample | SamplerType.Array,
"3d" => SamplerType.Texture3D, "cube" => SamplerType.TextureCube, "cubearray" => SamplerType.TextureCube | SamplerType.Array,
_ => SamplerType.Texture2D,
};
}
public TextureFormat QueryTextureFormat(int handle, int cbufSlot = -1)
{
int slot = TexSlot(handle, cbufSlot);
if (slot >= 0) ImgQueried.Add(slot);
string f = _job["img"] is JsonObject t && slot >= 0 && t[slot.ToString()] is JsonObject o ? (string)o["fmt"] : null;
if (f == null) { Notes.Add($"图像句柄 {handle:X} 槽 {slot} 无 PC 格式,按 R8G8B8A8Unorm"); return TextureFormat.R8G8B8A8Unorm; }
return Enum.TryParse(f, true, out TextureFormat tf) ? tf : TextureFormat.R8G8B8A8Unorm;
}
int Local(int i) => _job["local"] is JsonArray a && a.Count > i ? (int)a[i] : 1;
public int QueryComputeLocalSizeX() => Local(0);
public int QueryComputeLocalSizeY() => Local(1);
public int QueryComputeLocalSizeZ() => Local(2);
public int QueryComputeSharedMemorySize() => _job["shared"] is JsonNode n ? (int)n : 0; // 配对 PC 的 groupshared 声明之和 | sum of the paired PC shader's groupshared declarations
static AttributeType Attr(string s) => s switch { "sint" => AttributeType.Sint, "uint" => AttributeType.Uint, _ => AttributeType.Float };
public GpuGraphicsState QueryGraphicsState()
{
Array32<AttributeType> attr = default; Array8<AttributeType> fout = default;
if (_job["attr"] is JsonObject a) foreach (var kv in a) attr[int.Parse(kv.Key)] = Attr((string)kv.Value);
if (_job["fout"] is JsonObject f) foreach (var kv in f) fout[int.Parse(kv.Key)] = Attr((string)kv.Value);
// Vulkan: VK_EXT_depth_clip_control handles NEAR_IS_MINUS_W, so the shader is never rewritten ("depth_minus_w" in a job is ignored).
const bool depthMinusW = false;
// "early_fragment_tests": the fragment shader's NVN control byte +0x718 (the driver's early-Z-force, Ryujinx's
// EarlyZForce); the SPIR-V then declares EarlyFragmentTests (MacNativeGames ae8f4f4).
bool earlyZ = _job["early_fragment_tests"] is JsonValue ez && ez.TryGetValue<bool>(out bool eb) && eb;
return new GpuGraphicsState(earlyZ, InputTopology.Triangles, false, TessPatchType.Triangles, TessSpacing.EqualSpacing,
false, false, false, depthMinusW, false, 1f, AlphaTestOp.Always, 0f, attr, false, fout, false,
false /* 不做 Y 取反 | no Y flip */, true /* 原点左上 | origin upper-left */, false);
}
public bool QueryHostSupportsDepthClipControl() => true;
// Vulkan: the ConstOffset / ConstOffsets image operands Ryujinx emits must be constants. A TLD4.PTP whose offsets
// come from registers (agl_technique_pfx compute b940aa86, dfe7662f) otherwise becomes an OpConstantComposite over
// computed ids, which spirv-val rejects; false makes TexturePass emulate only non-constant offsets.
public bool QueryHostSupportsNonConstantTextureOffset() => false;
// "softfloat64": true lowers FP64 operations to FP32 (Ryujinx's DoubleToFloat pass), for a host without shaderFloat64.
public bool QueryHostSupportsShaderFloat64() => _job["softfloat64"] is not JsonValue v || !(v.TryGetValue<bool>(out bool b) && b);
public bool QueryHostSupportsTextureShadowLod() => true;
// Sub-texel precision bits of a host whose gathers round differently from Maxwell (AMD, Intel): Ryujinx then
// biases gather coordinates so the same texels are picked (TexturePass.InsertCoordGatherBias). 0: no bias.
public int QueryHostGatherBiasPrecision() => _job["gather_bias"] is JsonNode n ? (int)n : 0;
// 作业 reduced = true:放宽精度——翻译器只给强制精确的运算打 NoContraction(缺省全部打:保持 Maxwell 分开舍入的逐位结果,代价是 MSL 里大量禁优化的 spvFMul 等)
// Job reduced = true: relaxed precision - the translator marks NoContraction only on operations that must be exact (the default marks all: keeps the bit-exact results of Maxwell's separate rounding, at the cost of many optimization-disabled spvFMul etc. in the MSL)
public bool QueryHostReducedPrecision() => _job["reduced"] is JsonNode n && (bool)n;
// Host answers for GPUs other than the RX 9070 (runtime/vk_caps.c); absent from the job they keep Ryujinx's defaults.
// "sbuf_align": n: the host binds each storage buffer at its guest address rounded down to n (minStorageBufferOffsetAlignment
// above 4), so storage offsets count from there (Ryujinx's unaligned path; the multi-target path uses n too).
public bool QueryHasUnalignedStorageBuffer() => _job["sbuf_align"] is JsonNode;
public int QueryHostStorageBufferOffsetAlignment() => _job["sbuf_align"] is JsonNode n ? (int)n : 16;
// "subgroup": n: lanes per subgroup when the host cannot pin 32 (AMD GCN/Vega run 64): ballots and votes span n lanes.
public int QueryHostSubgroupSize() => _job["subgroup"] is JsonNode n ? (int)n : 32;
// "mvprev": true: the vertex shader also writes last frame's position, computed from slots bank + 15 in place of
// the user banks c3-c16 (patch 0015, runtime/vk_mvprev.c); res.json's "mvprev" names the output location (-1:
// none) and "mvprev_banks" the banks the position depends on (bit n: cn).
public bool QueryMotionPrevious() => _job["mvprev"] is JsonValue v && v.TryGetValue<bool>(out bool b) && b;
// "zero_locals": true: function-local variables start at 0 (patch 0016, runtime/vk_caps.c decides per driver).
public bool QueryZeroLocals() => _job["zero_locals"] is JsonValue v && v.TryGetValue<bool>(out bool b) && b;
public int MotionPreviousLocation = -1, MotionPreviousBanks;
public void ReportMotionPrevious(int location, int banks) => (MotionPreviousLocation, MotionPreviousBanks) = (location, banks);
}
internal static string Translate(JsonObject job, string outDir) // also called by the --service mode (Service.cs)
{
string key = (string)job["key"];
try
{
byte[] code = File.ReadAllBytes((string)job["code"]);
var acc = new Accessor(code, job);
// 作业 debug = false:关 DebugMode(DebugMode 会跳过 AST 优化器,产物满是临时变量;不改语义)
// Job debug = false: turn off DebugMode (DebugMode skips the AST optimizer and the output is full of temporaries; semantics unchanged)
var flags = (job["debug"] is JsonNode dbg && !(bool)dbg ? 0 : TranslationFlags.DebugMode) | ((string)job["stage"] == "cs" ? TranslationFlags.Compute : 0);
var ctx = Translator.CreateContext(0, acc, new TranslationOptions(TargetLanguage.Spirv, TargetApi.Vulkan, flags));
ShaderProgram p = ctx.Translate();
File.WriteAllBytes(Path.Combine(outDir, key + ".spv"), p.BinaryCode);
var res = new JsonObject
{
["key"] = key, ["stage"] = (string)job["stage"], ["notes"] = new JsonArray(acc.Notes.ConvertAll(n => (JsonNode)n).ToArray()),
["cbufs"] = new JsonArray(), ["sbufs"] = new JsonArray(), ["textures"] = new JsonArray(), ["images"] = new JsonArray(),
["uses_frag_coord"] = p.Info.UsesFragCoord, ["frag_out_map"] = p.Info.FragmentOutputMap,
["tex_queried"] = new JsonArray(acc.TexQueried.Select(x => (JsonNode)x).ToArray()), ["img_queried"] = new JsonArray(acc.ImgQueried.Select(x => (JsonNode)x).ToArray()),
};
if (acc.QueryMotionPrevious()) (res["mvprev"], res["mvprev_banks"]) = (acc.MotionPreviousLocation, acc.MotionPreviousBanks);
foreach (var b in p.Info.CBuffers) res["cbufs"].AsArray().Add((JsonNode)new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot });
foreach (var b in p.Info.SBuffers) res["sbufs"].AsArray().Add((JsonNode)new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot, ["cb_slot"] = b.SbCbSlot, ["cb_offset"] = b.SbCbOffset, ["flags"] = (int)b.Flags });
foreach (var (list, name) in new[] { (p.Info.Textures, "textures"), (p.Info.Images, "images") })
foreach (var t in list) res[name].AsArray().Add((JsonNode)new JsonObject { ["binding"] = t.Binding, ["type"] = (int)t.Type, ["format"] = t.Format.ToString(), ["cbuf_slot"] = t.CbufSlot, ["handle"] = t.HandleIndex, ["array"] = t.ArrayLength, ["separate"] = t.Separate, ["flags"] = (int)t.Flags });
File.WriteAllText(Path.Combine(outDir, key + ".res.json"), res.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
return null;
}
catch (Exception e) { if (Environment.GetEnvironmentVariable("DMSH_STACK") != null) Console.Error.WriteLine(e.StackTrace); return $"{e.GetType().Name}: {e.Message.Split('\n')[0]}"; }
}
static int Main(string[] args)
{
if (args.Length == 1 && args[0] == "--serve")
{
// One request per line: {"job": {...}, "out": "<dir>"}; one reply line "ok <key>" / "fail <key> <message>".
string line;
while ((line = Console.ReadLine()) != null)
{
if (line.Length == 0) continue;
string key = "?", err;
try
{
var req = JsonNode.Parse(line).AsObject(); var job = req["job"].AsObject(); string o = (string)req["out"];
key = (string)job["key"];
Directory.CreateDirectory(o);
err = Translate(job, o);
}
catch (Exception e) { err = $"{e.GetType().Name}: {e.Message.Split((char)10)[0]}"; }
Console.WriteLine(err == null ? $"ok {key}" : $"fail {key} {err}");
Console.Out.Flush();
}
return 0;
}
var jobs = JsonNode.Parse(File.ReadAllText(args[0])).AsArray(); string outDir = args[1]; Directory.CreateDirectory(outDir);
int ok = 0, bad = 0;
foreach (JsonObject job in jobs)
{
string err = Translate(job, outDir);
if (err == null) ok++; else { bad++; Console.Error.WriteLine($"【红】{(string)job["key"]}:{err}"); }
}
Console.WriteLine($"翻译 {ok} 成功,{bad} 失败");
return bad == 0 ? 0 : 1;
}
}

View File

@@ -0,0 +1,16 @@
<!-- NX2NAVI runtime shader translator: Switch Maxwell code -> SPIR-V (Vulkan) via the Ryujinx 1.3.2 shader translator.
Adapted from MacNativeGames games/<game>/tools/nx2navi_xlate/nx2navi_xlate.csproj (MIT). -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>disable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- tools/build_xlate.py passes the patched copy under build/xlate/ryujinx. -->
<RyuSrc Condition="'$(RyuSrc)' == ''">$(MSBuildThisFileDirectory)../vendor/ryujinx</RyuSrc>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(RyuSrc)/src/Ryujinx.Graphics.Shader/Ryujinx.Graphics.Shader.csproj" />
<ProjectReference Include="$(RyuSrc)/src/Ryujinx.Common/Ryujinx.Common.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,15 @@
--- a/src/Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
+++ b/src/Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
@@ -24,7 +24,11 @@
{
bool isWorthPropagating = propVar.Uses.Count == 1 || IsWorthPropagating(assignment.Source);
- if (propVar.Defs.Count == 1 && isWorthPropagating)
+ // NX2NAVI: SPIR-V passes call arguments by pointer to a variable (StructuredProgram copies them
+ // into temporaries); folding an expression into a call argument breaks GenerateCall.
+ bool usedByCall = propVar.Uses.Any(u => u is AstOperation op && op.Inst == Instruction.Call);
+
+ if (propVar.Defs.Count == 1 && isWorthPropagating && !usedByCall)
{
PropagateExpression(propVar, assignment.Source);
}

View File

@@ -0,0 +1,20 @@
--- a/src/Ryujinx.Graphics.Shader/Translation/Optimizations/Optimizer.cs
+++ b/src/Ryujinx.Graphics.Shader/Translation/Optimizations/Optimizer.cs
@@ -384,7 +384,16 @@
if (src.UseOps.Remove(node) && src.UseOps.Count == 0)
{
Debug.Assert(src.AsgOp != null);
- nodes.Enqueue(src.AsgOp);
+
+ // NX2NAVI (2026-10-16, from Ryujinx_Optime 01a1e37f): only follow into a producer that will itself be
+ // removed. An operation with side effects (a call, an atomic) stays in the block even when its
+ // result is unused, so its sources are still live: stripping their use lists here made the next
+ // DCE pass delete the whole chain feeding a global-memory atomic turned into a helper call, which
+ // then read an uninitialised value (NX2NAVI's sun-visibility kernel; our c7830fac lost its atomicMin).
+ if (!HasSideEffects(src.AsgOp))
+ {
+ nodes.Enqueue(src.AsgOp);
+ }
}
}
}

View File

@@ -0,0 +1,57 @@
--- a/src/Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
+++ b/src/Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
@@ -22,7 +22,12 @@
{
if (node is AstAssignment assignment && assignment.Destination is AstOperand propVar)
{
- bool isWorthPropagating = propVar.Uses.Count == 1 || IsWorthPropagating(assignment.Source);
+ // NX2NAVI (2026-10-16): an atomic / call / image atomic whose result is unused (Maxwell RED, ATOM with
+ // an RZ destination) stays a statement in place: propagating it would move the side effect to its
+ // use, and removing the assignment removed the operation itself (the reduction kernel c7830fac
+ // lost its atomicMin on 2026-10-13; every translation ran in DebugMode since, to avoid this).
+ bool sideEffects = HasSideEffects(assignment.Source);
+ bool isWorthPropagating = !sideEffects && (propVar.Uses.Count == 1 || IsWorthPropagating(assignment.Source));
// NX2NAVI: SPIR-V passes call arguments by pointer to a variable (StructuredProgram copies them
// into temporaries); folding an expression into a call argument breaks GenerateCall.
@@ -33,7 +38,7 @@
PropagateExpression(propVar, assignment.Source);
}
- if (propVar.Type == OperandType.LocalVariable && propVar.Uses.Count == 0)
+ if (propVar.Type == OperandType.LocalVariable && propVar.Uses.Count == 0 && !sideEffects)
{
visitor.Block.Remove(assignment);
@@ -46,6 +51,31 @@
RemoveEmptyBlocks(mainBlock);
}
+ private static bool HasSideEffects(IAstNode source)
+ {
+ if (source is AstOperation op)
+ {
+ switch (op.Inst & Instruction.Mask)
+ {
+ case Instruction.AtomicAdd:
+ case Instruction.AtomicAnd:
+ case Instruction.AtomicCompareAndSwap:
+ case Instruction.AtomicMaxS32:
+ case Instruction.AtomicMaxU32:
+ case Instruction.AtomicMinS32:
+ case Instruction.AtomicMinU32:
+ case Instruction.AtomicOr:
+ case Instruction.AtomicSwap:
+ case Instruction.AtomicXor:
+ case Instruction.Call:
+ case Instruction.ImageAtomic:
+ return true;
+ }
+ }
+
+ return false;
+ }
+
private static bool IsWorthPropagating(IAstNode source)
{
if (source is not AstOperation srcOp)

View File

@@ -0,0 +1,26 @@
--- a/src/Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
+++ b/src/Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
@@ -118,6 +118,8 @@
}
}
+ private const bool ElseIfFlattening = false;
+
private static void RemoveEmptyBlocks(AstBlock mainBlock)
{
Queue<AstBlock> pending = new();
@@ -163,7 +165,13 @@
parent.Remove(block);
}
}
- else if (isIf && parent.Type == AstBlockType.Else && parent.Count == (hasElse ? 2 : 1))
+ // NX2NAVI (2026-10-16): the else-if flattening (`else { if (c) A else B }` -> `else if (c) A else B`) is
+ // disabled. The SPIR-V backend gives the else-if the same merge block as the if before it, and
+ // SPIRV-Cross then drops the trailing else of the chain: NX2NAVI's fragment shader 1870878a lost three
+ // loops with an atomic max (a feedback write) and a discard (scripts/diag/msl_invariants.py found 12
+ // variants losing atomics and 83 changing discards). The nested form is what DebugMode always produced,
+ // because its comment nodes keep every block non-empty and this branch never ran.
+ else if (ElseIfFlattening && isIf && parent.Type == AstBlockType.Else && parent.Count == (hasElse ? 2 : 1))
{
AstBlock parentOfParent = parent.Parent;

View File

@@ -0,0 +1,36 @@
--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs
+++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs
@@ -225,6 +225,8 @@
private static void DeclareImages(CodeGenContext context, IEnumerable<TextureDefinition> images)
{
+ bool writeWithoutFormat = false;
+
foreach (TextureDefinition image in images)
{
int setIndex = context.TargetApi == TargetApi.Vulkan ? image.Set : 0;
@@ -240,6 +242,12 @@
AccessQualifier.ReadWrite,
GetImageFormat(image.Format));
+ // NX2NAVI (2026-10-20): an image declared without a format (QueryHostSupportsImageLoadFormatted) that the
+ // shader stores to needs StorageImageWriteWithoutFormat; upstream never declares it, so spirv-val rejects
+ // 22 agl_technique_pfx compute shaders with formatted SUST. Vulkan's shaderStorageImageWriteWithoutFormat
+ // feature backs it. Reads without a format need no capability under Vulkan 1.3 (format feature flags 2).
+ writeWithoutFormat |= image.Format == TextureFormat.Unknown && image.Flags.HasFlag(TextureUsageFlags.ImageStore);
+
SpvInstruction imagePointerType = context.TypePointer(StorageClass.UniformConstant, imageType);
SpvInstruction imageArrayPointerType = imagePointerType;
@@ -269,6 +277,11 @@
context.AddGlobalVariable(imageVariable);
}
+
+ if (writeWithoutFormat)
+ {
+ context.AddCapability(Capability.StorageImageWriteWithoutFormat);
+ }
}
private static Dim GetDim(SamplerType type)

View File

@@ -0,0 +1,40 @@
--- a/src/Ryujinx.Graphics.Shader/Translation/AttributeUsage.cs
+++ b/src/Ryujinx.Graphics.Shader/Translation/AttributeUsage.cs
@@ -19,6 +19,7 @@
private readonly IGpuAccessor _gpuAccessor;
public UInt128 NextInputAttributesComponents { get; private set; }
+ public bool NextStageKnown { get; private set; }
public UInt128 ThisInputAttributesComponents { get; private set; }
public AttributeUsage(IGpuAccessor gpuAccessor)
@@ -55,6 +56,7 @@
public void MergeFromtNextStage(bool gpPassthrough, bool nextUsesFixedFunctionAttributes, AttributeUsage nextStage)
{
+ NextStageKnown = true;
NextInputAttributesComponents = nextStage.ThisInputAttributesComponents;
NextUsedInputAttributesPerPatch = nextStage.UsedInputAttributesPerPatch;
NextUsesFixedFuncAttributes = nextUsesFixedFunctionAttributes;
--- a/src/Ryujinx.Graphics.Shader/Translation/Translator.cs
+++ b/src/Ryujinx.Graphics.Shader/Translation/Translator.cs
@@ -210,6 +210,19 @@
}
UInt128 usedAttributes = context.TranslatorContext.AttributeUsage.NextInputAttributesComponents;
+
+ // NX2NAVI (2026-10-22): the host translates each stage on its own (no SetNextStage), so the components the next
+ // stage reads are unknown. Maxwell reads an unwritten output component as (0, 0, 0, 1) (a VS writing xyz of a
+ // varying the FS divides by w); start every component of every written output there, as a linked pipeline would
+ // for the components the next stage reads. The host adds outputs the VS never writes (vk_pipeline.c).
+ if (!context.TranslatorContext.AttributeUsage.NextStageKnown)
+ {
+ for (int mask = context.TranslatorContext.AttributeUsage.UsedOutputAttributes; mask != 0; mask &= mask - 1)
+ {
+ usedAttributes |= (UInt128)0xf << (int.TrailingZeroCount(mask) * 4);
+ }
+ }
+
while (usedAttributes != UInt128.Zero)
{
int index = (int)UInt128.TrailingZeroCount(usedAttributes);

View File

@@ -0,0 +1,25 @@
--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs
+++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs
@@ -465,10 +465,9 @@
context.Decorate(perVertexStructType, Decoration.Block);
- if (context.HostCapabilities.ReducedPrecision)
- {
- context.MemberDecorate(perVertexStructType, 0, Decoration.Invariant);
- }
+ // NX2NAVI: Maxwell computes a position identically in every shader that runs the same code (a depth pre-pass drawn
+ // again with EQUAL), so the position is always invariant, not only with the ReducedPrecision job flag.
+ context.MemberDecorate(perVertexStructType, 0, Decoration.Invariant);
context.MemberDecorate(perVertexStructType, 0, Decoration.BuiltIn, (LiteralInteger)BuiltIn.Position);
context.MemberDecorate(perVertexStructType, 1, Decoration.BuiltIn, (LiteralInteger)BuiltIn.PointSize);
@@ -566,7 +565,7 @@
context.Decorate(spvVar, Decoration.Patch);
}
- if (context.HostCapabilities.ReducedPrecision && ioVariable == IoVariable.Position)
+ if (ioVariable == IoVariable.Position)
{
context.Decorate(spvVar, Decoration.Invariant);
}

View File

@@ -0,0 +1,40 @@
--- a/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs
+++ b/src/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs
@@ -85,7 +85,9 @@
// OpenGL requires the point size to be always written on the shader if PROGRAM_POINT_SIZE is set.
if (TranslatorContext.Definitions.Stage == ShaderStage.Vertex)
{
- this.Store(StorageKind.Output, IoVariable.PointSize, null, ConstF(TranslatorContext.Definitions.PointSize));
+ // NX2NAVI: the point size is NVN state (SetPointSize), not a translation constant: read it from the support buffer, which the
+ // host fills per draw. A shader that writes gl_PointSize itself overwrites this store.
+ this.Store(StorageKind.Output, IoVariable.PointSize, null, this.Load(StorageKind.ConstantBuffer, SupportBuffer.Binding, Const((int)SupportBufferField.PointSize)));
}
if (VertexAsCompute)
--- a/src/Ryujinx.Graphics.Shader/SupportBuffer.cs
+++ b/src/Ryujinx.Graphics.Shader/SupportBuffer.cs
@@ -24,6 +24,7 @@
RenderScale,
TfeOffset,
TfeVertexCount,
+ PointSize,
}
public struct SupportBuffer
@@ -80,7 +81,8 @@
new StructureField(AggregateType.S32, "frag_scale_count"),
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.S32, "tfe_vertex_count"),
+ new StructureField(AggregateType.FP32, "point_size")
]);
}
@@ -95,5 +97,6 @@
public Vector4<int> TfeOffset;
public Vector4<int> TfeVertexCount;
+ public Vector4<float> PointSize;
}
}

View File

@@ -0,0 +1,21 @@
--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs
+++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs
@@ -1283,6 +1283,18 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
if (isShadow)
{
dRef = Src(AggregateType.FP32);
+
+ // NX2NAVI: the shadow cascades are D16 array textures. Maxwell rounds the compare reference to the texture's
+ // 16-bit precision before the compare; Vulkan drivers may compare the full float (AMD does), so a lit
+ // surface fails its own compare by a fraction of a step and the whole face reads as shadowed. Array
+ // compares only: in NX2navi those are the D16 cascades (MacNativeGames 6283599 rounds the same ones).
+ if (isArray)
+ {
+ SpvInstruction d16Fp32 = context.TypeFP32();
+ SpvInstruction d16Clamped = context.GlslFClamp(d16Fp32, dRef, context.Constant(d16Fp32, 0f), context.Constant(d16Fp32, 1f));
+ SpvInstruction d16Scaled = context.FAdd(d16Fp32, context.FMul(d16Fp32, d16Clamped, context.Constant(d16Fp32, 65535f)), context.Constant(d16Fp32, 0.5f));
+ dRef = context.FMul(d16Fp32, context.GlslFloor(d16Fp32, d16Scaled), context.Constant(d16Fp32, 1f / 65535f));
+ }
}
SpvInstruction[] derivatives = null;

View File

@@ -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);
}
+ // NX2NAVI: 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, NX2NAVI_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;
}
}

View File

@@ -0,0 +1,82 @@
--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs
+++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs
@@ -853,7 +853,51 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
private static OperationResult GenerateLoad(CodeGenContext context, AstOperation operation)
{
- return GenerateLoadOrStore(context, operation, isStore: false);
+ OperationResult result = GenerateLoadOrStore(context, operation, isStore: false);
+ if (result.Type == AggregateType.FP32 && IsShadowSpread(context, operation))
+ {
+ SpvInstruction f32 = context.TypeFP32(), v4 = context.TypeVector(f32, 4);
+ SpvInstruction prmPtr = context.AccessChain(context.TypePointer(StorageClass.Uniform, v4), context.ConstantBuffers[SupportBuffer.Binding],
+ context.Constant(context.TypeS32(), (int)SupportBufferField.ShadowSpread));
+ SpvInstruction factor = context.CompositeExtract(f32, context.Load(v4, prmPtr), 0);
+ result = new OperationResult(AggregateType.FP32, context.FMul(f32, result.Value, factor));
+ }
+
+ return result;
+ }
+
+ // NX2NAVI: the spread of the sun shadow filter. The deferred lighting shaders take the sun shadow as four compares
+ // at the receiver ± h on the cascade map, h = 0.5 * c[56].xy (UV) of their lighting block (fp_c9, or fp_c5 in
+ // some), the same in every cascade. In the near cascade the map is sharp enough that the four copies of an edge
+ // show apart. In a fragment shader that has a 2D array shadow sampler, reads of element 56 .x and .y from any
+ // constant buffer but fp_c4 (which holds the cascade matrices, row 56 being cascade 3's depth row) are multiplied
+ // by the support buffer's shadow_spread.x (runtime/vk_exec_draw.c support_fill, NX2NAVI_SHADOW_SPREAD; 1 keeps the
+ // game's spread).
+ private static bool IsShadowSpread(CodeGenContext context, AstOperation load)
+ {
+ if (context.Definitions.Stage != ShaderStage.Fragment ||
+ load.StorageKind != StorageKind.ConstantBuffer ||
+ load.SourcesCount != 4 ||
+ load.GetSource(0) is not AstOperand { Type: OperandType.Constant } binding ||
+ load.GetSource(1) is not AstOperand { Type: OperandType.Constant, Value: 0 } ||
+ load.GetSource(2) is not AstOperand { Type: OperandType.Constant, Value: 56 } ||
+ load.GetSource(3) is not AstOperand { Type: OperandType.Constant, Value: < 2 } ||
+ !context.Properties.ConstantBuffers.TryGetValue(binding.Value, out BufferDefinition buffer) ||
+ buffer.Name == "fp_c4")
+ {
+ return false;
+ }
+
+ foreach (TextureDefinition texture in context.Properties.Textures.Values)
+ {
+ if ((texture.Type & (SamplerType.Mask | SamplerType.Array | SamplerType.Shadow)) ==
+ (SamplerType.Texture2D | SamplerType.Array | SamplerType.Shadow))
+ {
+ return true;
+ }
+ }
+
+ return false;
}
private static OperationResult GenerateLod(CodeGenContext context, AstOperation operation)
--- a/src/Ryujinx.Graphics.Shader/SupportBuffer.cs
+++ b/src/Ryujinx.Graphics.Shader/SupportBuffer.cs
@@ -26,6 +26,7 @@ namespace Ryujinx.Graphics.Shader
TfeVertexCount,
PointSize,
Pcss,
+ ShadowSpread,
}
public struct SupportBuffer
@@ -84,7 +85,8 @@ namespace Ryujinx.Graphics.Shader
new StructureField(AggregateType.Vector4 | AggregateType.S32, "tfe_offset"),
new StructureField(AggregateType.S32, "tfe_vertex_count"),
new StructureField(AggregateType.FP32, "point_size"),
- new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss")
+ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss"),
+ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "shadow_spread")
]);
}
@@ -101,5 +103,6 @@ namespace Ryujinx.Graphics.Shader
public Vector4<int> TfeVertexCount;
public Vector4<float> PointSize;
public Vector4<float> Pcss;
+ public Vector4<float> ShadowSpread;
}
}

View File

@@ -0,0 +1,64 @@
--- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs
+++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitBitfield.cs
@@ -142,13 +142,46 @@ namespace Ryujinx.Graphics.Shader.Instructions
Operand size = context.BitfieldExtractU32(srcB, Const(8), Const(8));
+ // NX2NAVI: Maxwell's BFE (as PTX bfe) cuts a field that runs past bit 31 there, and a field that starts past it
+ // gives 0, or bit 31 repeated when signed and the size is not 0. SPIR-V leaves an offset or offset + count over
+ // 32 undefined, and AMD's bitfield instructions take offset and width modulo 32. NX2NAVI's Depths terrain vertex
+ // shaders take position and size from a register (BFE.R), so they are clamped into the defined range here;
+ // constant fields inside the word are emitted as before.
+ bool constantInRange = srcB.Type == OperandType.Constant && (srcB.Value & 0xff) + ((srcB.Value >> 8) & 0xff) <= 32;
+ Operand positionIn = position;
+ Operand sizeIn = size;
+
+ if (!constantInRange)
+ {
+ ClampBitfield(context, ref position, ref size);
+ }
+
Operand res = isSigned
? context.BitfieldExtractS32(srcA, position, size)
: context.BitfieldExtractU32(srcA, position, size);
+ if (!constantInRange && isSigned)
+ {
+ // The clamped extract gave 0 for a field that starts past bit 31; a signed one is bit 31 repeated.
+ Operand signBits = context.ConditionalSelect(context.ICompareEqual(sizeIn, Const(0)), Const(0), context.ShiftRightS32(srcA, Const(31)));
+
+ res = context.ConditionalSelect(context.ICompareGreaterOrEqualUnsigned(positionIn, Const(32)), signBits, res);
+ }
+
context.Copy(GetDest(rd), res);
- // TODO: CC, X, corner cases.
+ // TODO: CC, X.
+ }
+
+ // NX2NAVI: position and size of a bitfield cut to the 32-bit word: the size shrinks to what is left of the word
+ // after the position (0 for a position of 32 or more) and the position stays at most 31, so offset and
+ // offset + count stay inside the range SPIR-V defines.
+ private static void ClampBitfield(EmitterContext context, ref Operand position, ref Operand size)
+ {
+ Operand left = context.ISubtract(Const(32), context.IMinimumU32(position, Const(32)));
+
+ size = context.IMinimumU32(size, left);
+ position = context.IMinimumU32(position, Const(31));
}
private static void EmitBfi(EmitterContext context, Operand srcA, Operand srcB, Operand srcC, int rd)
@@ -157,6 +190,13 @@ namespace Ryujinx.Graphics.Shader.Instructions
Operand size = context.BitfieldExtractU32(srcB, Const(8), Const(8));
+ // NX2NAVI: as in EmitBfe, a field past bit 31 is cut there; one that starts past it inserts nothing (size 0
+ // after the clamp), so C comes back unchanged, as on Maxwell.
+ if (!(srcB.Type == OperandType.Constant && (srcB.Value & 0xff) + ((srcB.Value >> 8) & 0xff) <= 32))
+ {
+ ClampBitfield(context, ref position, ref size);
+ }
+
Operand res = context.BitfieldInsert(srcC, srcA, position, size);
context.Copy(GetDest(rd), res);

View File

@@ -0,0 +1,32 @@
--- a/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs
+++ b/src/Ryujinx.Graphics.Shader/Instructions/InstEmitShift.cs
@@ -119,6 +119,10 @@ namespace Ryujinx.Graphics.Shader.Instructions
bool signedShift = maxShift == MaxShift.S64;
int maxShiftConst = isLongShift ? 64 : 32;
+ // NX2NAVI: the shift amount as a constant, when it is one (taken before the mask makes it an operation).
+ bool constantShift = srcB.Type == OperandType.Constant;
+ int shiftValue = constantShift ? (mask ? srcB.Value & (maxShiftConst - 1) : srcB.Value) : 0;
+
if (mask)
{
srcB = context.BitwiseAnd(srcB, Const(maxShiftConst - 1));
@@ -159,6 +163,18 @@ namespace Ryujinx.Graphics.Shader.Instructions
}
}
+ // NX2NAVI: a shift by 0 shifts the other word by 32, which SPIR-V leaves undefined; AMD's shift instructions take
+ // the amount's low 5 bits and give A | C. Maxwell gives the unshifted word: C for SHF.L, A for SHF.R, 32- and
+ // 64-bit alike. NX2NAVI's Depths terrain vertex shaders shift by registers (SHF.L.R, SHF.R.R).
+ if (!constantShift)
+ {
+ res = context.ConditionalSelect(context.ICompareEqual(srcB, Const(0)), left ? srcC : srcA, res);
+ }
+ else if (shiftValue == 0)
+ {
+ res = left ? srcC : srcA;
+ }
+
if (!mask)
{
// Clamped shift value.

View File

@@ -0,0 +1,376 @@
--- a/src/Ryujinx.Graphics.Shader/IGpuAccessor.cs
+++ b/src/Ryujinx.Graphics.Shader/IGpuAccessor.cs
@@ -184,6 +184,14 @@ namespace Ryujinx.Graphics.Shader
return false;
}
+ // NX2NAVI: true when a vertex shader should also write last frame's position (Transforms/MotionPrevious.cs),
+ // the user output location it went to (-1: none) and the banks the position depends on (bit n: cn).
+ bool QueryMotionPrevious() => false;
+
+ void ReportMotionPrevious(int location, int banks)
+ {
+ }
+
/// <summary>
/// Queries host about the presence of the FrontFacing built-in variable bug.
/// </summary>
--- a/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs
+++ b/src/Ryujinx.Graphics.Shader/Translation/ResourceManager.cs
@@ -65,7 +65,7 @@ namespace Ryujinx.Graphics.Shader.Translation
_stage = stage;
_stagePrefix = GetShaderStagePrefix(stage);
- _cbSlotToBindingMap = new SetBindingPair[18];
+ _cbSlotToBindingMap = new SetBindingPair[32]; // NX2NAVI: slots 18-31 for Transforms/MotionPrevious.cs
_sbSlotToBindingMap = new SetBindingPair[16];
_cbSlotToBindingMap.AsSpan().Fill(new(-1, -1));
_sbSlotToBindingMap.AsSpan().Fill(new(-1, -1));
--- /dev/null
+++ b/src/Ryujinx.Graphics.Shader/Translation/Transforms/MotionPrevious.cs
@@ -0,0 +1,330 @@
+using Ryujinx.Graphics.Shader.IntermediateRepresentation;
+using System.Collections.Generic;
+using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
+
+namespace Ryujinx.Graphics.Shader.Translation.Transforms
+{
+ // NX2NAVI: last frame's position for per-object motion vectors (runtime/vk_exec_draw.c, vk_mvprev.c). A vertex shader's
+ // position depends on uniform banks of this frame: the camera (c4), the object's place (c7), its bones (c5), the
+ // clock that moves wind and water (c14), and so on. Every operation the position depends on that reads one of the
+ // user banks c3..c16, directly or through other values, is computed a second time beside the original, reading slot
+ // bank + 15 (18..31) instead, where the runtime binds that bank's block of last frame; the position this gives is
+ // written to a free user output. Control flow stays the original's. Operations that cannot be repeated (stores,
+ // texture operations) keep their original result. The runtime gets the output location and the banks the position
+ // depends on (ReportMotionPrevious): an object with none of them changed since last frame held still.
+ static class MotionPrevious
+ {
+ public const int SlotOffset = 15;
+
+ private static int Remap(int slot) => slot >= 3 && slot <= 16 ? slot + SlotOffset : -1;
+
+ // The output location written (-1: none free, or no position store), and in banks the mask of the banks (bit
+ // n: cn) the position depends on.
+ public static int Run(BasicBlock[] blocks, ResourceManager resourceManager, AttributeUsage attributeUsage, out int banks)
+ {
+ banks = 0;
+ int location = -1;
+
+ for (int l = Constants.MaxAttributes - 1; l >= 0; l--)
+ {
+ if ((attributeUsage.UsedOutputAttributes & (1 << l)) == 0)
+ {
+ location = l;
+ break;
+ }
+ }
+
+ if (location < 0)
+ {
+ return -1;
+ }
+
+ // 1. What the position depends on: back from the values the position stores write, through every
+ // operation and phi that defines them.
+ HashSet<INode> slice = new();
+ Stack<Operand> work = new();
+ bool stores = false;
+
+ foreach (BasicBlock block in blocks)
+ {
+ for (LinkedListNode<INode> node = block.Operations.First; node != null; node = node.Next)
+ {
+ if (IsPositionStore(node.Value))
+ {
+ stores = true;
+ work.Push(((Operation)node.Value).GetSource(2));
+ }
+ }
+ }
+
+ if (!stores)
+ {
+ return -1;
+ }
+
+ while (work.Count != 0)
+ {
+ Operand v = work.Pop();
+
+ if (v == null || v.Type != OperandType.LocalVariable || v.AsgOp is not INode def || !slice.Add(def))
+ {
+ continue;
+ }
+
+ for (int s = 0; s < def.SourcesCount; s++)
+ {
+ work.Push(def.GetSource(s));
+ }
+ }
+
+ // 2. The banks the slice reads, and the bindings of those it loads with a computed offset to their
+ // last-frame slot's (only these get one: a binding is declared in the SPIR-V whether used or not, and the
+ // host's layout comes from the used ones). Direct operands (c[slot][offset]) get theirs when the
+ // structured program is made.
+ Dictionary<int, int> bindings = new();
+
+ foreach (INode n in slice)
+ {
+ if (n is Operation op && IsBankLoad(op, resourceManager, out int slot))
+ {
+ banks |= 1 << slot;
+
+ if (!bindings.ContainsKey(op.GetSource(0).Value))
+ {
+ bindings[op.GetSource(0).Value] = resourceManager.GetConstantBufferBinding(Remap(slot));
+ }
+ }
+
+ for (int s = 0; s < n.SourcesCount; s++)
+ {
+ Operand src = n.GetSource(s);
+
+ if (src != null && src.Type == OperandType.ConstantBuffer && Remap(src.GetCbufSlot()) >= 0)
+ {
+ banks |= 1 << src.GetCbufSlot();
+ }
+ }
+ }
+
+ if (banks == 0)
+ {
+ return -1;
+ }
+
+ // 3. Which of the slice's values depend on those banks, to a fixed point (phis carry it around loops).
+ HashSet<Operand> tainted = new();
+ bool changed = true;
+
+ while (changed)
+ {
+ changed = false;
+
+ foreach (BasicBlock block in blocks)
+ {
+ for (LinkedListNode<INode> node = block.Operations.First; node != null; node = node.Next)
+ {
+ INode n = node.Value;
+
+ if (!slice.Contains(n) || n.DestsCount == 0 || !Reads(n, tainted, bindings))
+ {
+ continue;
+ }
+
+ for (int d = 0; d < n.DestsCount; d++)
+ {
+ Operand dest = n.GetDest(d);
+
+ if (dest != null && dest.Type == OperandType.LocalVariable && tainted.Add(dest))
+ {
+ changed = true;
+ }
+ }
+ }
+ }
+ }
+
+ // 4. A copy of each such operation beside it, with new destinations.
+ Dictionary<Operand, Operand> prev = new();
+ List<(INode Original, INode Copy)> copies = new();
+
+ foreach (BasicBlock block in blocks)
+ {
+ for (LinkedListNode<INode> node = block.Operations.First; node != null; node = node.Next)
+ {
+ INode n = node.Value;
+
+ if (!slice.Contains(n) || n.DestsCount == 0 || !IsTainted(n, tainted))
+ {
+ continue;
+ }
+
+ INode copy = null;
+
+ if (n is PhiNode phi)
+ {
+ Operand dest = Local();
+ prev[phi.Dest] = dest;
+ copy = new PhiNode(dest);
+ }
+ else if (n is Operation op && op.GetType() == typeof(Operation) && op.Inst != Instruction.Store)
+ {
+ Operand[] dests = new Operand[op.DestsCount];
+
+ for (int d = 0; d < dests.Length; d++)
+ {
+ Operand dest = op.GetDest(d);
+ dests[d] = dest != null && dest.Type == OperandType.LocalVariable ? Local() : dest;
+
+ if (dest != null && dest.Type == OperandType.LocalVariable)
+ {
+ prev[dest] = dests[d];
+ }
+ }
+
+ Operand[] sources = new Operand[op.SourcesCount];
+
+ for (int s = 0; s < sources.Length; s++)
+ {
+ sources[s] = op.GetSource(s);
+ }
+
+ Operation c = op.StorageKind != StorageKind.None && dests.Length == 1
+ ? new Operation(op.Inst, op.StorageKind, dests[0], sources)
+ : new Operation(op.Inst, op.Index, dests, sources);
+ c.ForcePrecise = op.ForcePrecise;
+ copy = c;
+ }
+
+ if (copy != null)
+ {
+ node = block.Operations.AddAfter(node, copy);
+ copies.Add((n, copy));
+ }
+ }
+ }
+
+ // 5. The copies' sources: last frame's values, the remapped banks.
+ foreach ((INode original, INode copy) in copies)
+ {
+ if (copy is PhiNode phiCopy)
+ {
+ PhiNode phi = (PhiNode)original;
+
+ for (int s = 0; s < phi.SourcesCount; s++)
+ {
+ phiCopy.AddSource(phi.GetBlock(s), Prev(phi.GetSource(s), prev));
+ }
+
+ continue;
+ }
+
+ Operation op = (Operation)original, c = (Operation)copy;
+
+ for (int s = 0; s < op.SourcesCount; s++)
+ {
+ Operand src = op.GetSource(s);
+
+ if (s == 0 && op.Inst == Instruction.Load && op.StorageKind == StorageKind.ConstantBuffer &&
+ src.Type == OperandType.Constant && bindings.TryGetValue(src.Value, out int binding))
+ {
+ c.SetSource(s, Const(binding));
+ }
+ else if (src.Type == OperandType.ConstantBuffer && Remap(src.GetCbufSlot()) >= 0)
+ {
+ c.SetSource(s, Cbuf(Remap(src.GetCbufSlot()), src.GetCbufOffset()));
+ }
+ else
+ {
+ c.SetSource(s, Prev(src, prev));
+ }
+ }
+ }
+
+ // 6. Each position store also writes last frame's position to the output.
+ foreach (BasicBlock block in blocks)
+ {
+ for (LinkedListNode<INode> node = block.Operations.First; node != null; node = node.Next)
+ {
+ if (!IsPositionStore(node.Value))
+ {
+ continue;
+ }
+
+ Operation op = (Operation)node.Value;
+ Operation store = new(Instruction.Store, StorageKind.Output, null,
+ Const((int)IoVariable.UserDefined), Const(location), op.GetSource(1), Prev(op.GetSource(2), prev));
+ node = block.Operations.AddAfter(node, store);
+ }
+ }
+
+ attributeUsage.SetOutputUserAttribute(location);
+
+ return location;
+ }
+
+ private static bool IsPositionStore(INode n)
+ {
+ return n is Operation op && op.Inst == Instruction.Store && op.StorageKind == StorageKind.Output &&
+ op.SourcesCount == 3 && op.GetSource(0).Type == OperandType.Constant &&
+ (IoVariable)op.GetSource(0).Value == IoVariable.Position;
+ }
+
+ private static bool IsBankLoad(Operation op, ResourceManager resourceManager, out int slot)
+ {
+ slot = -1;
+
+ return op.Inst == Instruction.Load && op.StorageKind == StorageKind.ConstantBuffer &&
+ op.GetSource(0).Type == OperandType.Constant &&
+ resourceManager.TryGetConstantBufferSlot(op.GetSource(0).Value, out slot) && Remap(slot) >= 0;
+ }
+
+ private static Operand Prev(Operand src, Dictionary<Operand, Operand> prev)
+ {
+ return src != null && prev.TryGetValue(src, out Operand p) ? p : src;
+ }
+
+ private static bool IsTainted(INode n, HashSet<Operand> tainted)
+ {
+ for (int d = 0; d < n.DestsCount; d++)
+ {
+ if (n.GetDest(d) is Operand dest && tainted.Contains(dest))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static bool Reads(INode n, HashSet<Operand> tainted, Dictionary<int, int> bindings)
+ {
+ if (n is Operation op && op.Inst == Instruction.Load && op.StorageKind == StorageKind.ConstantBuffer &&
+ op.GetSource(0).Type == OperandType.Constant && bindings.ContainsKey(op.GetSource(0).Value))
+ {
+ return true;
+ }
+
+ for (int s = 0; s < n.SourcesCount; s++)
+ {
+ Operand src = n.GetSource(s);
+
+ if (src == null)
+ {
+ continue;
+ }
+
+ if (src.Type == OperandType.ConstantBuffer && Remap(src.GetCbufSlot()) >= 0)
+ {
+ return true;
+ }
+
+ if (tainted.Contains(src))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ }
+}
--- a/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs
+++ b/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs
@@ -301,6 +301,12 @@ namespace Ryujinx.Graphics.Shader.Translation
Optimizer.RunPass(context);
TransformPasses.RunPass(context);
+
+ if (i == 0 && Definitions.Stage == ShaderStage.Vertex && GpuAccessor.QueryMotionPrevious())
+ {
+ int location = MotionPrevious.Run(cfg.Blocks, resourceManager, AttributeUsage, out int banks);
+ GpuAccessor.ReportMotionPrevious(location, banks);
+ }
}
funcs[i] = new Function(cfg.Blocks, $"fun{i}", false, inArgumentsCount, outArgumentsCount);

View File

@@ -0,0 +1,71 @@
--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs
+++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Declarations.cs
@@ -33,8 +33,14 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
{
foreach (AstOperand local in function.Locals)
{
- SpvInstruction localPointerType = context.TypePointer(StorageClass.Function, context.GetType(local.VarType));
- SpvInstruction spvLocal = context.Variable(localPointerType, StorageClass.Function);
+ SpvInstruction localType = context.GetType(local.VarType);
+ SpvInstruction localPointerType = context.TypePointer(StorageClass.Function, localType);
+
+ // NX2NAVI: on hosts that ask for it (Mesa's compilers fold undefined values freely), a register read on a
+ // path that did not write it reads 0 instead of an undefined value.
+ SpvInstruction spvLocal = context.HostCapabilities.ZeroLocals
+ ? context.Variable(localPointerType, StorageClass.Function, context.ConstantNull(localType))
+ : context.Variable(localPointerType, StorageClass.Function);
context.AddLocalVariable(spvLocal);
context.DeclareLocal(local, spvLocal);
--- a/src/Ryujinx.Graphics.Shader/IGpuAccessor.cs
+++ b/src/Ryujinx.Graphics.Shader/IGpuAccessor.cs
@@ -188,6 +188,9 @@ namespace Ryujinx.Graphics.Shader
// the user output location it went to (-1: none) and the banks the position depends on (bit n: cn).
bool QueryMotionPrevious() => false;
+ // NX2NAVI: true when function-local variables start at 0 (CodeGen/Spirv/Declarations.cs DeclareLocals).
+ bool QueryZeroLocals() => false;
+
void ReportMotionPrevious(int location, int banks)
{
}
--- a/src/Ryujinx.Graphics.Shader/Translation/HostCapabilities.cs
+++ b/src/Ryujinx.Graphics.Shader/Translation/HostCapabilities.cs
@@ -12,6 +12,7 @@ namespace Ryujinx.Graphics.Shader.Translation
public readonly bool SupportsShaderNonUniformIndexing;
public readonly bool SupportsTextureShadowLod;
public readonly bool SupportsViewportMask;
+ public readonly bool ZeroLocals;
public HostCapabilities(
bool reducedPrecision,
@@ -23,7 +24,8 @@ namespace Ryujinx.Graphics.Shader.Translation
bool supportsShaderFloat64,
bool supportsShaderNonUniformIndexing,
bool supportsTextureShadowLod,
- bool supportsViewportMask)
+ bool supportsViewportMask,
+ bool zeroLocals)
{
ReducedPrecision = reducedPrecision;
SupportsFragmentShaderInterlock = supportsFragmentShaderInterlock;
@@ -35,6 +37,7 @@ namespace Ryujinx.Graphics.Shader.Translation
SupportsShaderNonUniformIndexing = supportsShaderNonUniformIndexing;
SupportsTextureShadowLod = supportsTextureShadowLod;
SupportsViewportMask = supportsViewportMask;
+ ZeroLocals = zeroLocals;
}
}
}
--- a/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs
+++ b/src/Ryujinx.Graphics.Shader/Translation/TranslatorContext.cs
@@ -372,7 +372,8 @@ namespace Ryujinx.Graphics.Shader.Translation
GpuAccessor.QueryHostSupportsShaderFloat64(),
GpuAccessor.QueryHostSupportsShaderNonUniformIndexing(),
GpuAccessor.QueryHostSupportsTextureShadowLod(),
- GpuAccessor.QueryHostSupportsViewportMask());
+ GpuAccessor.QueryHostSupportsViewportMask(),
+ GpuAccessor.QueryZeroLocals());
CodeGenParameters parameters = new CodeGenParameters(attributeUsage, definitions, resourceManager.Properties, hostCapabilities, GpuAccessor, Options.TargetApi);